Link to home
Start Free TrialLog in
Avatar of vpool
vpool

asked on

PIC16f877

Hi Steveiam

This is my function for reading distance...

I want to send 10 pulse burst of 40 KHZ

could you please tell me corrections please

//pIc running at 4MHZ

#define trig RB0

unsigned int read_distance(int)
{
      TMR1H = 0xff;                                    // prepare timer for 25uS pulse
      TMR1L = -14;
      T1CON = 0x21;                                          // 1:* prescale and running
      int i=10;                              
      do
      {
      TMR1IF = 0;      
      trig = 1;                                    // start trigger pulse
      while(!TMR1IF);                              // wait
      trig = 0;                                          // end trigger pulse
      TMR1ON = 0;                                          // stop timer
      i--;
      }
      while(i<10);                                          
      TMR1H = 0;                                          // prepare timer to measure echo pulse
      TMR1L = 0;
      T1CON = 0x20;                                    // 1:* prescale but not running yet
      TMR1IF = 0;
      while(!echo && !TMR1IF);            // wait for echo pulse to start (go high)
      TMR1ON = 1;                                          // start timer to measure pulse
      while(echo && !TMR1IF);                  // wait for echo pulse to stop (go low)
      TMR1ON = 0;                                          // stop timer
      return (TMR1H<<8)+TMR1L;            // TMR1H:TMR1L contains flight time of the pulse in *** uS units
      
}
Avatar of WelkinMaze
WelkinMaze

Hi,
What is your problem? Do you receive some compilation error or something else is wrong?
At my first glance I see the following:
In the following code you initialize i with 10 then decrease it with i-- and finally check in the while statement if it is <10. I think you should check in the while statement if i>0 not if i<10

     int i=10;                        
     do
     {
     TMR1IF = 0;    
     trig = 1;                              // start trigger pulse
     while(!TMR1IF);                         // wait
     trig = 0;                                   // end trigger pulse
     TMR1ON = 0;                                   // stop timer
     i--;
     }
     while(i<10);
ASKER CERTIFIED SOLUTION
Avatar of steveiam
steveiam

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial