Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
//ANSWER//
#include <avr/interrupt.h>
#include <string.h>
#include <stdlib.h>
#include <avr/io.h>
#define F_CPU 16000000L
#include "avr/interrupt.h"
#include <util/delay.h>
#define lcd_port PORTB
#define rs_high PORTC |= (1<<4) //Register Select(RS)
#define rs_low PORTC &=~ (1<<4)
#define en_high PORTC |= (1<<2) //Enable
#define en_low PORTC &=~ (1<<2)
unsigned char i, channel;
#define tri_pin PA0
int TimerOverFlow = 0;
void lcd_cmd(char cmd)
{
lcd_port = cmd;
rs_low;
en_high;
_delay_ms(1);
en_low;
_delay_ms(1);
}
void lcd_data (char data)
{
lcd_port = data;
rs_high;
en_high;
_delay_ms(2);
en_low;
_delay_ms(2);
}
void lcd_init()
{
lcd_cmd(0x38);//2 lines 5x7 matrix _delay_ms(5); lcd_cmd(0x01);//Clearing screen _delay_ms(5); lcd_cmd(0x0c);//Display on ,cursor off _delay_ms(5); lcd_cmd(0x06);//Incrementing cursor _delay_ms(5); lcd_cmd(0x80);//Force cursor begin 1st line _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_cmd(0x7F+y);
}
else
{
lcd_cmd(0xBF+y);
}
}
void lcd_out(char x, char y, char *str)
{
cursorpos(x,y);
while(*str)
{
lcd_data(*str);
str++;
}
}
ISR(TIMER1_OVF_vect) { TimerOverFlow++; }
int main (void)
{
char string[10];
long count;
double distance;
DDRA = 0x01;
DDRB = 0xff;
lcd_init();
sei();
TIMSK = (1<< TOIE1);
TCCR1A = 0;
DDRC = 0xff;
PORTC = 0xff;
while(1)
{
PORTA |= (1<< tri_pin);
_delay_us(10);
PORTA &=(~(1<< tri_pin));
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;
TimerOverFlow = 0;
while ((TIFR & (1<< ICF1))== 0);
count = ICR1 +(65535 * TimerOverFlow);
distance = (double)count/466.47;
dtostrf(distance,2,2,string);
strcat(string,"cm");
lcd_out(2,0,"dist= ");
lcd_out(2,7,string);
_delay_us(10);
}
}