Challenge

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

Dear Sir/Mam,

Please find the attached simulation and code

#define F_cpu 8000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>

#define LCD_Data_Dir DDRD //to define lcd data port direction
#define LCD_Command_Dir DDRC //to define lcd cmd port direction register
#define LCD_Data_Port PortD //LCD Port defining
#define LCD_Command_Port PORTC //To define sata port
#define EN PC2//Enable sig pin
#define RW PC3//read/wrt sig pin
#define RS PC4// Register select

void LCD_Command (char);
void LCD_Char (Char);
void LCD_Init (void);
void LCD_String (char*);
void LCD_String_xy (char,char,char*);//row,position,string to lcd

void LCD_Command (char cmd)
{
LCD_Data_Port = cmd;
LCD_Command_Port &= ~((1<<RS)|(1<<RW));
LCD_Command_Port |= (1<<EN);
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(3);
}

void LCD_Char (char char_data)
{
LCD_Data_Port = char_data;
LCD_Command_Port &= ~((1<<RW);
LCD_Command_Port |= (1<<EN)|(1<<RS);
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(1);
}

void LCD_Init (void)
{
LCD_Command_Dir &= ~((1<<RS)|(1<<RW)|(1<<EN);
LCD_Data_Dir = 0xFF;
_delay_ms(20);
LCD_Command (0x38);
LCD_Command (0x0C);
LCD_Command (0x06);
LCD_Command (0x01);
LCD_Command (0x80);
}

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 //Trigger pin

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_us(10);
PORTA |= (1 << Trigger_Pin);

TCNT1 = 0; //clear timer counter
TCCR1B = 0x41;
TIFR = 1<< ICF1; //clear icp flag
TIFR = 1<<T0V1; //clear timer overflow flag
TimerOverflow = 0;//Clear Timer overflow count

while ((TIFR & (1 << ICF1)) == 0);
count = ICR1 + (65535 * TimerOverflow);//take count
distance = (double)count/466.47;

dtostrf(distance,2,2 string); //distance to string
strcat(string, " cm "); //concat unit i.e.cm
LCD_String_xy(2, 0, "Dist = ");
LCD_String_xy(2, 7, string);//print distance
_delay_ms(200);
}
}

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.