Challenge

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

/*

* main.c

*

* Created: 1/2/2024 8:45:48 PM

* Author: GOURAV SANKADIA

*/

#include <avr/io.h>

//#include <avr/dtostrf.h>

#define F_CPU 16000000UL

#include <avr/interrupt.h>

#include <string.h>

#include <stdlib.h>

#include <util/delay.h>

#define F_CPU 16000000UL

#define trigpin PA0

#define echopin PC7

//timer delay

//********//lcd rs and en declaration//**********

#define rs_high() PORTD |=(1<<2);

#define rs_low() PORTD &= ~(1<<2);

#define en_high() PORTD |= (1<<3);

#define en_low() PORTD &= ~(1<<3);

//*****lcd data pin configuration//******

#define lcdport PORTB

//******lcd in command mode//*********

void lcd_command(unsigned char cmd)

{

lcdport = cmd;

rs_low();

en_high();

_delay_ms(1);

en_low();

}

//**********lcd in data mode//*******

void lcd_data(unsigned char data)

{

lcdport = data;

rs_high();

en_high();

_delay_ms(1);

en_low();

}

//********initialisation of lcd//********

void lcd_init()

{

DDRD=0xFF;

DDRB=0xFF;

lcd_command(0x38);_delay_ms(5);//2 lines

lcd_command(0x02);_delay_ms(5);//return home

lcd_command(0x01);_delay_ms(5);//clearscreen

lcd_command(0x0c);_delay_ms(5);//display on

lcd_command(0x06);_delay_ms(5);//increament cursor

lcd_command(0x80);_delay_ms(5);//force cursor begin to first line

lcd_command(0xC0);_delay_ms(5);//force cursor to second line

}

//********cursor position//*********

void cursorpos(char x, char y)//row=x,column=y

{

if( (x < 1 || x > 2) || (y < 1 || y > 16) )

{

x = 1;

y = 1;

}

if(x == 1)

lcd_command(0x80+y);

else

lcd_command(0xC0+y);

}

//******lcd print function******

void lcd_print(char row, char coloumn, double value)

{

if(row==0||coloumn==0)

{

cursorpos(1,1);

}

else

{

cursorpos(row,coloumn);

}

}

void lcd_out(char x,char y,const char *str)

{

cursorpos(x,y);

while(*str)

{

lcd_data(*str);

str++;

}

}

int TOF = 0;//timer overflow

ISR(TIMER1_OVF_vect)

{

TOF++;

}

int main (void)

{

//char dist_value[10];

long count;

double distance;

DDRA = 0b00000001;

lcd_init();

lcd_out(1,1,"ultrasonic");

sei();

TIMSK = (1<< TOIE1);

TCCR1A = 0;

while(1)

{

PORTC |= (1<< trigpin);

_delay_ms(10);

PORTC &=(~(1<< trigpin));

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;

TOF = 0;

while ((TIFR & (1<< ICF1))== 0);

count = ICR1 +(65535 * TOF);

distance = (double)count/466.47;

//dtostrf(distance,2,2,dist_value);

//strcat(dist_value,"cm");

lcd_out(2,1,"dist= ");

lcd_print(2,7,distance);

_delay_ms(200);

}

return 0;

}

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.