Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
#define F_CPU 8000000L
#define rs_high PORTA |=(1<<6)//enabling lcd register high
#define rs_low PORTA &=~(1<<6)//enabling lcd register low
#define en_high PORTA |=(1<<7)//enabling lcd enable high
#define en_low PORTA &=~(1<<7)//enabling lcd enable low
#include // This header file includes the appropriate Input/output definitions for the device
#include // to use delay function we need to include this library
#include
#include // we'll be using itoa() function to convert integer to character array that resides in this library
#define Trigger_pin PB1
void lcd_cmd(unsigned char cmd)
{
PORTC = cmd;//giving cmd to the LCD
rs_low;//making register low
en_high;//making enable high
_delay_ms(1);
en_low;//making enable low
}
void lcd_data(unsigned char data)
{
PORTC = data;//giving data to the LCD
rs_high;//making register high
en_high;//making enable high
_delay_ms(1);
en_low;//making enable low
}
void lcd_init()
{
//Making lcd ready for displaying the output//
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 cursorpos(char x,char y)
{
if((x<1 || x>2)||(y<1 || y>16))//condtion check the 2 rows and 16 columns
{
x=1;
y=1;
}
if (x==1)
{
lcd_cmd(0x7F+y);//{80-1=7f} for starting the 1st line hex decimal value(80) y we r using means we need to dtart from that column
}
else
{
lcd_cmd(0xBF+y);//0c-1=0b for starting 2nd line,2nd row
}
}
void lcd_out(char a, char b,char *str)
{
cursorpos(a,b);//checking the cursor position or setting the position
while(*str)
{
lcd_data(*str);//sending the data to lcd function with string as argument
str++;
}
}
int Timeroverflow=0;
ISR(TIMER1_OVF_vect)
{
Timeroverflow++;/* Increment Timer Overflow count */
}
int main()
{
char dist[10];
long count;
double dis;
DDRB |=0b00000010; /* Make trigger pin as output */
DDRD&=~(1<<6);
PORTD |=(0b010000000);
DDRC |=0xFF;/* Make trigger pin as output */
DDRA |=0xFF;/* Make trigger pin as output */
lcd_init();
lcd_out(1,1,"Ultrasonic");
sei();/* Enable global interrupt */
TIMSK=(1< TCCR1A=0;/* Set all bit to zero Normal operation */
while(1)
{
/* Give 10us trigger pulse on trig. pin to HC-SR04 */
PORTB |=(1< _delay_ms(10);
PORTB &=(~(1< TCNT1=0;/* Clear Timer counter */
TCCR1B=0x41;/* Capture on rising edge, No prescaler*/
TIFR=(1< TIFR=(1< /*Calculate width of Echo by Input Capture (ICP) */
while ((TIFR &(1<
TCNT1=0; /*Clear Timer counter */
TCCR1B=0X01;/* Capture on falling edge, No prescaler */
TIFR=(1< TIFR=(1< Timeroverflow=0;/* Clear Timer overflow count */
while ((TIFR & (1 << ICF1))==0);/* Wait for falling edge */
count = ICR1 + (65535 * Timeroverflow); /* Take count */
/* 8MHz Timer freq, sound speed =343 m/s */
dis = (double)count / 466.47;
itoa(dis,dist,4);
lcd_out(2,1,dist);
lcd_out(2,5,"CM");
_delay_ms(10);
}
}