]> git.piffa.net Git - sketchbook_andrea/blob - hardware/ultrasonic/ultrasonic_distance_simple/ultrasonic_distance_simple.ino
Rover prima lezione
[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 Schema: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/step2/Connect-the-components/
13
14  */
15
16 #define trigPin 12
17 #define echoPin 13
18 #define RED 11
19 #define GREEN 10
20
21 void setup() {
22   Serial.begin (9600);
23   pinMode(trigPin, OUTPUT);
24   pinMode(echoPin, INPUT);
25   pinMode(RED, OUTPUT);
26   pinMode(GREEN, OUTPUT);
27 }
28
29 void loop() {
30   long duration, distance;
31   digitalWrite(trigPin, LOW);  // Prepare for ping
32   delayMicroseconds(2); // 
33   digitalWrite(trigPin, HIGH); // Send a ping
34   delayMicroseconds(10); // 
35   digitalWrite(trigPin, LOW); // Set down ping
36   duration = pulseIn(echoPin, HIGH);
37   distance = (duration/2) / 29.1; // Speed is ~300m/s, 
38       // so it takes ~29.1 milliseconds for a cm.
39       // Distance is half of (out + back)
40   if (distance < 5) {  // This is where the LED On/Off happens
41     digitalWrite(RED,HIGH); // When the Red condition is met, the Green LED should turn off
42     digitalWrite(GREEN,LOW);
43   }
44   else {
45     digitalWrite(RED,LOW);
46     digitalWrite(GREEN,HIGH);
47   }
48   if (distance >= 200 || distance <= 0){
49     Serial.println("Out of range");
50   }
51   else {
52     Serial.print(distance);
53     Serial.println(" cm");
54   }
55   delay(500);
56 }
57