Sending data to ThingSpeak

This shows the use of a "ThingSpeak logger" object. Data is sent to ThingSpeak using MQTT.



Unique Features of the ThingSpeak Example

  • A single logger publishes data to ThingSpeak.
  • Uses an Espressif ESP8266 to publish data.

To Use this Example

Prepare and set up PlatformIO

  • Create a channel on ThingSpeak with fields to receive your data.
  • Create a new PlatformIO project
  • Replace the contents of the platformio.ini for your new project with the platformio.ini file in the examples/logging_to_ThingSpeak folder on GitHub.
    • It is important that your PlatformIO configuration has the lib_ldf_mode and build flags set as they are in the example.
    • Without this, the program won't compile.
  • Open logging_to_ThingSpeak.ino and save it to your computer.
    • After opening the link, you should be able to right click anywhere on the page and select "Save Page As".
    • Move it into the src directory of your project.
    • Delete main.cpp in that folder.

Modify the Example

  • Modify logging_to_ThingSpeak.ino to have the modem, sensor, and variable objects that you are interested in.
    • This example is written for an ESP8266 (wifi) modem. Change this to whatever modem you are using. Pastable chunks of code for each modem are available in the individual sensor documentation or in the menu a la carte example.
    • Don't forget to put in your wifi username/password or cellular APN!
    • This example is written for a Campbell OBS3+ and a Meter Hydros 21. Remove those sensors if you are not using them and add code for all of your sensors. See the pages for the individual sensors in the documentation for code snippets/examples.
      • Remember, no more than 8 variables/fields can be sent to a single ThingSpeak channel. If you want to send data to multiple channels, you must create individual logger objects with unique publishers attached for each channel you want to send to.
  • Make sure the pin numbers and serial ports selected in your code match with how things are physically attached to your board!
  • Order the variables in your variable array in the same order as your fields are on ThingSpeak.
    • This order is crucial. The results from the variables in the VariableArray will be sent to ThingSpeak in the order they are in the array; that is, the first variable in the array will be sent as Field1, the second as Field2, etc.
    • Any UUID's or custom variable codes are ignored for ThingSpeak. They will only appear in the header of your file on the SD card.
  • Find this information for your ThingSpeak account and channel and put it into logging_to_ThingSpeak.ino:
1const char *thingSpeakMQTTKey = "XXXXXXXXXXXXXXXX"; // Your MQTT API Key from Account > MyProfile.
2const char *thingSpeakChannelID = "######"; // The numeric channel id for your channel
3const char *thingSpeakChannelKey = "XXXXXXXXXXXXXXXX"; // The Write API Key for your channel

Upload!

  • Test everything at home before deploying out in the wild!

PlatformIO Configuration

1; PlatformIO Project Configuration File
2;
3; Build options: build flags, source filter
4; Upload options: custom upload port, speed and extra flags
5; Library options: dependencies, extra library storages
6; Advanced options: extra scripting
7;
8; Please visit documentation for the other options and examples
9; http://docs.platformio.org/page/projectconf.html
10
11[platformio]
12description = ModularSensors example sending data to ThingSpeak
13
14[env:mayfly]
15monitor_speed = 115200
16board = mayfly
17platform = atmelavr
18framework = arduino
19lib_ldf_mode = deep+
20lib_ignore =
21 RTCZero
22 Adafruit NeoPixel
23 Adafruit GFX Library
24 Adafruit SSD1306
25 Adafruit ADXL343
26 Adafruit STMPE610
27 Adafruit TouchScreen
28 Adafruit ILI9341
29build_flags =
30 -DSDI12_EXTERNAL_PCINT
31 -DNEOSWSERIAL_EXTERNAL_PCINT
32 -DMQTT_MAX_PACKET_SIZE=240
33 -DTINY_GSM_RX_BUFFER=64
34 -DTINY_GSM_YIELD_MS=2
35lib_deps =
36 envirodiy/EnviroDIY_ModularSensors
37; ^^ Use this when working from an official release of the library
38; https://github.com/EnviroDIY/ModularSensors.git#develop
39; ^^ Use this when if you want to pull from the develop branch

