WiFi101 ThingSpeak Data Uploader Example
This tutorial demonstrates how to use the Arduino Zero or Arduino Uno and the WiFi shield 101 to send a live stream of the light and temperature values.
WiFi 101 ThingSpeak Data Uploader
This tutorial demonstrates how to use the Arduino Zero or Arduino Uno and the WiFi Shield 101 to send a live stream of the light and temperature values in your environment using ThingSpeak.com. ThingSpeak is an open data platform for the Internet of Things which allows you to collect data in a your own channel and get data from other channels using the API. In this example, we will use a photocell and a temperature sensor and send their values wirelessly to the ThingSpeak server.
Hardware Required
Arduino Zero or Uno Board
Arduino Wifi Shield 101
Photocell
Temperature Sensor (This example uses a TMP36)
10K Ohm Resistor
The Circuit
The Wifi Shield 101 sits on top of the Zero/Uno. The photocell should be connected with one leg to pin A0 and the other to ground via the 10K Ohm resistor. As with ordinary resistors, photocells do not have polarity so it does not matter which leg is connected to which pin. The temperature sensor has three pins: Power, Voltage out and Ground. In this case it is important that pin 1 goes to power and pin 3 goes to ground, and the middle leg of the sensor (voltage out) is then connected to pin A1, as seen in the circuit below.
In the above image, the board would be stacked below the WiFi Shield 101.
Creating a Channel on ThingSpeak
First of all, it is necessary to create a channel on ThingSpeak.com to which the data can be uploaded. To do this, navigate to www.thingspeak.com in your web browser and Sign Up with a new account or with an existing MathWorks account. You can then Create a Channel, give your channel a name such as "Arduino Channel" and a description, such as "Light and temperature values from my environment". Tick the boxes next to Field 1 and Field 2, naming them "Light" and "Temperature" respectively. The rest of the fields are optional and example information is found in Channel Settings on the same page. Hit save channel, and you will be taken to the current view of your new channel. Go to the API Keys tab and find your Write API Key. You will need to insert this into the sketch in order to write to your channel.
Code
This sketch simply continuously reads the values of the thermistor and photocell inside the loop and stores them in a string, and every 20 seconds the current values of the analog sensors are sent to your channel. Before using the program, your wireless network's SSID and its password must be entered into the following lines in the code:
1char ssid[] = "networkssid"; // your network SSID (name)2char pass[] = "password"; // your network password
Then in the ThingSpeak settings, the Write API Key described in the previous section must be inserted into the String APIKey. Optionally, the duration of time in between updates can be changed in updateThingSpeakInterval:
1char thingSpeakAddress[] = "api.thingspeak.com";2
3String APIKey = "O2JUIN8J6CPPX1AW"; //enter your channel's Write API Key4
5const int updateThingSpeakInterval = 20 * 1000; // 20 second interval at which to update ThingSpeak
The analog value of range 0-1023 from the temperature sensor is converted into a temperature value in degrees Celsius by first converting the sensor value to a voltage. From the datasheet, we can see that the offset voltage for the TMP36 is 0.5V (Note: the TMP37 and TMP35 do not have an offset Voltage), therefore the temperature can be read using formula Temp °C = 100 * (voltageReading - 0.5).
1float voltage = analogRead(A1) * (3.3 / 1024); // convert from range 0 - 1023 to 0 - 3.3V2int tempVal = (voltage - 0.5) * 100; // convert to Celsius using offset of 0.5V
Strings must be sent to ThingSpeak, therefore a conversion is required. The light value straight from the A0 pin and the previously calculated temperature are cast to strings.
1String light = String(analogRead(A0),DEC);2
3String temp = String(tempVal,DEC);
An if statement inside the loop then determines whether the specified amount of time has passed and whether the client is disconnected. If so, the function updateThingSpeak sends the string values of light and temperature to fields 1 and 2 respectively:
1if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {2
3 updateThingSpeak("field1=" + light + "&field2=" + temp);4
5 }
The full code can be found below. Upon running the sketch, you can go to your channel and view your Private/Public channel and see the Channel Stats. You should have two graphs, the first showing light and the second temperature. You can now watch this dynamic graph change without refreshing the page. You can also use the MatLab or thingspeak.com/apps to visualise and trigger actions from the data.
1/*2
3WiFi 101 ThingSpeak Data Uploader4
5Hardware Required:6
7* Arduino Zero or Uno Board8
9* Arduino Wifi Shield 10110
11* Photocell12
13* Temperature Sensor (This example uses a TMP36)14
15* 10K Ohm Resistor16
17created Sept 201518
19by Helena Bisby <support@arduino.cc>20
21This example code is in the public domain22
23https://www.arduino.cc/en/Tutorial/WiFi101ThingSpeakDataUploader24
25*/26
27#include <SPI.h>28#include <WiFi101.h>29
30// Local Network Settings31#include "arduino_secrets.h"32///////please enter your sensitive data in the Secret tab/arduino_secrets.h33char ssid[] = SECRET_SSID; // your network SSID (name)34char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)35int keyIndex = 0; // your network key Index number (needed only for WEP)36
37int status = WL_IDLE_STATUS;38
39WiFiServer server(80);40
41// ThingSpeak Settings42char thingSpeakAddress[] = "api.thingspeak.com";43
44String APIKey = "XXXXXXXXXXXXXXXX"; // enter your channel's Write API Key45
46const int updateThingSpeakInterval = 20 * 1000; // 20 second interval at which to update ThingSpeak47
48// Variable Setup49long lastConnectionTime = 0;50boolean lastConnected = false;51
52// Initialize Arduino Ethernet Client53
54WiFiClient client;55
56void setup() {57
58 // Start Serial for debugging on the Serial Monitor59
60 Serial.begin(9600);61
62 while (!Serial) {63
64 ; // wait for serial port to connect. Needed for Leonardo only65
66 }67
68 // check for the presence of the shield:69
70 if (WiFi.status() == WL_NO_SHIELD) {71
72 Serial.println("WiFi shield not present");73
74 // don't continue:75
76 while (true);77
78 }79
80 // attempt to connect to Wifi network:81
82 while ( status != WL_CONNECTED) {83
84 Serial.print("Attempting to connect to SSID: ");85
86 Serial.println(ssid);87
88 // Connect to WPA/WPA2 network. Change this line if using open or WEP network:89
90 status = WiFi.begin(ssid, pass);91
92 // wait 10 seconds for connection:93
94 delay(10000);95
96 }97
98 // you're connected now, so print out the status:99
100 printWifiStatus();101}102
103void loop() {104
105 // read values from pins and store as strings106
107 String light = String(analogRead(A0), DEC); // read light value108
109 // find temp value110
111 float voltage = analogRead(A1) * (3.3 / 1024); // convert 0-1023 range to 3.3V range112
113 int tempVal = (voltage - 0.5) * 100; // convert voltage to temperature in *C114
115 String temp = String(tempVal);116
117 // Print Update Response to Serial Monitor118
119 if (client.available()) {120
121 char c = client.read();122
123 Serial.print(c);124
125 }126
127 // Disconnect from ThingSpeak128
129 if (!client.connected() && lastConnected) {130
131 Serial.println("...disconnected");132
133 Serial.println();134
135 client.stop();136
137 }138
139 // Update ThingSpeak140
141 if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {142
143 updateThingSpeak("field1=" + light + "&field2=" + temp);144
145 Serial.println(light);146
147 Serial.println(temp);148
149 }150
151 lastConnected = client.connected();152}153
154void updateThingSpeak(String tsData) {155
156 if (client.connect(thingSpeakAddress, 80)) {157
158 client.print("POST /update HTTP/1.1\n");159
160 client.print("Host: api.thingspeak.com\n");161
162 client.print("Connection: close\n");163
164 client.print("X-THINGSPEAKAPIKEY: " + APIKey + "\n");165
166 client.print("Content-Type: application/x-www-form-urlencoded\n");167
168 client.print("Content-Length: ");169
170 client.print(tsData.length());171
172 client.print("\n\n");173
174 client.print(tsData);175
176 lastConnectionTime = millis();177
178 if (client.connected()) {179
180 Serial.println("Connecting to ThingSpeak...");181
182 Serial.println();183
184 }185
186 }187}188
189void printWifiStatus() {190
191 // print the SSID of the network you're attached to:192
193 Serial.print("SSID: ");194
195 Serial.println(WiFi.SSID());196
197 // print your WiFi shield's IP address:198
199 IPAddress ip = WiFi.localIP();200
201 Serial.print("IP Address: ");202
203 Serial.println(ip);204
205 // print the received signal strength:206
207 long rssi = WiFi.RSSI();208
209 Serial.print("signal strength (RSSI):");210
211 Serial.print(rssi);212
213 Serial.println(" dBm");214}
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.