Hardware Reference
In-Depth Information
Listing 11-1: ( continued )
20 pinMode(echoPin, INPUT);
21 pinMode(vccPin, OUTPUT);
22 pinMode(gndPin, OUTPUT);
23
24 // Trigger set to low
25 digitalWrite(trigPin, LOW);
26
27 // VCC and GND
28 digitalWrite(vccPin, HIGH);
29 digitalWrite(gndPin, LOW);
30
31 // Prepare LCD screen text
32 lcd.print("Distance");
33 }
34
35 void loop()
36 {
37 long duration, distance;
38
39 digitalWrite(trigPin, HIGH);
40 delayMicroseconds(10);
41 digitalWrite(trigPin, LOW);
42
43 duration = pulseIn(echoPin, HIGH);
44 distance = duration / 58;
45
46 // Set the cursor to column 0, line 1 (beginning of second line)
47 lcd.setCursor(0, 1);
48
49 if (distance >= 400 || distance <= 0)
50 {
51 // Inform the user that we are out of range
52 lcd.print("Out of range");
53 }
54 else
55 {
56 // Tell the user what distance has been detected
57 lcd.print(distance);
58 lcd.print(" cm "); // Extra space overwrites any text
59 }
60
61 // Wait for half a second before repeating
62 delay(500);
63 }
From the start, on line 1, the LCD library is imported. Afterward, four pins
are dei ned as constants: vccPin , gndPin , trigPin , and echoPin . These pins
correspond to the pins found on the HC-SR04 sensor board. The vccPin and the
Search WWH ::




Custom Search