Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
code:
#include <avr/io.h>
#define F_CPU 16000000L
#include <util/delay.h>
#define rs_high PORTD |=(1<<0);//DEFINE BIT FOR RS_HIGH
#define rs_low PORTD &=~(1<<0);//DEFINE BIT FOR RS_LOW
#define en_high PORTD |= (1<<2);//DEFINE BIT FOR EN_HIGH
#define en_low PORTD &=~(1<<2);//DEFINE BIT FOR EN_LOW
#define rw_high PORTD |= (1<<1);
#define rw_low PORTD &= ~(1<<1);
#define US_ERROR -1
#define US_NO_OBSTACLE -2
#define US_PORT PORTC
#define US_PIN PINC
#define US_DDR DDRC
int distance, previous_distance;
void lcd_cmd(unsigned char cmd)//LCD_COMMAND FUNCTION
{
PORTB = cmd;
rs_low;
rw_high;
en_high;
_delay_ms(1);
en_low;
}
void lcd_data(unsigned char data)//LCD DATA FUNCTION
{
PORTB = data;
rw_low;
rs_high;
en_high;
_delay_ms(1);
en_low;
}
void lcd_init()//LCD INITILIAZATION
{
rw_high;
rs_high;
en_high;
PORTB = 0xff;
lcd_cmd(0x38);
_delay_ms(5);
lcd_cmd(0x02);
_delay_ms(5);
lcd_cmd(0x01);
_delay_ms(5);
lcd_cmd(0x0c);
_delay_ms(5);
lcd_cmd(0x06);
_delay_ms(5);
lcd_cmd(0x80);
_delay_ms(5);
}
void cursorpos(char x,char y)//CURSOR POSITION FUNCTION
{
if((x<1 || x>2)||(y<1 || y>16))
{
x=1;
y=1;
}
if (x==1)
{
lcd_cmd(0x7F+y);
}
else
{
lcd_cmd(0xBF+y);
}
}
void lcd_out(char a, char b,char *str)//LCD OUT FUNCTION
{
cursorpos(a,b);
while(*str)
{
lcd_data(*str);
str++;
}
}
void lcd_clear()
{
lcd_cmd (0x01); // this line clears the LCD screen
_delay_ms(2); // waits for two milliseconds
lcd_cmd (0x80); // this line sets the cursor to the row 1 column 1
}
void HCSR04Init()
{
// we're setting the trigger pin as output as it will generate ultrasonic sound wave
US_DDR|=(1<<US_TRIG_POS);
}
void HCSR04Trigger()
{
US_PORT|=(1<<US_TRIG_POS); //high
_delay_us(15); //wait 15uS
US_PORT&=~(1<<US_TRIG_POS); //low
}
uint16_t GetPulseWidth()
{
for(i=0;i<600000;i++)
{
if(!(US_PIN & (1<<US_ECHO_POS)))
continue; //Line is still low, so wait
else
break;
}
if(i==600000)
return US_ERROR;
TCCR1A=0X00;
TCCR1B=(1<<CS11);
TCNT1=0x00;
for(i=0;i<600000;i++) s
{
if(US_PIN & (1<<US_ECHO_POS))
{
if(TCNT1 > 60000) break; else continue;
}
else
break;
}
if(i==600000)
return US_NO_OBSTACLE;
result=TCNT1;
TCCR1B=0x00;
if(result > 60000)
return US_NO_OBSTACLE;
else
return (result>>1);
}
int main()
{
lcd_init();
char numberString[4];
while(1) {
uint16_t r;
_delay_ms(100);
HCSR04Init();
while(1)
{
HCSR04Trigger();
r=GetPulseWidth();
if(r==US_ERROR)
{
cursorpos(1, 1);
char j[10] = "Error!";
lcd_out(1,1,&j);
}
else
{
distance=(r*0.034/2.0);
char f[15]= "Distance = ";
lcd_out(1,0,&f);
itoa(distance, numberString, 10);
lcd_out(2,4,numberString);
char h[6] = " cm";
lcd_out(2,10,&h);
previous_distance = distance;
_delay_ms(30);
}
}
}
}
Expected Outcomes:
The students will get the Knowledge on Ultrasonic sensor (HC-SR04)
to measure the distance travelled by wave to the object,
the hardware connection of Atmega328p and HC-SR04 and how to use
input capture mode of Timer1