Challenge

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


#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000UL
#include <util/delay.h>
#define lcdport PORTB // Defining the PORT B as Lcd port
#define rs_high PORTD|=(1<<2)
#define rs_low PORTD&=~(1<<2)
#define en_high PORTD|=(1<<3)
#define en_low PORTD&=~(1<<3)
sei; // Enabling the global input.


void lcd_cmd(unsigned char cmd)
{
lcdport=cmd;
rs_low;
en_low;
_delay_ms(1);
en_high;
}

void lcd_data(unsigned char data)
{
lcdport=data;
rs_high;
en_low;
_delay_ms(1);
en_high;
}

void lcd_init()
{
lcd_cmd(0x38);
_delay_ms(5);
lcd_cmd(0x02);
_delay_ms(5);
lcd_cmd(0x01);
_delay_ms(5);
lcd_cmd(0x0c);
_delay_ms(5);
lcd_cmd(0x06);
_delay_ms(5);
lcd_cmd(0x80);
_delay_ms(5);
}

void curs_pos(char x,char y)
{
if((x<1 || x>2) || (y<1 || y>16))
{
x=1;
y=1;
}
if(x==1)
lcd_cmd(0x7F+y);
else
lcd_cmd(0xBF+y);
}

void lcd_out(char x, char y,char *str)
{
curs_pos(x,y);
while(*str)
{

lcd_data(*str);
str++;
}

}
void lcd_print(char row, char col, unsigned int value,int digits)
{
unsigned int temp;
unsigned int unit;
unsigned int ten;
unsigned int hundred;
unsigned int thousand;
unsigned int million;

unsigned char flag = 0;

if (row==0||col ==0)
{
curs_pos(1,1);
}
else
{
curs_pos(row,col);
}

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;
ten = temp%10 + 48;
lcd_data(ten);
flag = 1;
}

if((digits==1) || (flag ==1))
{
unit = value%10 + 48;
lcd_data(unit);
}

if(digits>5)
{
lcd_data('e');
}

}


int main(void)
{
lcd_init();
DDRC |= (1<<1); // Setting the pin 1 as output pin
DDRD &= ~(1<<6); // Setting the IP capture pin as input
TCCR1B = 0x14;
TIMSK |= (1<<5); // Setting the bit 5 as output to enable the interrupt for input capture
while (1)
{
PORTC |= (1<<PINC1); // Emitting the signal with 15 ms delay.
_delay_ms(15);
PORTC &= ~(1<<PINC1);

}
}

ISR (TIMER1_CAPT_vect) // Interrupt function to capture the input signal
{
unsigned char value;
lcd_init();
value = read_register();

lcd_print(1,8,value,3);
}

int read_register() // Function to read the signal from ICR1 register.
{
unsigned int a,result;

a = ICR1L;
result = ICR1H;
result = result<<8;
result = result | a;
return result;

};

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.