Challenge

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

#include <avr/io.h>
#include <util/delay.h>

#define TRIG_PIN 2 // PD2
#define ECHO_PIN 3 // PD3

void init_sensor() {
// Set TRIG_PIN as output
DDRD |= (1 << TRIG_PIN);
// Set ECHO_PIN as input
DDRD &= ~(1 << ECHO_PIN);
// Enable pull-up resistor for ECHO_PIN
PORTD |= (1 << ECHO_PIN);
}

int measure_distance() {
// Send a 10us pulse on TRIG_PIN to trigger the sensor
PORTD |= (1 << TRIG_PIN);
_delay_us(10);
PORTD &= ~(1 << TRIG_PIN);

// Measure the duration of the pulse on ECHO_PIN
unsigned long pulse_start, pulse_end, pulse_duration;
while ((PIND & (1 << ECHO_PIN)) == 0);
pulse_start = micros();
while ((PIND & (1 << ECHO_PIN)) != 0);
pulse_end = micros();
pulse_duration = pulse_end - pulse_start;

// Calculate distance in cm using the speed of sound (343 m/s)
return pulse_duration * 343 / 20000;
}

int main() {
init_sensor();
while (1) {
int distance = measure_distance();
// Do something with the distance, such as displaying it on an LCD
}
return 0;
}

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.