ULTRA SONIC SENSOR READING IN MIKROC FOR PIC16F877A

Photo of author

By Jackson Taylor

/*
——-calculation———–
speed of sound = 340.29 m/sec.
Here the total distance travelled by sound = sum of
distance from sensor to object and object to sensor.
But both are same . so we need only one distance.
then speed become 170.15 m/sec.
converts m/sec to cm/microseconds.
then (170*100)/1000000 = 0.01715cm/us.
from above equation time taken to
travel distance 1CM= 1/0.01715cm = 58.3us.
—WIRING—–
 VCC to  5v
 GND to  GND
 Echo to  pin B0
 Trig to  pin B1
 */
 int c1=0;
 char distance[8];
 void usinit(void);
 void uscheck(void);
// LCD module connections
sbit LCD_RS at RD2_bit;
sbit LCD_EN at RD3_bit;
sbit LCD_D4 at RD4_bit;
sbit LCD_D5 at RD5_bit;
sbit LCD_D6 at RD6_bit;
sbit LCD_D7 at RD7_bit;
sbit LCD_RS_Direction at TRISD2_bit;
sbit LCD_EN_Direction at TRISD3_bit;
sbit LCD_D4_Direction at TRISD4_bit;
sbit LCD_D5_Direction at TRISD5_bit;
sbit LCD_D6_Direction at TRISD6_bit;
sbit LCD_D7_Direction at TRISD7_bit;
// End LCD module connections
void main(){
  Lcd_Init();                        // Initialize LCD
  Lcd_Cmd(_LCD_CLEAR);               // Clear display
  Lcd_Cmd(_LCD_CURSOR_OFF);          // Cursor off
  usinit();
  while(1)
  {      Lcd_Cmd(_LCD_CLEAR);
         Lcd_Out(2,1,distance);
          uscheck();
  }
}
void uscheck(void)
{
 portb.f1=1  ;
  delay_us(10);
   portb.f1=0  ;
   while(!portb.f0);
   c1=0;
   while(portb.f0) {c1++;  delay_us(58); }        // 1CM ==58US
      IntToStr(c1, distance);
      delay_ms(200);
}
void usinit(void)
{
      trisb.f0=1; //echoPin
      trisb.f1=0;   //trigPin
}

See also
MSP430-assembly language part-2.1-TIMER