The Complete Code

1/** =========================================================================
2 * @example{lineno} logging_to_ThingSpeak.ino
3 * @copyright Stroud Water Research Center
4 * @license This example is published under the BSD-3 license.
5 * @author Sara Geleskie Damiano <sdamiano@stroudcenter.org>
6 *
7 * @brief Example logging data and publishing to ThingSpeak.
8 *
9 * See [the walkthrough page](@ref example_thingspeak) for detailed
10 * instructions.
11 *
12 * @m_examplenavigation{example_thingspeak,}
13 * ======================================================================= */
14
15// ==========================================================================
16// Defines for TinyGSM
17// ==========================================================================
18/** Start [defines] */
19#ifndef TINY_GSM_RX_BUFFER
20#define TINY_GSM_RX_BUFFER 64
21#endif
22#ifndef TINY_GSM_YIELD_MS
23#define TINY_GSM_YIELD_MS 2
24#endif
25#ifndef MQTT_MAX_PACKET_SIZE
26#define MQTT_MAX_PACKET_SIZE 240
27#endif
28/** End [defines] */
29
30// ==========================================================================
31// Include the libraries required for any data logger
32// ==========================================================================
33/** Start [includes] */
34// The Arduino library is needed for every Arduino program.
35#include <Arduino.h>
36
37// Include the main header for ModularSensors
38#include <ModularSensors.h>
39/** End [includes] */
40
41
42// ==========================================================================
43// Data Logging Options
44// ==========================================================================
45/** Start [logging_options] */
46// The name of this program file
47const char* sketchName = "logging_to_ThingSpeak.ino";
48// Logger ID, also becomes the prefix for the name of the data file on SD card
49const char* LoggerID = "XXXXX";
50// How frequently (in minutes) to log data
51const uint8_t loggingInterval = 15;
52// Your logger's timezone.
53const int8_t timeZone = -5; // Eastern Standard Time
54// NOTE: Daylight savings time will not be applied! Please use standard time!
55
56// Set the input and output pins for the logger
57// NOTE: Use -1 for pins that do not apply
58const int32_t serialBaud = 115200; // Baud rate for debugging
59const int8_t greenLED = 8; // Pin for the green LED
60const int8_t redLED = 9; // Pin for the red LED
61const int8_t buttonPin = 21; // Pin for debugging mode (ie, button pin)
62const int8_t wakePin = 31; // MCU interrupt/alarm pin to wake from sleep
63// Mayfly 0.x D31 = A7
64// Set the wake pin to -1 if you do not want the main processor to sleep.
65// In a SAMD system where you are using the built-in rtc, set wakePin to 1
66const int8_t sdCardPwrPin = -1; // MCU SD card power pin
67const int8_t sdCardSSPin = 12; // SD card chip select/slave select pin
68const int8_t sensorPowerPin = 22; // MCU pin controlling main sensor power
69/** End [logging_options] */
70
71
72// ==========================================================================
73// Wifi/Cellular Modem Options
74// ==========================================================================
75/** Start [espressif_esp8266] */
76// For almost anything based on the Espressif ESP8266 using the AT command
77// firmware
78#include <modems/EspressifESP8266.h>
79// Create a reference to the serial port for the modem
80HardwareSerial& modemSerial = Serial1; // Use hardware serial if possible
81const int32_t modemBaud = 115200; // Communication speed of the modem
82// NOTE: This baud rate too fast for an 8MHz board, like the Mayfly! The
83// module should be programmed to a slower baud rate or set to auto-baud using
84// the AT+UART_CUR or AT+UART_DEF command.
85
86// Modem Pins - Describe the physical pin connection of your modem to your board
87// NOTE: Use -1 for pins that do not apply
88const int8_t modemVccPin = -2; // MCU pin controlling modem power
89const int8_t modemResetPin = 20; // MCU pin connected to modem reset pin
90const int8_t modemLEDPin =
91 redLED; // MCU pin connected an LED to show modem status
92
93// Network connection information
94const char* wifiId = "xxxxx"; // The WiFi access point
95const char* wifiPwd = "xxxxx"; // The password for connecting to WiFi
96
97// Create the loggerModem object
98EspressifESP8266 modemESP(&modemSerial, modemVccPin, modemResetPin, wifiId,
99 wifiPwd);
100// Create an extra reference to the modem by a generic name
101EspressifESP8266 modem = modemESP;
102/** End [espressif_esp8266] */
103
104
105// ==========================================================================
106// Using the Processor as a Sensor
107// ==========================================================================
108/** Start [processor_sensor] */
109#include <sensors/ProcessorStats.h>
110
111// Create the main processor chip "sensor" - for general metadata
112const char* mcuBoardVersion = "v1.1";
113ProcessorStats mcuBoard(mcuBoardVersion);
114/** End [processor_sensor] */
115
116
117// ==========================================================================
118// Maxim DS3231 RTC (Real Time Clock)
119// ==========================================================================
120/** Start [ds3231] */
121#include <sensors/MaximDS3231.h>
122
123// Create a DS3231 sensor object
124MaximDS3231 ds3231(1);
125/** End [ds3231] */
126
127
128// ==========================================================================
129// Campbell OBS 3 / OBS 3+ Analog Turbidity Sensor
130// ==========================================================================
131/** Start [obs3] */
132#include <sensors/CampbellOBS3.h>
133
134const int8_t OBS3Power = sensorPowerPin; // Power pin (-1 if unconnected)
135const uint8_t OBS3NumberReadings = 10;
136const uint8_t ADSi2c_addr = 0x48; // The I2C address of the ADS1115 ADC
137// Campbell OBS 3+ *Low* Range Calibration in Volts
138const int8_t OBSLowADSChannel = 0; // ADS channel for *low* range output
139const float OBSLow_A = 0.000E+00; // "A" value (X^2) [*low* range]
140const float OBSLow_B = 1.000E+00; // "B" value (X) [*low* range]
141const float OBSLow_C = 0.000E+00; // "C" value [*low* range]
142
143// Create a Campbell OBS3+ *low* range sensor object
144CampbellOBS3 osb3low(OBS3Power, OBSLowADSChannel, OBSLow_A, OBSLow_B, OBSLow_C,
145 ADSi2c_addr, OBS3NumberReadings);
146
147
148// Campbell OBS 3+ *High* Range Calibration in Volts
149const int8_t OBSHighADSChannel = 1; // ADS channel for *high* range output
150const float OBSHigh_A = 0.000E+00; // "A" value (X^2) [*high* range]
151const float OBSHigh_B = 1.000E+00; // "B" value (X) [*high* range]
152const float OBSHigh_C = 0.000E+00; // "C" value [*high* range]
153
154// Create a Campbell OBS3+ *high* range sensor object
155CampbellOBS3 osb3high(OBS3Power, OBSHighADSChannel, OBSHigh_A, OBSHigh_B,
156 OBSHigh_C, ADSi2c_addr, OBS3NumberReadings);
157/** End [obs3] */
158
159
160// ==========================================================================
161// Meter Hydros 21 Conductivity, Temperature, and Depth Sensor
162// ==========================================================================
163/** Start [hydros21] */
164#include <sensors/MeterHydros21.h>
165
166const char* hydrosSDI12address = "1"; // The SDI-12 Address of the Hydros 21
167const uint8_t hydrosNumberReadings = 6; // The number of readings to average
168const int8_t SDI12Power = sensorPowerPin; // Power pin (-1 if unconnected)
169const int8_t SDI12Data = 7; // The SDI12 data pin
170
171// Create a Meter Hydros 21 sensor object
172MeterHydros21 hydros21(*hydrosSDI12address, SDI12Power, SDI12Data,
173 hydrosNumberReadings);
174/** End [hydros21] */
175
176
177// ==========================================================================
178// Creating the Variable Array[s] and Filling with Variable Objects
179// ==========================================================================
180/** Start [variable_arrays] */
181Variable* variableList[] = {
182 new MeterHydros21_Cond(&hydros21, "12345678-abcd-1234-ef00-1234567890ab"),
183 new MeterHydros21_Temp(&hydros21, "12345678-abcd-1234-ef00-1234567890ab"),
184 new MeterHydros21_Depth(&hydros21, "12345678-abcd-1234-ef00-1234567890ab"),
185 new CampbellOBS3_Turbidity(&osb3low, "12345678-abcd-1234-ef00-1234567890ab",
186 "TurbLow"),
187 new CampbellOBS3_Turbidity(
188 &osb3high, "12345678-abcd-1234-ef00-1234567890ab", "TurbHigh"),
189 new ProcessorStats_Battery(&mcuBoard,
190 "12345678-abcd-1234-ef00-1234567890ab"),
191 new MaximDS3231_Temp(&ds3231, "12345678-abcd-1234-ef00-1234567890ab"),
192 new Modem_RSSI(&modem, "12345678-abcd-1234-ef00-1234567890ab")};
193// Count up the number of pointers in the array
194int variableCount = sizeof(variableList) / sizeof(variableList[0]);
195
196// Create the VariableArray object
197VariableArray varArray;
198/** End [variable_arrays] */
199
200
201// ==========================================================================
202// The Logger Object[s]
203// ==========================================================================
204/** Start [loggers] */
205// Create a logger instance
206Logger dataLogger;
207/** End [loggers] */
208
209
210// ==========================================================================
211// Creating Data Publisher[s]
212// ==========================================================================
213// Create a channel with fields on ThingSpeak in advance
214// The fields will be sent in exactly the order they are in the variable array.
215// Any custom name or identifier given to the field on ThingSpeak is irrelevant.
216// No more than 8 fields of data can go to any one channel. Any fields beyond
217// the eighth in the array will be ignored.
218const char* thingSpeakMQTTKey =
219 "XXXXXXXXXXXXXXXX"; // Your MQTT API Key from Account > MyProfile.
220const char* thingSpeakChannelID =
221 "######"; // The numeric channel id for your channel
222const char* thingSpeakChannelKey =
223 "XXXXXXXXXXXXXXXX"; // The Write API Key for your channel
224
225// Create a data publisher for ThingSpeak
226#include <publishers/ThingSpeakPublisher.h>
227ThingSpeakPublisher TsMqtt;
228/** End [loggers] */
229
230
231// ==========================================================================
232// Working Functions
233// ==========================================================================
234/** Start [working_functions] */
235// Flashes the LED's on the primary board
236void greenredflash(uint8_t numFlash = 4, uint8_t rate = 75) {
237 for (uint8_t i = 0; i < numFlash; i++) {
238 digitalWrite(greenLED, HIGH);
239 digitalWrite(redLED, LOW);
240 delay(rate);
241 digitalWrite(greenLED, LOW);
242 digitalWrite(redLED, HIGH);
243 delay(rate);
244 }
245 digitalWrite(redLED, LOW);
246}
247
248// Reads the battery voltage
249// NOTE: This will actually return the battery level from the previous update!
250float getBatteryVoltage() {
251 if (mcuBoard.sensorValues[0] == -9999) mcuBoard.update();
252 return mcuBoard.sensorValues[0];
253}
254/** End [working_functions] */
255
256
257// ==========================================================================
258// Arduino Setup Function
259// ==========================================================================
260/** Start [setup] */
261void setup() {
262 // Start the primary serial connection
263 Serial.begin(serialBaud);
264
265 // Print a start-up note to the first serial port
266 Serial.print(F("Now running "));
267 Serial.print(sketchName);
268 Serial.print(F(" on Logger "));
269 Serial.println(LoggerID);
270 Serial.println();
271
272 Serial.print(F("Using ModularSensors Library version "));
273 Serial.println(MODULAR_SENSORS_VERSION);
274 Serial.print(F("TinyGSM Library version "));
275 Serial.println(TINYGSM_VERSION);
276 Serial.println();
277
278 // Start the serial connection with the modem
279 modemSerial.begin(modemBaud);
280
281 // Set up pins for the LED's
282 pinMode(greenLED, OUTPUT);
283 digitalWrite(greenLED, LOW);
284 pinMode(redLED, OUTPUT);
285 digitalWrite(redLED, LOW);
286 // Blink the LEDs to show the board is on and starting up
287 greenredflash();
288
289 // Set the timezones for the logger/data and the RTC
290 // Logging in the given time zone
291 Logger::setLoggerTimeZone(timeZone);
292 // It is STRONGLY RECOMMENDED that you set the RTC to be in UTC (UTC+0)
293 Logger::setRTCTimeZone(0);
294
295 // Attach the modem and information pins to the logger
296 dataLogger.attachModem(modem);
297 modem.setModemLED(modemLEDPin);
298 dataLogger.setLoggerPins(wakePin, sdCardSSPin, sdCardPwrPin, buttonPin,
299 greenLED);
300
301 // Begin the variable array[s], logger[s], and publisher[s]
302 varArray.begin(variableCount, variableList);
303 dataLogger.begin(LoggerID, loggingInterval, &varArray);
304 TsMqtt.begin(dataLogger, &modem.gsmClient, thingSpeakMQTTKey,
305 thingSpeakChannelID, thingSpeakChannelKey);
306
307 // Note: Please change these battery voltages to match your battery
308 // Set up the sensors, except at lowest battery level
309 if (getBatteryVoltage() > 3.4) {
310 Serial.println(F("Setting up sensors..."));
311 varArray.setupSensors();
312 }
313
314 // Sync the clock if it isn't valid or we have battery to spare
315 if (getBatteryVoltage() > 3.55 || !dataLogger.isRTCSane()) {
316 // Synchronize the RTC with NIST
317 // This will also set up the modem
318 dataLogger.syncRTC();
319 }
320
321 // Create the log file, adding the default header to it
322 // Do this last so we have the best chance of getting the time correct and
323 // all sensor names correct
324 // Writing to the SD card can be power intensive, so if we're skipping
325 // the sensor setup we'll skip this too.
326 if (getBatteryVoltage() > 3.4) {
327 Serial.println(F("Setting up file on SD card"));
328 dataLogger.turnOnSDcard(
329 true); // true = wait for card to settle after power up
330 dataLogger.createLogFile(true); // true = write a new header
331 dataLogger.turnOffSDcard(
332 true); // true = wait for internal housekeeping after write
333 }
334
335 // Call the processor sleep
336 Serial.println(F("Putting processor to sleep"));
337 dataLogger.systemSleep();
338}
339/** End [setup] */
340
341
342// ==========================================================================
343// Arduino Loop Function
344// ==========================================================================
345/** Start [loop] */
346// Use this short loop for simple data logging and sending
347void loop() {
348 // Note: Please change these battery voltages to match your battery
349 // At very low battery, just go back to sleep
350 if (getBatteryVoltage() < 3.4) {
351 dataLogger.systemSleep();
352 }
353 // At moderate voltage, log data but don't send it over the modem
354 else if (getBatteryVoltage() < 3.55) {
355 dataLogger.logData();
356 }
357 // If the battery is good, send the data to the world
358 else {
359 dataLogger.logDataAndPublish();
360 }
361}
362/** End [loop] */