Simple HC-SR04 rangefinder example for Arduino Nano

// Simplified HC-SR04 rangefinder example for Arduino Nano
// This example switches on an LED when an object is closer
// than 68cm. It can easily be adapted to control motors. 
// Written by Ted Burke - last updated 3-10-2018

void setup()
  pinMode(2, OUTPUT); // Rangefinder trigger pin
  pinMode(3, INPUT);  // Rangefinder echo pin
  pinMode(7, OUTPUT); // LED pin

void loop()
  // Send trigger pulse to rangefinder
  digitalWrite(2, HIGH);
  digitalWrite(2, LOW);

  // Delay for 4ms (sound travels 136cm in 4ms - that's 2 x 68cm)
  if (digitalRead(3) == 0) // Only true if echo pulse has ended
    // An object must be within 68cm because the echo pulse
    // was shorter than 4ms, so switch on the LED
    digitalWrite(7, HIGH);
    // No object detected within 68cm because the echo pulse
    // is still active after 4ms, so switch off the LED
    digitalWrite(7, LOW);

  // Delay for 100ms before triggering next reading so that
  // all echos of previous ultrasonic pulse have died down

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s