Maker Pro
Maker Pro

Programming Help

Gav1985

Mar 12, 2013
18
Joined
Mar 12, 2013
Messages
18
Hi everyone, I need help :D

I'm working with a PIC18F4550. The idea is to start and stop a timer (timer 0) and measure the time period.

I have a Astable Schmitt trigger providing an oscillating input to pin RB7 and I need to measure the time period of this oscillation.

So, the code I have looks like this...

HTML:
// Setup timer.
	T0CON = 0x04; ;				// Internal Clock src (Fosc/4), 1:8 prescaler   0.2uSx8 = 1.6uS Resolution
	INTCONbits.GIEH = 0;
	INTCONbits.TMR0IE = 1;
	INTCONbits.TMR0IF = 0;				

	x = PORTBbits.RB7; 			// Read pin state.
	while (x==PORTBbits.RB7){	// Wait until pin state change.
		_asm nop _endasm
	}

	T0CONbits.TMR0ON = 1; 		// Start the timer
	while (PORTBbits.RB7 != x){ 
		_asm nop _endasm
	}
	while (PORTBbits.RB7 == x){ 
		_asm nop _endasm
	}
	T0CONbits.TMR0ON = 0;		// Stop Timer

	// -- Workout tA - Period -- //			

	period = TMR0L;			// Read TMR0 Register
	period *=0.0000016;


The prescaler is set to a 1:8 resolution and this is more than adequate so that TM0L shouldn't overflow so I don't have to deal with interrupt flags.

While simulating this, Var period will work out to around 230 -260uS. Using breakpoints, MPLAB/proteus timestep tells me that the time elapsed between starting and stopping TIMER0 is around 330us. Roughly a 100uS discrepancy.

I should add, the digital oscilloscope doesn't produce a symmetric square wave which I put down to the limitations of the simulation software.

The Schmitt Trigger i'm using is HCC/HCF 40106b and there is a formula for working out the time period which is handy, I'm just struggling to get the code/simulator to produce a result which is even close to what the formula is telling me I should get.....

Thanks all.
 
Last edited:

KrisBlueNZ

Sadly passed away in 2015
Nov 28, 2011
8,393
Joined
Nov 28, 2011
Messages
8,393
I can't help much here, since I have no experience with PICs, but for measuring intervals, it's more usual (and more accurate) to use an input capture peripheral, as described in section 15 of the data sheet.
 

BobK

Jan 5, 2010
7,682
Joined
Jan 5, 2010
Messages
7,682
Try zeroing the timer just before turning it on.

bob
 
Top