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: 1 const char * thingSpeakMQTTKey = "XXXXXXXXXXXXXXXX" ; // Your MQTT API Key from Account > MyProfile.
2 const char * thingSpeakChannelID = "######" ; // The numeric channel id for your channel
3 const 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
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
8 ; Please visit documentation for the other options and examples
9 ; http://docs.platformio.org/page/projectconf.html
12 description = ModularSensors example sending data to ThingSpeak
30 -DSDI12_EXTERNAL_PCINT
31 -DNEOSWSERIAL_EXTERNAL_PCINT
32 -DMQTT_MAX_PACKET_SIZE = 240
33 -DTINY_GSM_RX_BUFFER = 64
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>
7 * @brief Example logging data and publishing to ThingSpeak.
9 * See [the walkthrough page](@ref example_thingspeak) for detailed
12 * @m_examplenavigation{example_thingspeak,}
13 * ======================================================================= */
15 // ==========================================================================
17 // ==========================================================================
19 #ifndef TINY_GSM_RX_BUFFER
20 #define TINY_GSM_RX_BUFFER 64
22 #ifndef TINY_GSM_YIELD_MS
23 #define TINY_GSM_YIELD_MS 2
25 #ifndef MQTT_MAX_PACKET_SIZE
26 #define MQTT_MAX_PACKET_SIZE 240
30 // ==========================================================================
31 // Include the libraries required for any data logger
32 // ==========================================================================
33 /** Start [includes] */
34 // The Arduino library is needed for every Arduino program.
37 // Include the main header for ModularSensors
38 #include <ModularSensors.h>
42 // ==========================================================================
43 // Data Logging Options
44 // ==========================================================================
45 /** Start [logging_options] */
46 // The name of this program file
47 const char * sketchName = "logging_to_ThingSpeak.ino" ;
48 // Logger ID, also becomes the prefix for the name of the data file on SD card
49 const char * LoggerID = "XXXXX" ;
50 // How frequently (in minutes) to log data
51 const uint8_t loggingInterval = 15 ;
52 // Your logger's timezone.
53 const int8_t timeZone = -5 ; // Eastern Standard Time
54 // NOTE: Daylight savings time will not be applied! Please use standard time!
56 // Set the input and output pins for the logger
57 // NOTE: Use -1 for pins that do not apply
58 const int32_t serialBaud = 115200 ; // Baud rate for debugging
59 const int8_t greenLED = 8 ; // Pin for the green LED
60 const int8_t redLED = 9 ; // Pin for the red LED
61 const int8_t buttonPin = 21 ; // Pin for debugging mode (ie, button pin)
62 const int8_t wakePin = 31 ; // MCU interrupt/alarm pin to wake from sleep
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
66 const int8_t sdCardPwrPin = -1 ; // MCU SD card power pin
67 const int8_t sdCardSSPin = 12 ; // SD card chip select/slave select pin
68 const int8_t sensorPowerPin = 22 ; // MCU pin controlling main sensor power
69 /** End [logging_options] */
72 // ==========================================================================
73 // Wifi/Cellular Modem Options
74 // ==========================================================================
75 /** Start [espressif_esp8266] */
76 // For almost anything based on the Espressif ESP8266 using the AT command
78 #include <modems/EspressifESP8266.h>
79 // Create a reference to the serial port for the modem
80 HardwareSerial & modemSerial = Serial1 ; // Use hardware serial if possible
81 const 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.
86 // Modem Pins - Describe the physical pin connection of your modem to your board
87 // NOTE: Use -1 for pins that do not apply
88 const int8_t modemVccPin = -2 ; // MCU pin controlling modem power
89 const int8_t modemResetPin = 20 ; // MCU pin connected to modem reset pin
90 const int8_t modemLEDPin =
91 redLED ; // MCU pin connected an LED to show modem status
93 // Network connection information
94 const char * wifiId = "xxxxx" ; // The WiFi access point
95 const char * wifiPwd = "xxxxx" ; // The password for connecting to WiFi
97 // Create the loggerModem object
98 EspressifESP8266 modemESP ( & modemSerial , modemVccPin , modemResetPin , wifiId ,
100 // Create an extra reference to the modem by a generic name
101 EspressifESP8266 modem = modemESP ;
102 /** End [espressif_esp8266] */
105 // ==========================================================================
106 // Using the Processor as a Sensor
107 // ==========================================================================
108 /** Start [processor_sensor] */
109 #include <sensors/ProcessorStats.h>
111 // Create the main processor chip "sensor" - for general metadata
112 const char * mcuBoardVersion = "v1.1" ;
113 ProcessorStats mcuBoard ( mcuBoardVersion );
114 /** End [processor_sensor] */
117 // ==========================================================================
118 // Maxim DS3231 RTC (Real Time Clock)
119 // ==========================================================================
121 #include <sensors/MaximDS3231.h>
123 // Create a DS3231 sensor object
124 MaximDS3231 ds3231 ( 1 );
128 // ==========================================================================
129 // Campbell OBS 3 / OBS 3+ Analog Turbidity Sensor
130 // ==========================================================================
132 #include <sensors/CampbellOBS3.h>
134 const int8_t OBS3Power = sensorPowerPin ; // Power pin (-1 if unconnected)
135 const uint8_t OBS3NumberReadings = 10 ;
136 const uint8_t ADSi2c_addr = 0x48 ; // The I2C address of the ADS1115 ADC
137 // Campbell OBS 3+ *Low* Range Calibration in Volts
138 const int8_t OBSLowADSChannel = 0 ; // ADS channel for *low* range output
139 const float OBSLow_A = 0.000E+00 ; // "A" value (X^2) [*low* range]
140 const float OBSLow_B = 1.000E+00 ; // "B" value (X) [*low* range]
141 const float OBSLow_C = 0.000E+00 ; // "C" value [*low* range]
143 // Create a Campbell OBS3+ *low* range sensor object
144 CampbellOBS3 osb3low ( OBS3Power , OBSLowADSChannel , OBSLow_A , OBSLow_B , OBSLow_C ,
145 ADSi2c_addr , OBS3NumberReadings );
148 // Campbell OBS 3+ *High* Range Calibration in Volts
149 const int8_t OBSHighADSChannel = 1 ; // ADS channel for *high* range output
150 const float OBSHigh_A = 0.000E+00 ; // "A" value (X^2) [*high* range]
151 const float OBSHigh_B = 1.000E+00 ; // "B" value (X) [*high* range]
152 const float OBSHigh_C = 0.000E+00 ; // "C" value [*high* range]
154 // Create a Campbell OBS3+ *high* range sensor object
155 CampbellOBS3 osb3high ( OBS3Power , OBSHighADSChannel , OBSHigh_A , OBSHigh_B ,
156 OBSHigh_C , ADSi2c_addr , OBS3NumberReadings );
160 // ==========================================================================
161 // Meter Hydros 21 Conductivity, Temperature, and Depth Sensor
162 // ==========================================================================
163 /** Start [hydros21] */
164 #include <sensors/MeterHydros21.h>
166 const char * hydrosSDI12address = "1" ; // The SDI-12 Address of the Hydros 21
167 const uint8_t hydrosNumberReadings = 6 ; // The number of readings to average
168 const int8_t SDI12Power = sensorPowerPin ; // Power pin (-1 if unconnected)
169 const int8_t SDI12Data = 7 ; // The SDI12 data pin
171 // Create a Meter Hydros 21 sensor object
172 MeterHydros21 hydros21 ( * hydrosSDI12address , SDI12Power , SDI12Data ,
173 hydrosNumberReadings );
177 // ==========================================================================
178 // Creating the Variable Array[s] and Filling with Variable Objects
179 // ==========================================================================
180 /** Start [variable_arrays] */
181 Variable * 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" ,
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
194 int variableCount = sizeof ( variableList ) / sizeof ( variableList [ 0 ]);
196 // Create the VariableArray object
197 VariableArray varArray ;
198 /** End [variable_arrays] */
201 // ==========================================================================
202 // The Logger Object[s]
203 // ==========================================================================
204 /** Start [loggers] */
205 // Create a logger instance
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.
218 const char * thingSpeakMQTTKey =
219 "XXXXXXXXXXXXXXXX" ; // Your MQTT API Key from Account > MyProfile.
220 const char * thingSpeakChannelID =
221 "######" ; // The numeric channel id for your channel
222 const char * thingSpeakChannelKey =
223 "XXXXXXXXXXXXXXXX" ; // The Write API Key for your channel
225 // Create a data publisher for ThingSpeak
226 #include <publishers/ThingSpeakPublisher.h>
227 ThingSpeakPublisher TsMqtt ;
231 // ==========================================================================
233 // ==========================================================================
234 /** Start [working_functions] */
235 // Flashes the LED's on the primary board
236 void 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 );
241 digitalWrite ( greenLED , LOW );
242 digitalWrite ( redLED , HIGH );
245 digitalWrite ( redLED , LOW );
248 // Reads the battery voltage
249 // NOTE: This will actually return the battery level from the previous update!
250 float getBatteryVoltage () {
251 if ( mcuBoard . sensorValues [ 0 ] == -9999 ) mcuBoard . update ();
252 return mcuBoard . sensorValues [ 0 ];
254 /** End [working_functions] */
257 // ==========================================================================
258 // Arduino Setup Function
259 // ==========================================================================
262 // Start the primary serial connection
263 Serial . begin ( serialBaud );
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 );
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 );
278 // Start the serial connection with the modem
279 modemSerial . begin ( modemBaud );
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
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 );
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 ,
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 );
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 ();
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 ();
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
335 // Call the processor sleep
336 Serial . println ( F ( "Putting processor to sleep" ));
337 dataLogger . systemSleep ();
342 // ==========================================================================
343 // Arduino Loop Function
344 // ==========================================================================
346 // Use this short loop for simple data logging and sending
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 ();
353 // At moderate voltage, log data but don't send it over the modem
354 else if ( getBatteryVoltage () < 3.55 ) {
355 dataLogger . logData ();
357 // If the battery is good, send the data to the world
359 dataLogger . logDataAndPublish ();