Connect with us

Programming Help

Discussion in 'Microcontrollers, Programming and IoT' started by Gav1985, Apr 28, 2013.

Scroll to continue with content
  1. Gav1985


    Mar 12, 2013
    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...

    // 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: Apr 28, 2013
  2. KrisBlueNZ

    KrisBlueNZ Sadly passed away in 2015

    Nov 28, 2011
    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.
  3. BobK


    Jan 5, 2010
    Try zeroing the timer just before turning it on.

  4. Gav1985


    Mar 12, 2013
    Thanks Bobk.
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day