Challenge

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

#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>

#define LCD_Data_Dir DDRD // LCD data port
#define LCD_Command_Dir DDRC // LCD command port
#define LCD_Data_Port PORTD // LCD data port
#define LCD_Command_Port PORTC // LCD data port
#define EN PC2 // Enable signal pin
#define RW PC3 // Read/Write signal pin
#define RS PC4 //Register Select

void LCD_Command (char); // command write
void LCD_Char (char); // data write
void LCD_Init (void); // LCD Initialize
void LCD_String (char*); //string function
void LCD_String_xy (char,char,char*); //row, position and string

void LCD_Command (char cmd)
{
LCD_Data_Port = cmd; // command data to LCD data
LCD_Command_Port &= ~((1<<RS)|(1<<RW)); // RS LOW, RW LOW
LCD_Command_Port |= (1<<EN);
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(3);
}

void LCD_Char (char char_data)
{
LCD_Data_Port = char_data; //data to LCD
LCD_Command_Port &= ~(1<<RW); // Make RW LOW
LCD_Command_Port |= (1<<EN)|(1<<RS); //RS and EN HIGH
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(1);
}

void LCD_Init (void)
{
LCD_Command_Dir |= (1<<RS)|(1<<RW)|(1<<EN); // output
LCD_Data_Dir = 0xFF; // output

_delay_ms(15);
LCD_Command (0x38);
LCD_Command (0x0C);
LCD_Command (0x06);
LCD_Command (0x01);
LCD_Command (0x80);
}

void LCD_String (char *str)
{
int i;
for(i=0;str[i]!=0;i++)
{
LCD_Char (str[i]); // LCD data
}
}

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);
}
#define Trigger_pin PA0

int TimerOverflow = 0;

ISR(TIMER1_OVF_vect)
{
TimerOverflow++; //count
}

int main(void)
{
char string[10];
long count;
double distance;

DDRA = 0x01; //output
PORTB = 0xFF; //Pull-up

LCD_Init();
LCD_String_xy(1, 0, "Helloi");

sei();
TIMSK = (1 << TOIE1);
TCCR1A = 0;

while(1)
{
PORTA |= (1 << Trigger_pin);
_delay_us(10);
PORTA &= (~(1 << Trigger_pin));

TCNT1 = 0; //Timer counter
TCCR1B = 0x41; //rising edge
TIFR = 1<<ICF1; // ICP flag
TIFR = 1<<TOV1; // Timer Overflow flag

while ((TIFR & (1 << ICF1)) == 0);
TCNT1 = 0; //Timer counter
TCCR1B = 0x01; // falling edge
TIFR = 1<<ICF1; // ICP flag
TIFR = 1<<TOV1; // Timer Overflow flag
TimerOverflow = 0; // Timer overflow count

while ((TIFR & (1 << ICF1)) == 0); // falling edge
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, 7, string);
_delay_ms(200);
}
}

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.