Progetto

Generale

Profilo

File » ping2.ino

Andrea Belloni, 22-11-2015 19:12

 
1
const int TRIG_PIN = 5;
2
const int ECHO_PIN = 6;
3
 
4
void setup() {
5
  // initialize serial communication:
6
  Serial.begin(9600);
7
 
8
  pinMode(TRIG_PIN,OUTPUT);
9
  pinMode(ECHO_PIN,INPUT);
10
}
11
 
12
void loop()
13
{
14
   long duration, distanceCm, distanceIn;
15
 
16
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
17
  digitalWrite(TRIG_PIN, LOW);
18
  delayMicroseconds(2);
19
  digitalWrite(TRIG_PIN, HIGH);
20
  delayMicroseconds(10);
21
  digitalWrite(TRIG_PIN, LOW);
22
  duration = pulseIn(ECHO_PIN,HIGH);
23
 
24
  // convert the time into a distance
25
  distanceCm = duration / 29.1 / 2 ;
26
  distanceIn = duration / 74 / 2;
27
 
28
  if (distanceCm <= 0){
29
    Serial.println("Out of range");
30
  }
31
  else {
32
    Serial.print(distanceIn);
33
    Serial.print("in, ");
34
    Serial.print(distanceCm);
35
    Serial.print("cm");
36
    Serial.println();
37
  }
38
  delay(1000);
39
}
40

    
(66-66/98)