Arduino

Distance Sensor (HC-SR04)

Layout
circuit diagram circuit board
Source-code
        
#define trig 13
#define echo 12
#define led_grd 8
#define led_blue 9
#define led_green 10
#define led_red 11
#define led_board 13
#define speed false

void setup() {
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(led_red, OUTPUT);
  pinMode(led_green, OUTPUT);
  pinMode(led_blue, OUTPUT);
  pinMode(led_grd, OUTPUT);
  digitalWrite(led_grd, LOW);
}

long span, distance, tmp;
int led;

void loop() {
  delayMicroseconds(20);
  digitalWrite(trig, HIGH);
  delayMicroseconds(2);
  digitalWrite(trig, LOW);

  span = pulseIn(echo, HIGH);
  distance = (span / 2) / 29.1;

  if (tmp != distance) {
    digitalWrite(led, LOW);
    digitalWrite(led_board, HIGH);

    if (distance <= 10) led = led_red;
    if (distance > 10) led = led_green;
    if (distance >= 200) led = led_blue;

    if (distance < tmp) 
      Serial.println(String("Approaching:  ") += (String(distance) += " cm"));
    if (distance > tmp) 
      Serial.println(String("Disappearing: ") += (String(distance) += " cm"));
    # object-speed without signal runtime
    if (speed)
      Serial.println(String("Speed: ") += String(abs(distance - tmp) * 2) += " cm/sec" );
    tmp = distance;
  }

  digitalWrite(led, HIGH);

  if (!speed && distance <= 20 && distance > 3) {
    delay(distance * 12.5);
    digitalWrite(led, LOW);
    delay(distance * 12.5);
  } else delay(480);

  digitalWrite(led_board, LOW);
}