]> git.piffa.net Git - sketchbook_andrea/blob - hardware/ultrasonic/ultrasonic_distance_simple/ultrasonic_distance_simple.ino
85b5ad629ab52b9e0fa78831bdeef15a458a664a
[sketchbook_andrea] / hardware / ultrasonic / ultrasonic_distance_simple / ultrasonic_distance_simple.ino
1 /*
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
11  */
12
13 #define trigPin 8
14 #define echoPin 7
15 #define RED 11
16 #define GREEN 10
17
18 void setup() {
19   Serial.begin (9600);
20   pinMode(trigPin, OUTPUT);
21   pinMode(echoPin, INPUT);
22   pinMode(RED, OUTPUT);
23   pinMode(GREEN, OUTPUT);
24 }
25
26 void loop() {
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);
40   }
41   else {
42     digitalWrite(RED,LOW);
43     digitalWrite(GREEN,HIGH);
44   }
45   if (distance >= 200 || distance <= 0){
46     Serial.println("Out of range");
47   }
48   else {
49     Serial.print(distance);
50     Serial.println(" cm");
51   }
52   delay(500);
53 }
54