2 HC-SR04 Ping distance sensor]
3 VCC to arduino 5v GND to arduino GND
4 Echo to Arduino pin 13 Trig to Arduino pin 12
5 Red POS to Arduino pin 11
6 Green POS to Arduino pin 10
7 560 ohm resistor to both LED NEG and GRD power rail
8 More info at: http://goo.gl/kJ8Gl
9 Original code improvements to the Ping sketch sourced from Trollmaker.com
10 Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar
20 pinMode(trigPin, OUTPUT);
21 pinMode(echoPin, INPUT);
23 pinMode(GREEN, OUTPUT);
27 long duration, distance;
28 digitalWrite(trigPin, LOW); // Prepare for ping
29 delayMicroseconds(2); //
30 digitalWrite(trigPin, HIGH); // Send a ping
31 delayMicroseconds(10); //
32 digitalWrite(trigPin, LOW); // Set down ping
33 duration = pulseIn(echoPin, HIGH);
34 distance = (duration/2) / 29.1; // Speed is ~300m/s,
35 // so it takes ~29.1 milliseconds for a cm.
36 // Distance is half of (out + back)
37 if (distance < 5) { // This is where the LED On/Off happens
38 digitalWrite(RED,HIGH); // When the Red condition is met, the Green LED should turn off
39 digitalWrite(GREEN,LOW);
42 digitalWrite(RED,LOW);
43 digitalWrite(GREEN,HIGH);
45 if (distance >= 200 || distance <= 0){
46 Serial.println("Out of range");
49 Serial.print(distance);
50 Serial.println(" cm");