]> git.piffa.net Git - rover/blob - prototypes/ultra/check_func/check_func.ino
Aggiunti esempi, funzioni per servo
[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;
17 int distance;
18 const int minDistance = 10;
19
20 void setup() {
21     pinMode(trig, OUTPUT);
22     pinMode(echo, INPUT);
23     pinMode(led, OUTPUT);
24
25
26     //Debug
27 #ifdef DEBUG
28 Serial.begin(9600);
29 #endif
30 Serial.begin(9600); // Need for distanceMonitor
31 }
32
33 void loop() {
34 if (distanceCheck()) {
35     digitalWrite(led,HIGH);
36 } else {
37     digitalWrite(led,LOW);
38 }
39 Serial.println(distanceMonitor());
40 delay(50);
41
42 }
43
44 boolean distanceCheck() {
45     digitalWrite(trig, LOW);  // Prepare for ping
46     delayMicroseconds(2); //
47     digitalWrite(trig, HIGH); // Send a ping
48     delayMicroseconds(10); //
49     digitalWrite(trig, LOW); // Set down ping
50     duration = pulseIn(echo, HIGH);
51     //distance = (duration / 2) / 29.1; // Speed is ~300m/s,
52     // so it takes ~29.1 milliseconds for a cm.
53     distance = (duration / 58.2); // Atmegas are not found of divisions
54     // Distance is half of (out + back)
55 #ifdef DEBUG
56 Serial.print("Distanza oggetto: ");    
57 Serial.println(distance);
58 #endif
59     if (distance < minDistance) {  // This is where the LED On/Off happens
60         return 1;
61     }
62     else {
63         return 0;
64     }
65 }
66
67 int distanceMonitor() {
68     digitalWrite(trig, LOW);  // Prepare for ping
69     delayMicroseconds(2); //
70     digitalWrite(trig, HIGH); // Send a ping
71     delayMicroseconds(10); //
72     digitalWrite(trig, LOW); // Set down ping
73     duration = pulseIn(echo, HIGH);
74     //distance = (duration / 2) / 29.1; // Speed is ~300m/s,
75     // so it takes ~29.1 milliseconds for a cm.
76     distance = (duration / 58.2); // Atmegas are not found of divisions
77     // Distance is half of (out + back)
78
79     return distance;
80 }