Challenge

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

Instructor: Abinaya inbamani

Code:

#include <avr/io.h>
#define F_CPU 16000000L
#include <util/delay.h>
#include "avr/interrupt.h"

#define Lcd_Port PORTB
#define Rs_high PORTD|=(1<<0)
#define Rs_low PORTD&=~(1<<0)
#define En_high PORTD|=(1<<1)
#define En_low PORTD&=~(1<<1)
unsigned int tov=0,count,distance;
void Lcd_Command(unsigned char cmd);
void Lcd_data(unsigned char data);
void Lcd_init();
void cursorpos(char x, char y);
void Lcd_Print(char row,char coloumn,unsigned int value,int digits);
void Lcd_out(char x,char y,char *str);


int main(void)
{
DDRB=0xff; // portB as output
DDRD|=(0<<6); // PortD pin 6 as input from echo pin of sensor
DDRC|=(1<<0); //PortC as output

sei(); //enabling interrupt
Lcd_init();
TCCR1A=0x00;
TIMSK|=(1<<2);

while (1)
{
PORTC|=(1<<0); // trigger the sensor
_delay_ms(10);
PORTC&=~(1<<0);

TCCR1B=0x41; // ICF Enable,No prescaling.
TCNT1=0;
TIFR=(1<<ICF1);
TIFR=(1<<TOV1);
tov=0;

while((TIFR&(1<<ICF1))==0); // check timer overflow condition

TCNT1=0;
TCCR1B=0x01;
TIFR=(1<<ICF1);
TIFR=(1<<TOV1);

tov=0;
while((TIFR&(1<<ICF1))==0);
count = ICR1 + (65535*tov); // calculate the count for time taken
distance = (unsigned int)count/932.87; // sensor formula

Lcd_Print(1,1,distance,4);
Lcd_out(1,6,"cm");
}
}

ISR(TIMER1_OVF_vect)
{
tov++;
}
void Lcd_Command(unsigned char cmd)
{

Lcd_Port=cmd;
Rs_low;
En_low;
_delay_ms(1);
En_high;
}
void Lcd_data(unsigned char data)
{
Lcd_Port=data;
Rs_high;
En_low;
_delay_ms(1);
En_high;
}
void Lcd_init()
{
Lcd_Command(0x38);_delay_ms(5);
Lcd_Command(0x02);_delay_ms(5);
Lcd_Command(0x01);_delay_ms(5);
Lcd_Command(0x0c);_delay_ms(5);
Lcd_Command(0x06);_delay_ms(5);
Lcd_Command(0x80);_delay_ms(5);
Lcd_Command(0xC0);_delay_ms(5);
}
void cursorpos(char x, char y)
{
if ((x<1||x>2)||(y<1||y>16))
{
x=1;
y=1;
}
if (x==1)
Lcd_Command(0x7f+y);
else
Lcd_Command(0xbf+y);

}

void Lcd_out(char x,char y,char *str)
{
cursorpos(x,y);
while(*str)
{
Lcd_data(*str);
str++;
}
}
void Lcd_Print(char row, char coloumn, unsigned int value, int digits)
{
unsigned int temp,unit,tens,hundred,thousand,million;
unsigned char flag=0;
if(row==0||coloumn==0)
{
cursorpos(1,1);
}
else
{
cursorpos(row,coloumn);
}
if(digits==5|| flag==1)
{
million=value/10000+48;
Lcd_data(million);
flag=1;
}
if(digits==4 || flag==1)
{
temp = value/1000;
thousand = temp%10 +48;
Lcd_data(thousand);
flag=1;
}
if(digits==3 || flag==1)
{
temp = value/100;
hundred = temp%10 +48;
Lcd_data(hundred);
flag=1;
}
if(digits==2 || flag==1)
{
temp = value/10;
tens= temp%10 +48;
Lcd_data(tens);
flag=1;
}
if(digits==1 || flag==1)
{
unit = value%10 + 48;
Lcd_data(unit);
}
if(digits>5)
{
Lcd_data('e');
}
}

Output1:

Output2:

Output3:

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.