]> git.piffa.net Git - rover/blob - prototypes/ultra/check_func/check_func.ino
40481b1e86d6d5a0e484358d7df6b3d559a06254
[rover] / prototypes / ultra / check_func / check_func.ino
1 /* Ultrasonic rilevatore distanza
2
3 Rilevatore distanza minore di 5cm.
4 funzione
5
6 HC-SR04 Ping distance sensor
7 VCC to arduino 5v - GND to arduino GND
8
9  */
10 # define DEBUG
11
12 // Ultrasuoni
13 const byte trig = 11;
14 const byte echo = 12;
15 const byte led = 13;
16 long duration, distance;
17 boolean allarm = 0;
18
19 void setup() {
20     pinMode(trig, OUTPUT);
21     pinMode(echo, INPUT);
22     pinMode(led, OUTPUT);
23
24
25     //Debug
26     Serial.begin (9600);
27 }
28
29 void loop() {
30 if (check()) {
31     digitalWrite(led,HIGH);
32 } else {
33     digitalWrite(led,LOW);
34 }
35
36 #ifdef DEBUG
37 Serial.begin(9600);
38 #endif
39
40 }
41
42 boolean check() {
43     digitalWrite(trig, LOW);  // Prepare for ping
44     delayMicroseconds(2); //
45     digitalWrite(trig, HIGH); // Send a ping
46     delayMicroseconds(10); //
47     digitalWrite(trig, LOW); // Set down ping
48     duration = pulseIn(echo, HIGH);
49     distance = (duration/2) / 29.1; // Speed is ~300m/s,
50     // so it takes ~29.1 milliseconds for a cm.
51     // Distance is half of (out + back)
52     if (distance < 5) {  // This is where the LED On/Off happens
53         return 1;
54     }
55     else {
56         return 0;
57     }
58 }