Skip to content

Commit ce49719

Browse files
WiFiClient example fix (#7711)
* Modified WiFiClient example to use thingspeak instead of non-functionig sparkfun * Moved instructions to README * Fixed spelling * Added link to S3 datasheet --------- Co-authored-by: Jan Procházka <[email protected]>
1 parent 26c8b30 commit ce49719

File tree

2 files changed

+238
-59
lines changed

2 files changed

+238
-59
lines changed

Diff for: libraries/WiFi/examples/WiFiClient/README.md

+165
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# WiFiClient
2+
3+
This example demonstrates reading and writing data from and to a web service which can be used for logging data, creating insights and taking actions based on those data.
4+
5+
# Supported Targets
6+
7+
Currently, this example supports all SoC with WiFi.
8+
9+
10+
| Supported Targets | ESP32 | ESP32-S2 | ESP32-C3 | ESP32-S3 |
11+
12+
13+
## How to Use Example
14+
15+
Flash this example and observe the serial output. You can also take a look at the values at [https://thingspeak.com/channels/2005329](https://thingspeak.com/channels/2005329)
16+
17+
Please note that this public channel can be accessed by anyone and it is possible that more people will write their values.
18+
19+
### Configure the Project
20+
21+
Change `SSID` and `password` to connect to your WiFi.
22+
Default values will allow you to use this example without any changes. If you want to use your own channel and you don't have one already follow these steps:
23+
24+
* Create an account on [thingspeak.com](https://www.thingspeak.com).
25+
* After logging in, click on the "New Channel" button to create a new channel for your data. This is where your data will be stored and displayed.
26+
* Fill in the Name, Description, and other fields for your channel as desired, then click the "Save Channel" button.
27+
* Take note of the "Write API Key" located in the "API keys" tab, this is the key you will use to send data to your channel.
28+
* Replace the channelID from tab "Channel Settings" and privateKey with "Read API Keys" from "API Keys" tab.
29+
* Replace the host variable with the thingspeak server hostname "api.thingspeak.com"
30+
* Upload the sketch to your ESP32 board and make sure that the board is connected to the internet. The ESP32 should now send data to your Thingspeak channel at the intervals specified by the loop function.
31+
* Go to the channel view page on thingspeak and check the "Field1" for the new incoming data.
32+
* You can use the data visualization and analysis tools provided by Thingspeak to display and process your data in various ways.
33+
* Please note, that Thingspeak accepts only integer values.
34+
35+
#### Config example:
36+
37+
You can find the data to be changed at the top of the file:
38+
39+
```cpp
40+
const char* ssid = "your-ssid"; // Change this to your WiFi SSID
41+
const char* password = "your-password"; // Change this to your WiFi password
42+
43+
const char* host = "api.thingspeak.com"; // This should not be changed
44+
const int httpPort = 80; // This should not be changed
45+
const String channelID = "2005329"; // Change this to your channel ID
46+
const String writeApiKey = "V6YOTILH9I7D51F9"; // Change this to your Write API key
47+
const String readApiKey = "34W6LGLIFXD56MPM"; // Change this to your Read API key
48+
49+
// The default example accepts one data filed named "field1"
50+
// For your own server you can ofcourse create more of them.
51+
int field1 = 0;
52+
53+
int numberOfResults = 3; // Number of results to be read
54+
int fieldNumber = 1; // Field number which will be read out
55+
```
56+
57+
#### Using Arduino IDE
58+
59+
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
60+
61+
* Before Compile/Verify, select the correct board: `Tools -> Board`.
62+
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
63+
64+
#### Using Platform IO
65+
66+
* Select the COM port: `Devices` or set the `upload_port` option on the `platformio.ini` file.
67+
68+
## Example Log Output
69+
70+
The initial output which is common for all examples can be ignored:
71+
```
72+
SP-ROM:esp32c3-api1-20210207
73+
Build:Feb 7 2021
74+
rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT)
75+
SPIWP:0xee
76+
mode:DIO, clock div:1
77+
load:0x3fcd5810,len:0x438
78+
load:0x403cc710,len:0x918
79+
load:0x403ce710,len:0x24e4
80+
entry 0x403cc710
81+
```
82+
Follows the setup output where connection to your WiFi happens:
83+
```
84+
******************************************************
85+
Connecting to your-ssid
86+
.
87+
WiFi connected
88+
IP address:
89+
192.168.1.2
90+
```
91+
Then you can see the write log:
92+
```
93+
HTTP/1.1 200 OK
94+
Date: Fri, 13 Jan 2023 13:12:31 GMT
95+
Content-Type: text/plain; charset=utf-8
96+
Content-Length: 1
97+
Connection: close
98+
Status: 200 OK
99+
Cache-Control: max-age=0, private, must-revalidate
100+
Access-Control-Allow-Origin: *
101+
Access-Control-Max-Age: 1800
102+
X-Request-Id: 188e3464-f155-44b0-96f6-0f3614170bb0
103+
Access-Control-Allow-Headers: origin, content-type, X-Requested-With
104+
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
105+
ETag: W/"5feceb66ffc86f38d952786c6d696c79"
106+
X-Frame-Options: SAMEORIGIN
107+
108+
0
109+
Closing connection
110+
```
111+
Last portion is the read log:
112+
```
113+
HTTP/1.1 200 OK
114+
Date: Fri, 13 Jan 2023 13:12:32 GMT
115+
Content-Type: application/json; charset=utf-8
116+
Transfer-Encoding: chunked
117+
Connection: close
118+
Status: 200 OK
119+
Cache-Control: max-age=7, private
120+
Access-Control-Allow-Origin: *
121+
Access-Control-Max-Age: 1800
122+
X-Request-Id: 91b97016-7625-44f6-9797-1b2973aa57b7
123+
Access-Control-Allow-Headers: origin, content-type, X-Requested-With
124+
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
125+
ETag: W/"8e9c308fe2c50309f991586be1aff28d"
126+
X-Frame-Options: SAMEORIGIN
127+
128+
1e3
129+
{"channel":{"id":2005329,"name":"WiFiCLient example","description":"Default setup for Arduino ESP32 WiFiClient example","latitude":"0.0","longitude":"0.0","field1":"data0","created_at":"2023-01-11T15:56:08Z","updated_at":"2023-01-13T08:13:58Z","last_entry_id":2871},"feeds":[{"created_at":"2023-01-13T13:11:30Z","entry_id":2869,"field1":"359"},{"created_at":"2023-01-13T13:11:57Z","entry_id":2870,"field1":"361"},{"created_at":"2023-01-13T13:12:23Z","entry_id":2871,"field1":"363"}]}
130+
0
131+
132+
133+
Closing connection
134+
```
135+
After this the write+read log repeat every 10 seconds.
136+
137+
138+
## Troubleshooting
139+
140+
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***
141+
142+
* **WiFi not connected:** Check the SSID and password and also that the signal has sufficient strength.
143+
* **400 Bad Request:** Check the writeApiKey.
144+
* **404 Not Found:** Check the channel ID.
145+
* **No data on chart / reading NULL:** Data must be sent as an integer, without commas.
146+
147+
If the error persists, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
148+
149+
## Contribute
150+
151+
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
152+
153+
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
154+
155+
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
156+
157+
## Resources
158+
159+
* Official ESP32 Forum: [Link](https://esp32.com)
160+
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
161+
* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
162+
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
163+
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
164+
* ESP32-S3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s3_datasheet_en.pdf)
165+
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

Diff for: libraries/WiFi/examples/WiFiClient/WiFiClient.ino

+73-59
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,46 @@
11
/*
2-
* This sketch sends data via HTTP GET requests to data.sparkfun.com service.
3-
*
4-
* You need to get streamId and privateKey at data.sparkfun.com and paste them
5-
* below. Or just customize this script to talk to other HTTP servers.
6-
*
2+
Go to thingspeak.com and create an account if you don't have one already.
3+
After logging in, click on the "New Channel" button to create a new channel for your data. This is where your data will be stored and displayed.
4+
Fill in the Name, Description, and other fields for your channel as desired, then click the "Save Channel" button.
5+
Take note of the "Write API Key" located in the "API keys" tab, this is the key you will use to send data to your channel.
6+
Replace the channelID from tab "Channel Settings" and privateKey with "Read API Keys" from "API Keys" tab.
7+
Replace the host variable with the thingspeak server hostname "api.thingspeak.com"
8+
Upload the sketch to your ESP32 board and make sure that the board is connected to the internet. The ESP32 should now send data to your Thingspeak channel at the intervals specified by the loop function.
9+
Go to the channel view page on thingspeak and check the "Field1" for the new incoming data.
10+
You can use the data visualization and analysis tools provided by Thingspeak to display and process your data in various ways.
11+
Please note, that Thingspeak accepts only integer values.
12+
13+
You can later check the values at https://thingspeak.com/channels/2005329
14+
Please note that this public channel can be accessed by anyone and it is possible that more people will write their values.
715
*/
816

917
#include <WiFi.h>
1018

11-
const char* ssid = "your-ssid";
12-
const char* password = "your-password";
19+
const char* ssid = "your-ssid"; // Change this to your WiFi SSID
20+
const char* password = "your-password"; // Change this to your WiFi password
1321

14-
const char* host = "data.sparkfun.com";
15-
const char* streamId = "....................";
16-
const char* privateKey = "....................";
22+
const char* host = "api.thingspeak.com"; // This should not be changed
23+
const int httpPort = 80; // This should not be changed
24+
const String channelID = "2005329"; // Change this to your channel ID
25+
const String writeApiKey = "V6YOTILH9I7D51F9"; // Change this to your Write API key
26+
const String readApiKey = "34W6LGLIFXD56MPM"; // Change this to your Read API key
27+
28+
// The default example accepts one data filed named "field1"
29+
// For your own server you can ofcourse create more of them.
30+
int field1 = 0;
31+
32+
int numberOfResults = 3; // Number of results to be read
33+
int fieldNumber = 1; // Field number which will be read out
1734

1835
void setup()
1936
{
2037
Serial.begin(115200);
21-
delay(10);
38+
while(!Serial){delay(100);}
2239

2340
// We start by connecting to a WiFi network
2441

2542
Serial.println();
26-
Serial.println();
43+
Serial.println("******************************************************");
2744
Serial.print("Connecting to ");
2845
Serial.println(ssid);
2946

@@ -40,55 +57,52 @@ void setup()
4057
Serial.println(WiFi.localIP());
4158
}
4259

43-
int value = 0;
44-
45-
void loop()
46-
{
47-
delay(5000);
48-
++value;
49-
50-
Serial.print("connecting to ");
51-
Serial.println(host);
52-
53-
// Use WiFiClient class to create TCP connections
54-
WiFiClient client;
55-
const int httpPort = 80;
56-
if (!client.connect(host, httpPort)) {
57-
Serial.println("connection failed");
58-
return;
60+
void readResponse(WiFiClient *client){
61+
unsigned long timeout = millis();
62+
while(client->available() == 0){
63+
if(millis() - timeout > 5000){
64+
Serial.println(">>> Client Timeout !");
65+
client->stop();
66+
return;
5967
}
68+
}
6069

61-
// We now create a URI for the request
62-
String url = "/input/";
63-
url += streamId;
64-
url += "?private_key=";
65-
url += privateKey;
66-
url += "&value=";
67-
url += value;
68-
69-
Serial.print("Requesting URL: ");
70-
Serial.println(url);
71-
72-
// This will send the request to the server
73-
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
74-
"Host: " + host + "\r\n" +
75-
"Connection: close\r\n\r\n");
76-
unsigned long timeout = millis();
77-
while (client.available() == 0) {
78-
if (millis() - timeout > 5000) {
79-
Serial.println(">>> Client Timeout !");
80-
client.stop();
81-
return;
82-
}
83-
}
84-
85-
// Read all the lines of the reply from server and print them to Serial
86-
while(client.available()) {
87-
String line = client.readStringUntil('\r');
88-
Serial.print(line);
89-
}
70+
// Read all the lines of the reply from server and print them to Serial
71+
while(client->available()) {
72+
String line = client->readStringUntil('\r');
73+
Serial.print(line);
74+
}
9075

91-
Serial.println();
92-
Serial.println("closing connection");
76+
Serial.printf("\nClosing connection\n\n");
9377
}
9478

79+
void loop(){
80+
WiFiClient client;
81+
String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n";
82+
83+
// WRITE --------------------------------------------------------------------------------------------
84+
if (!client.connect(host, httpPort)) {
85+
return;
86+
}
87+
88+
client.print("GET /update?api_key=" + writeApiKey + "&field1=" + field1 + footer);
89+
readResponse(&client);
90+
91+
// READ --------------------------------------------------------------------------------------------
92+
93+
String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?results=" + numberOfResults + " HTTP/1.1\r\n" +
94+
"Host: " + host + "\r\n" +
95+
"Connection: close\r\n\r\n";
96+
97+
if (!client.connect(host, httpPort)) {
98+
return;
99+
}
100+
101+
client.print(readRequest);
102+
readResponse(&client);
103+
104+
// -------------------------------------------------------------------------------------------------
105+
106+
++field1;
107+
delay(10000);
108+
}

0 commit comments

Comments
 (0)