Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Answer:
Code:
#include
#include
#include
#include
#include
#define F_CPU 16000000UL
#define LCD_DATA_DIR DDRD
#define LCD_COMMAND_DIR DDRC
#define LCD_DATA_PORT PORTD
#define LCD_COMMAND_PORT PORTC
#define ECHO_PIN PB1
#define TRIGGER_PIN PB0
#define EN PC2
#define RW PC3
#define RS PC4
void lcd_command(uint8_t cmd);
void lcd_char(uint8_t char_data);
void lcd_init(void);
void lcd_string(const char *str);
void lcd_string_xy(uint8_t row, uint8_t pos, const char *str);
volatile uint16_t TimerOverFlow = 0;
ISR(TIMER1_OVF_vect)
{
TimerOverFlow++;
}
void lcd_command(uint8_t cmd)
{
LCD_DATA_PORT = cmd;
LCD_COMMAND_PORT &= ~((1 << RS>
LCD_COMMAND_PORT |= (1 << EN>
_delay_ms(1);
LCD_COMMAND_PORT &= ~(1 << EN>
_delay_ms(2);
}
void lcd_char(uint8_t char_data)
{
LCD_DATA_PORT = char_data;
LCD_COMMAND_PORT &= ~(1 << RW>
LCD_COMMAND_PORT |= ((1 << EN>
_delay_ms(1);
LCD_COMMAND_PORT &= ~(1 << EN>
_delay_ms(1);
}
void lcd_init(void)
{
LCD_COMMAND_DIR |= (1 << RS>
LCD_DATA_DIR = 0xFF;
_delay_ms(20);
lcd_command(0x38); // Initialize LCD in 8-bit mode, 2 lines, 5x7 dots format
lcd_command(0x0C); // Display on, cursor off, blink off
lcd_command(0x06); // Entry mode - Increment cursor by 1, no display shift
lcd_command(0x01); // Clear display and return home
lcd_command(0x80); // Set cursor to the beginning of the first line
}
void lcd_string(const char *str)
{
for (uint8_t i = 0; str[i] != 0; i++)
{
lcd_char(str[i]);
}
}
void lcd_string_xy(uint8_t row, uint8_t pos, const char *str) {
if (row == 1)
lcd_command((pos & 0x0F) | 0x80);
else if (row == 2)
lcd_command((pos & 0x0F) | (0xC0));
// Clear the line
for (int i = 0; i < 16>
lcd_char(' ');
}
// Display the new string
lcd_command((pos & 0x0F) | 0x80);
lcd_string(str);
}
int main(void)
{
char string[10];
long count;
double distance;
DDRB |= (1 << TRIGGER>
PORTB = 0xFF; // Set all other pins as inputs with pull-up resistors
lcd_init();
sei(); // Enable global interrupts
TIMSK1 |= (1 << TOIE1>
TCCR1A = 0;
while (1)
{
// Simulate the trigger pulse
PORTB |= (1 << TRIGGER>
_delay_ms(100); // Simulate the trigger duration
PORTB &= ~(1 << TRIGGER>
// Simulate the ultrasonic sensor's response
_delay_ms(10); // Simulate the echo delay
// Simulate a response value
count = 3000; // Simulate a distance reading (adjust as needed for testing)
distance = (double)count / 466.47;
dtostrf(distance, 2, 2, string);
strcat(string, "cm");
lcd_string_xy(2, 0, "Dist: ");
lcd_string_xy(2, 10, string);
_delay_ms(200); // Simulate a delay before the next measurement
}
return 0;
}