Challenge

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

1.

#include <avr/io.h>

#include<avr/delay.h>

#define F_CPU 16000000L

#include<avr/interrupt.h>

#define lcdport 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_out(char x,char y,char *str);

void lcd_print(char row,char column,unsigned int value,int digits);

void lcd_command(unsigned char cmd)

{

lcdport = cmd;

rs_low;

en_high;

_delay_ms(1);

en_low;

}

void lcd_data(unsigned char data)

{

lcdport = data;

rs_high;

en_high;

_delay_ms(1);

en_low;

}

void lcd_init()

{

lcd_command(0x38);_delay_ms(500);

lcd_command(0x02);_delay_ms(500);

lcd_command(0x01);_delay_ms(5);

lcd_command(0x0c);_delay_ms(5);

lcd_command(0x06);_delay_ms(5);

lcd_command(0x80);_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(0x80+y);

else

lcd_command(0xC0+y);

}

void lcd_print(char row, char column, unsigned int value, int digits)

{

unsigned int temp;

unsigned int unit;

unsigned int tens;

unsigned int hundred;

unsigned int thousand;

unsigned int million;

unsigned char flag=0;

if(row==0||column==0)

{

cursorpos(1,1);

}

else

{

cursorpos(row,column);

}

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');

}

}

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

{

cursorpos(x,y);

while(*str)

{

lcd_data(*str);

str++;

}

}

int main(void)

{

DDRB=0xff;

DDRD |=(0<<6);

DDRD |=(1<<0);

sei();

lcd_init();

TCCR1A=0x00;

TIMSK |=(1<<2);

while (1)

{

PORTC|=(1<<0);

_delay_us(10);

PORTC&=~(1<<0);

TCCR1B=0x41;

TCNT1=0;

TIFR=(1<<ICF1);

TIFR=(1<<TOV1);

tov=0;

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

count=ICR1+(65535+tov);

distance=(unsigned int) count/932.87;

lcd_print(1,1,distance,4);

lcd_out(1,0,"cm");

}

}

ISR(TIMER1_OVF_vect)

{

tov++;

}

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.