· 6 years ago · Oct 08, 2019, 02:04 PM
1/*
2
3 * Description: Distance measurement using ultrasonic HC-SR04 and ESP32 connected to AskSensors
4 * Author: https://asksensors.com, 2018 - 2019
5 * github: https://github.com/asksensors
6 */
7
8#include <WiFi.h>
9#include <WiFiMulti.h>
10#include <HTTPClient.h>
11
12// utlrasonic pinout
13#define ULTRASONIC_TRIG_PIN 5 // pin TRIG
14#define ULTRASONIC_ECHO_PIN 4 // pin ECHO
15
16
17WiFiMulti WiFiMulti;
18HTTPClient ask;
19// TODO: user config
20const char* ssid = "............."; //Wifi SSID
21const char* password = "............."; //Wifi Password
22String apiKeyIn = "............."; // API Key
23const unsigned int writeInterval = 25000; // write interval (in ms)
24// ASKSENSORS API host config
25const char* host = "api.asksensors.com"; // API host name
26const int httpPort = 80; // port
27
28void setup(){
29
30 // open serial
31 Serial.begin(9600);
32 Serial.println("*****************************************************");
33 Serial.println("********** Program Start : Connect ESP32 to AskSensors.");
34 Serial.println("Wait for WiFi... ");
35
36 // connecting to the WiFi network
37 WiFiMulti.addAP(ssid, password);
38 while (WiFiMulti.run() != WL_CONNECTED) {
39 Serial.print(".");
40 delay(500);
41 }
42 // connected
43 Serial.println("WiFi connected");
44 Serial.println("IP address: ");
45 Serial.println(WiFi.localIP());
46
47 // ultraonic setup
48 pinMode(ULTRASONIC_TRIG_PIN, OUTPUT);
49 pinMode(ULTRASONIC_ECHO_PIN, INPUT);
50
51}
52
53
54void loop(){
55
56 // Use WiFiClient class to create TCP connections
57 WiFiClient client;
58 // measure distance
59 long duration, distance;
60 digitalWrite(ULTRASONIC_TRIG_PIN, LOW);
61 delayMicroseconds(2);
62
63 digitalWrite(ULTRASONIC_TRIG_PIN, HIGH);
64 delayMicroseconds(10);
65
66 digitalWrite(ULTRASONIC_TRIG_PIN, LOW);
67 duration = pulseIn(ULTRASONIC_ECHO_PIN, HIGH);
68 distance = (duration/2) / 29.1;
69 Serial.print("********** Ultrasonic Distance: ");
70 Serial.print(distance);
71 Serial.println(" cm");
72
73 if (!client.connect(host, httpPort)) {
74 Serial.println("connection failed");
75 return;
76 }else {
77
78 // Create a URL for the request
79 String url = "https://api.asksensors.com/write/";
80 url += apiKeyIn;
81 url += "?module1=";
82 url += distance;
83
84 Serial.print("********** requesting URL: ");
85 Serial.println(url);
86
87 ask.begin(url); //Specify the URL
88
89 //Check for the returning code
90 int httpCode = ask.GET();
91
92 if (httpCode > 0) {
93
94 String payload = ask.getString();
95 Serial.println(httpCode);
96 Serial.println(payload);
97 } else {
98 Serial.println("Error on HTTP request");
99 }
100
101 ask.end(); //End
102 Serial.println("********** End ");
103 Serial.println("*****************************************************");
104
105 }
106
107 client.stop(); // stop client
108
109 delay(writeInterval); // delay
110}