Example code for rangefinder testing

// HC-SR04 rangefinder testing - written by Ted Burke 11-4-2018

int echo_pin      = 2;
int trigger_pin   = 3;
int green_LED_pin = 4;
int red_LED_pin   = 5;

void setup()
  // Set i/o pins
  pinMode(echo_pin, INPUT);
  pinMode(trigger_pin, OUTPUT);
  pinMode(green_LED_pin, OUTPUT);
  pinMode(red_LED_pin, OUTPUT);

void loop()
  // Send trigger pulse
  digitalWrite(trigger_pin, HIGH);
  digitalWrite(trigger_pin, LOW);

  // Wait for 4ms (68cm return trip at speed of sound)

  // Check if echo pulse is still active
  if (digitalRead(echo_pin) == 1)
    // Echo pulse still active: no object within distance
    digitalWrite(green_LED_pin, LOW);
    digitalWrite(red_LED_pin, HIGH);
    // Echo pulse has ended: an object is within distance
    digitalWrite(green_LED_pin, HIGH);
    digitalWrite(red_LED_pin, LOW);

  // Wait 100 ms before triggering sensor again
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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