Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
#include
#include
// Function to initialize Timer 1 in Input Capture Mode
void timer1_init() {
// Set Timer 1 in Input Capture Mode with prescaler 8 (1 tick = 1 µs)
TCCR1B |= (1 << ICNC1) | (1 << ICES1) | (1 << CS11);
// Enable Input Capture Interrupt
TIMSK1 |= (1 << ICIE1);
// Enable Global Interrupts
sei();
}
volatile uint16_t pulse_width = 0;
int main() {
// Set Trig pin as output
DDRB |= (1 << DDB0);
// Set Echo pin as input
DDRD &= ~(1 << DDD6);
// Initialize Timer 1
timer1_init();
while (1) {
// Send ultrasonic pulse by setting Trig pin high for at least 10 µs
PORTB |= (1 << PORTB0);
_delay_us(10);
PORTB &= ~(1 << PORTB0);
// Calculate the distance using pulse width (assuming speed of sound in air as 343 m/s)
float distance_cm = pulse_width * 0.017; // 1 tick = 1 µs, 1 cm = 0.017 µs (343 m/s)
// Use the distance value as needed for further processing or display
// Wait for some time before measuring the distance again
_delay_ms(100);
}
return 0;
}
// Interrupt Service Routine (ISR) for Timer 1 Input Capture
ISR(TIMER1_CAPT_vect) {
// Capture the pulse width (in microseconds)
static uint16_t start_time = 0;
pulse_width = ICR1 - start_time;
start_time = ICR1;
}