Ultrasonic sensors use sound to determine the distance between the sensor and the closest object in its path. The sensor sends out a sound wave at a specific frequency. It then listens for that specific sound wave to bounce off of an object and come back. The sensor keeps track of the time between sending the sound wave and the sound wave returning.
Let’s initialize the sensor with 10µs pulse. Wait until ECHO pin goes high then start the timer. Wait until ECHO pin goes low then stop the timer. Let’s initialize the Timer0 with overflow vect. Since overflow gives only 32µs we have to calculate all the value. Our first target is to initialize the sensor
#include<avr/interrupt.h>
#define DDR_TR DDRB
#define DDR_ECHO DDRB
#define DDR_TR_PIN DDB4
#define DDR_ECHO_PIN DDB3
#define PORT_TR PORTB
#define PORT_TR_PIN PORTB4
#define PORT_ECHO PINB
#define PORT_ECHO_PIN PINB3
DDR_TR|=(1<<DDR_TR_PIN);
DDR_ECHO&=~(1<<DDR_ECHO_PIN);
sei();
TIMSK|=(1<<TOIE0);
uint8_t ultrasonic(void)
{
uint8_t value;
PORT_TR|=(1<<PORT_TR_PIN);
_delay_us(10);
PORT_TR&=~(1<<PORT_TR_PIN);
while(!(PORT_ECHO&(1<<PORT_ECHO_PIN)));
timer0_init();
while(PORT_ECHO&(1<<PORT_ECHO_PIN));
timer0_stop();
value=TCNT0;
return value;
}
#include<avr/io.h>
#include<util/delay.h>
#include<avr/interrupt.h>
#include"ultrasonic.h"
#include"lcd.h"
char str[40];
uint8_t time,overflow=1;
float distance;
int main(void)
{
LCD_INIT(); //LCD intilize
system_init();
LCD_write_string(1,1,"Object tracking");
while(1)
{
time=ultrasonic();
if(overflow==1){
distance=.5488*time;
}else if(overflow==2){
distance=.5488*time+140.5;
overflow=1;
}else if(overflow==3){
distance=.5488*time+281;
overflow=1;
}else if(overflow==4){
distance=.5488*time+421.5;
overflow=1;
}
sprintf(str,"Distance:%.4f",distance);
LCD_write_string(1,2,str);
_delay_ms(1000); //delay for LCD update
}
return 0;
}
ISR(TIMER0_OVF_vect)
{
overflow++;
}
We just introduce the basic object detection. You can use it for water level detection in a reservoir tank or any object nearby. We can also use it in mini radar technology that will be discussed in ARM section.