Challenge

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

// Define pins

#define TRIG_PIN 9

#define ECHO_PIN 8

// Variables for capturing time

volatile unsigned long startTime;

volatile unsigned long endTime;

void setup() {

Serial.begin(9600);

// Setup pins

pinMode(TRIG_PIN, OUTPUT);

pinMode(ECHO_PIN, INPUT);

// Setup Timer 1 for Input Capture Mode

TCCR1A = 0; // Normal operation

TCCR1B = (1 << ICES1) | (1 << CS11); // Capture on rising edge, prescaler 8

TIMSK1 = (1 << ICIE1); // Enable input capture interrupt

sei(); // Enable global interrupts

}

void loop() {

// Send trigger signal

digitalWrite(TRIG_PIN, LOW);

delayMicroseconds(2);

digitalWrite(TRIG_PIN, HIGH);

delayMicroseconds(10);

digitalWrite(TRIG_PIN, LOW);

// Wait for echo

delay(100); // Adjust delay according to maximum distance

// Calculate distance

unsigned long duration = endTime - startTime;

float distance = duration * 0.034 / 2; // Speed of sound = 340 m/s

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

delay(1000);

}

// ISR for Input Capture Event

ISR(TIMER1_CAPT_vect) {

if (TCCR1B & (1 << ICES1)) {

startTime = ICR1; // Capture start time

TCCR1B &= ~(1 << ICES1); // Switch to falling edge

} else {

endTime = ICR1; // Capture end time

TCCR1B |= (1 << ICES1); // Switch to rising edge

}

}

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.