Challenge

Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)

#include // AVR main header file
#define F_CPU 16000000l
#include // this is a delay header file
#include // interrupt header file
#include //string header file
#include
#define lcd_data_dir DDRD //using DDRD data port direction
#define lcd_command_dir DDRC //this is command port direction
#define lcd_data_port PORTD
#define lcd_command_port PORTC
#define EN PC2 //lcd enable pin
#define RW PC3 //lcd read and write pin
#define RS PC4
#define trigger_pin PA0 //trigger pin port A0
void lcd_command(char); //command write function
void lcd_char(char); //data write function
void lcd_init(void); // initialize function for lcd
void lcd_string(char*); //send dtring to lcd function
void lcd_string_xy (char,char,char*); //send row postion
void lcd_command (char cmd)
{
lcd_data_port = cmd; //command to lcd
lcd_command_port&=~((1<lcd_command_port|= (1<_delay_ms(1);
lcd_command_port&=~(1<_delay_ms(2);
}
void lcd_char(char char_data)
{
lcd_data_port= char_data;
lcd_command_port&=~(1<lcd_command_port|=((1<pin high
_delay_ms(1);
lcd_command_port&=~(1<_delay_ms(1);
}
void lcd_init(void)
{
lcd_command_dir|= (1<pins are high
lcd_data_dir = 0xff;
_delay_ms(20);
lcd_command(0x38);//16x2 lcd 8 bit
lcd_command(0x0C);//display on
lcd_command(0x06);//auto incrment cursor
lcd_command(0x01);//clar lcd command
lcd_command(0x80);//8 is the line and postion
}
void lcd_string(char *str){ //string function
int i;
for(i=0;str[i]!=0;i++)
{
lcd_char (str[i]); // calling the lcd data write
}
}
void lcd_string_xy(char row,char pos,char *str)
{
if (row == 1)
lcd_command((pos & 0x0f)|0x80);
else if (row == 2)
lcd_command((pos & 0x0f)|(0xC0));
lcd_string(str); //call lcd string function
}
int TimerOverFlow = 0;
ISR(TIMER1_OVF_vect)
{
TimerOverFlow++; // making the overflow count
}
int main (void)
{
char string[10];
long count;
double distance;
DDRA = 0x01; // pin A0 is output
PORTB = 0xff; //portb all pin are high
lcd_init();
lcd_string_xy(1,0,"obj in ultrasonic"); // this is a position of string
sei(); //enable global interrupt
TIMSK = (1<< TOIE1); //TOIE1 setting high
TCCR1A = 0; //bit is 0 in normal position
while(1)
{
PORTA |= (1<< trigger_pin); //A0 is high
_delay_ms(10);
PORTA &=(~(1<< trigger_pin)); //A0 is low
TCNT1 = 0;
TCCR1B = 0x41;
TIFR = 1<TIFR = 1<while ((TIFR & (1<TCNT1 = 0;
TCCR1B = 0x01;
TIFR = 1<TIFR = 1<TimerOverFlow = 0;
while ((TIFR & (1<< ICF1))== 0);
count = ICR1 +(65535 * TimerOverFlow);
distance = (double)count/466.47;
dtostrf(distance,2,2,string);
strcat(string,"cm"); //units of distance
lcd_string_xy(2,0,"dist: "); // dist string
lcd_string_xy(2,7,string);
_delay_ms(200);
}
}

SIMU:-

OUTPUT:-

CODE:-

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.