Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
#Project 02
/*
* Project 02.c
*
* Created: 16-04-2023 11:37:27
* Author : night(Ambrose Joseph)
*/
#include <avr/io.h>
#define F_CPU 16000000UL
#include <util/delay.h>
#include <avr/interrupt.h>
#define lcd DDRD // define lcd data port direction
#define lcd_cmd_dir DDRC // define lcd command port direction
#define lcd_data PORTD //define lcd data port
#define lcd_cmd_port PORTC // define lcd data port
#define EN PC2 // define enable
#define RW PC3 // define read/write
#define RS PC4 // define register select
void lcd_command(char); // lcd command write function
void lcd_char(char); // lcd data write function
void lcd_init(void); // lcd initialize function
void lcd_string(char*); // send string to lcd
void lcd_string_xy(char,char,char*); // send row position
void lcd_command(char cmd) // lcd command write function
{
lcd_data = cmd; // write command to lcd data port
lcd_cmd_port&=~((1<<RS)|(1<<RW)); // make RS low and RW low
lcd_cmd_port|=(1<<EN); // high to low transition on EN
_delay_ms(1);
lcd_cmd_port&=~(1<<EN);
_delay_ms(2); // delay provided
}
void lcd_char(char char_data)
{
lcd_data=char_data; // write data to lcd data port
lcd_cmd_port&=~(1<<RW); // make RW low(write)
lcd_cmd_port|=((1<<EN)|(1<<RW)); // make RS high and high to low tnasition
_delay_ms(1);
lcd_cmd_port&=~(1<<EN);
_delay_ms(1);
}
void lcd_init(void)
{
lcd_cmd_dir|=((1<RS)|(1<<RW)|(1<<EN)); // lcd command port direction as output
lcd_cmd_dir=0xFF; //make lcd data port direction as output
_delay_ms(20);
lcd_command(0x38); // 16x2 lcd 8 bit
lcd_command(0x0C); // display On
lcd_command(0x06); // auto increment cursor
lcd_command(0x01); // clear lcd command
lcd_command(0x80); // 8 is the line and 0 is 0th position
}
void lcd_string(char*str)
{
int i;
for(i=0;str[i]!=0;i++)
{
lcd_char(str[i]);
}
}
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);
}
#define trigger_pin PA0
int TimerOverFlow = 0;
ISR(TIMER1_OVF_vect)
{
TimerOverFlow++;
}
int main(void)
{
char string[10];
long count;
double distance;
DDRA = 0x01;
PORTB = 0xFF;
lcd_init();
lcd_string_xy(1,0,"Ultrasonic");
sei();
TIMSK=(1<<TOIE1);
TCCR1A=0;
while (1)
{
PORTA|=(1<<trigger_pin);
_delay_ms(10);
PORTA&=~(1<<trigger_pin);
TCNT1 = 0;
TCCR1B = 0x41;
TIFR = 1<<ICF1;
TIFR = 1<<TOV1;
while((TIFR&(1<<ICF1))==0);
TCNT1=0;
TCCR1B=0x01;
TIFR = 1<<ICF1;
TIFR = 1<<TOV1;
TimerOverFlow=0;
while((TIFR&(1<<ICF1))==0);
count=ICR1 + (65535*TimerOverFlow);
distance=(double)count/466.47;
dtostrf(distance,2,2,string);
strcat(string,"cm");
lcd_string_xy(2,0,"dist=");
lcd_string_xy(2,7,string);
_delay_ms(200);
}
}