Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int pingPin = 9;
int inPin = 8;
 
// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
     Serial.begin(9600);
}
 
// the loop routine runs over and over again forever:
void loop() {
 
   long duration, cm;
 
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);           // wait for a second
 
    pinMode(inPin, INPUT);
  duration = pulseIn(inPin, HIGH);
 
 
  cm = microsecondsToCentimeters(duration);
  Serial.print("distance=");
  Serial.println(cm);
 
  delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds *0.034 / 2;