6
6
1. Attach a HC-SR04 to your Arduino:
7
7
Schematic:
8
8
HC-SR04 Arduino
9
- [VDD ] --- [5V]
9
+ [VCC ] --- [5V]
10
10
[GND] --- [GND]
11
- [TRIGGER ] --- [Digital Pin 2]
12
- [ECHO ] --- [Digital Pin 3]
11
+ [TRIGGER_PIN ] --- [Digital Pin 2]
12
+ [ECHO_PIN ] --- [Digital Pin 3]
13
13
2. Set the DISTANCE_VIRTUAL_CHANNEL value below to a free virtual channel.
14
14
3. Set the Cayenne authentication info to match the authentication info from the Dashboard.
15
15
4. Compile and upload this sketch.
@@ -28,17 +28,17 @@ char clientID[] = "CLIENT_ID";
28
28
29
29
#define DISTANCE_VIRTUAL_CHANNEL 1
30
30
31
- // defines pins numbers
32
- #define TRIGPIN 2
33
- #define ECHOPIN 3
31
+ // Defines pins numbers for the HC-SR04 connections.
32
+ #define TRIGGER_PIN 2
33
+ #define ECHO_PIN 3
34
34
35
- // defines variables
35
+ // Defines variables for storing the calculated values.
36
36
long duration;
37
37
int distance;
38
38
39
39
void setup () {
40
- pinMode (TRIGPIN , OUTPUT);
41
- pinMode (ECHOPIN , INPUT);
40
+ pinMode (TRIGGER_PIN , OUTPUT);
41
+ pinMode (ECHO_PIN , INPUT);
42
42
Serial.begin (9600 );
43
43
Cayenne.begin (username, password, clientID);
44
44
}
@@ -50,17 +50,19 @@ void loop() {
50
50
// This function is called at intervals to send temperature sensor data to Cayenne.
51
51
CAYENNE_OUT (DISTANCE_VIRTUAL_CHANNEL)
52
52
{
53
- digitalWrite (TRIGPIN , LOW);// Clears the trigPin
53
+ digitalWrite (TRIGGER_PIN , LOW);// Clears the trigPin
54
54
delayMicroseconds (2 );
55
55
56
- digitalWrite (TRIGPIN , HIGH); // Sets the trigPin on HIGH state for 10 micro seconds
56
+ digitalWrite (TRIGGER_PIN , HIGH); // Sets the trigPin on HIGH state for 10 micro seconds
57
57
delayMicroseconds (10 );
58
- digitalWrite (TRIGPIN, LOW);
59
-
60
- duration = pulseIn (ECHOPIN, HIGH);// Reads the echoPin, returns the sound wave travel time in microseconds
58
+ digitalWrite (TRIGGER_PIN, LOW);
61
59
62
- distance = duration * 0.034 / 2 ; // Calculating the distance
60
+ duration = pulseIn (ECHO_PIN, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
63
61
64
- // Send the distance value to Cayenne on counter widget.
65
- Cayenne.virtualWrite (DISTANCE_VIRTUAL_CHANNEL, distance, " counter" , " null" );
62
+ distance = duration * 0.034 / 2 ; // Calculating the distance.
63
+
64
+ // Send the distance value to Cayenne on proximity widget in centimeter.
65
+ Cayenne.virtualWrite (DISTANCE_VIRTUAL_CHANNEL, distance, " prox" , " cm" );
66
+ // Send the distance value to Cayenne on proximity widget in meter.
67
+ // Cayenne.virtualWrite(DISTANCE_VIRTUAL_CHANNEL, distance, "prox", "m");
66
68
}
0 commit comments