Example logging data and publishing to ThingSpeak.
Example logging data and publishing to ThingSpeak.=========================================================================
See the walkthrough page for detailed instructions.
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
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!
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
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] */
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
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.
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
93// Network connection information
94const char* wifiId = "xxxxx"; // The WiFi access point
95const char* wifiPwd = "xxxxx"; // The password for connecting to WiFi
97// Create the loggerModem object
98EspressifESP8266 modemESP(&modemSerial, modemVccPin, modemResetPin, wifiId,
100// Create an extra reference to the modem by a generic name
101EspressifESP8266 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
112const char* mcuBoardVersion = "v1.1";
113ProcessorStats 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
124MaximDS3231 ds3231(1);
128// ==========================================================================
129// Campbell OBS 3 / OBS 3+ Analog Turbidity Sensor
130// ==========================================================================
132#include <sensors/CampbellOBS3.h>
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]
143// Create a Campbell OBS3+ *low* range sensor object
144CampbellOBS3 osb3low(OBS3Power, OBSLowADSChannel, OBSLow_A, OBSLow_B, OBSLow_C,
145 ADSi2c_addr, OBS3NumberReadings);
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]
154// Create a Campbell OBS3+ *high* range sensor object
155CampbellOBS3 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>
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
171// Create a Meter Hydros 21 sensor object
172MeterHydros21 hydros21(*hydrosSDI12address, SDI12Power, SDI12Data,
173 hydrosNumberReadings);
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",
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]);
196// Create the VariableArray object
197VariableArray 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.
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
225// Create a data publisher for ThingSpeak
226#include <publishers/ThingSpeakPublisher.h>
227ThingSpeakPublisher TsMqtt;
231// ==========================================================================
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);
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!
250float 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();