1const unsigned int TRIG_PIN=13;
2const unsigned int ECHO_PIN=12;
3const unsigned int BAUD_RATE=9600;
4
5void setup() {
6 pinMode(TRIG_PIN, OUTPUT);
7 pinMode(ECHO_PIN, INPUT);
8 Serial.begin(BAUD_RATE);
9}
10
11void loop() {
12 digitalWrite(TRIG_PIN, LOW);
13 delayMicroseconds(2);
14 digitalWrite(TRIG_PIN, HIGH);
15 delayMicroseconds(10);
16 digitalWrite(TRIG_PIN, LOW);
17
18
19 const unsigned long duration= pulseIn(ECHO_PIN, HIGH);
20 int distance= duration/29/2;
21 if(duration==0){
22 Serial.println("Warning: no pulse from sensor");
23 }
24 else{
25 Serial.print("distance to nearest object:");
26 Serial.println(distance);
27 Serial.println(" cm");
28 }
29 delay(100);
30 }