Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
#include <avr/io.h>
#define F_CPU 16000000UL
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>
// Define LCD port and pin configurations
#define LCD_DDR DDRD
#define LCD_PORT PORTD
#define RS PD0
#define EN PD1
void lcd_command(unsigned char cmnd);
void lcd_char(unsigned char data);
void lcd_init(void);
void lcd_string(char *str);
void lcd_string_xy(char row, char pos, char *str);
void lcd_command(unsigned char cmnd) {
LCD_PORT = (LCD_PORT & 0x0F) | (cmnd & 0xF0);
LCD_PORT &= ~ (1<<RS);
LCD_PORT |= (1<<EN);
_delay_us(1);
LCD_PORT &= ~ (1<<EN);
_delay_us(200);
LCD_PORT = (LCD_PORT & 0x0F) | (cmnd << 4);
LCD_PORT |= (1<<EN);
_delay_us(1);
LCD_PORT &= ~ (1<<EN);
_delay_ms(2);
}
void lcd_char(unsigned char data) {
LCD_PORT = (LCD_PORT & 0x0F) | (data & 0xF0);
LCD_PORT |= (1<<RS);
LCD_PORT |= (1<<EN);
_delay_us(1);
LCD_PORT &= ~ (1<<EN);
_delay_us(200);
LCD_PORT = (LCD_PORT & 0x0F) | (data << 4);
LCD_PORT |= (1<<EN);
_delay_us(1);
LCD_PORT &= ~ (1<<EN);
_delay_ms(2);
}
void lcd_init(void) {
LCD_DDR = 0xFF;
_delay_ms(20);
lcd_command(0x02);
lcd_command(0x28);
lcd_command(0x0c);
lcd_command(0x06);
lcd_command(0x01);
_delay_ms(2);
}
void lcd_string(char *str) {
int i;
for(i = 0; str[i] != 0; i++) {
lcd_char(str[i]);
}
}
void lcd_string_xy(char row, char pos, char *str) {
if (row == 1)
lcd_command((pos & 0x0F) | 0x80);
else if (row == 2)
lcd_command((pos & 0x0F) | 0xC0);
lcd_string(str);
}
// HC-SR04 Ultrasonic Sensor pins
#define TRIG_PIN PB0
#define ECHO_PIN PB1
volatile int TimerOverflow = 0;
ISR(TIMER1_OVF_vect) {
TimerOverflow++;
}
int main(void) {
char string[10];
long count;
double distance;
DDRB = (1<<TRIG_PIN);
PORTB = 0xFF;
lcd_init();
lcd_string_xy(1, 0, "Ultrasonic");
sei();
TIMSK1 = (1 << TOIE1);
TCCR1A = 0;
while(1) {
PORTB |= (1<<TRIG_PIN);
_delay_us(10);
PORTB &= ~(1<<TRIG_PIN);
TCNT1 = 0;
TCCR1B = 0x41;
TIFR1 = 1<<ICF1;
TIFR1 = 1<<TOV1;
while ((TIFR1 & (1<<ICF1)) == 0);
TCNT1 = 0;
TCCR1B = 0x01;
TIFR1 = 1<<ICF1;
TIFR1 = 1<<TOV1;
TimerOverflow = 0;
while ((TIFR1 & (1<<ICF1)) == 0);
count = ICR1 + (65535 * TimerOverflow);
distance = (double)count / 466.47;
dtostrf(distance, 2, 2, string);
strcat(string, " cm");
lcd_string_xy(2, 0, "Dist= ");
lcd_string_xy(2, 6, string);
_delay_ms(200);
}
}