1 /* Ultrasonic rilevatore distanza
3 Rilevatore distanza minore di 5cm.
5 HC-SR04 Ping distance sensor
6 VCC to arduino 5v - GND to arduino GND
15 long duration, distance;
18 pinMode(trig, OUTPUT);
28 digitalWrite(trig, LOW); // Prepare for ping
29 delayMicroseconds(2); //
30 digitalWrite(trig, HIGH); // Send a ping
31 delayMicroseconds(10); //
32 digitalWrite(trig, LOW); // Set down ping
33 duration = pulseIn(echo, 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(led,HIGH); // When the Red condition is met, the Green LED should turn off
41 digitalWrite(led,LOW);
44 Serial.println(distance);