Ultrasonic module for PIC

I was searching for a mikroC code written for ultrasonic module HC-SR04 ultrasonic module, but had to write it from scratch. Sharing it.

RB3 pin is used as an input and is connected to echo pin of ultrasonic module  RB4 pin is used as an output and is connected to trig pin of ultrasonic module. PortC is used as a indicator, Connect some LEDs

float temp; //This variable is used for calculations
unsigned cnt; //This variable is used to store the number of TMR0 overflows.

void interrupt() {

if(intcon.t0if) // TMR0 has been overflowed
{
    cnt++;                    // Interrupt causes cnt to be incremented by 1
}
INTCON = 0b10100000;   // Clearing flags
}

void main()
{
    INTCON = 0b10100000;  //GIE set, TMR0 Overflow Interrupt Set
    //TMR0 Settings
    OPTION_REG.T0CS = 0;
    OPTION_REG.PSA = 0;
    OPTION_REG.PS2 = 0;
    OPTION_REG.PS1 = 0;
    OPTION_REG.PS0 = 0;

  TRISB.F3 = 1; //RB3 pin is used as an input and is connected to echo pin of ultrasonic module
  TRISB.F4 = 0; //RB4 pin is used as an output and is connected to trig pin of ultrasonic module
  TRISC=0; //PortC is used as a indicator, Connect some LEDs
while(1)
{

  PORTB.F4 = 1; //set ultrasonic trig pin to high state
  delay_us(10);
  PORTB.F4 = 0; //clear ultrasonic trig pin to low state
  while(PORTB.F3 == 0); //wait till echo pin gets high.

  cnt = 0;
  TMR0 = 0;  // start the stop watch
  while(PORTB.F3 == 1);     // wait till the echo is off

  temp = cnt*256; //the counter increments at TMR0 overflow(256)
  temp = temp + TMR0; //total time in cycles
  //multiplying with velocity of sound, 
  //But needs to divide by to because the total time is for the signal to hit some object and reflect
  temp = temp * 340 /2;  
  //Oscilator used is 20MHz, Instruction cycle is 20MHz/4 = 5MHz, 
  //To get the time in seconds devide by 5*10^6
  temp = temp *0.2;   
  temp = temp/1000000 ; //By now temp has distance in meters 

  //The following code is just a indicator. For 30cm. 
  if(temp<0.3) PORTC = 255; 
  if(temp>0.3) PORTC = 0; 

} 

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: