Forum Replies Created
-
AuthorPosts
-
Thanks Shannon. Please let me know as I will likely order a few of these and some mayfly 1.1’s.
Appreciate the hard work.
James
Hi Shannon,
Do you have any idea when the RS-485 half shields are likely to be in stock?
James
Hi @ddrummonrtp and @aufdenkampe,
I’m interested in using these mDot modules to connect with the Helium network.
Dale or Anthony, would you mind posting your code to integrate mDot modules with the Mayfly?
Thanks for your help!
Regards,
James
<h2 class=”user-nicename”></h2>@shicks, thanks for your help anyway Shannon. @aufdenkampe, any insight on the code above would be greatly appreciated.
@neilh20, yes all setups are the same. Some work fine, others have issues with dropping out. I have spare Mayflies and a spare CTD, but no spare turbidity sensor. Did you ever end up producing your Mayfly wings for the 0.5? This might just be another case of rubbish RS485/ttl’s.I kinda wish my project was delayed by six months so I could get the version 1.0’s with the new modbus wing!
James
Hi @shicks. I’m just wondering if you saw anything in the code above that might be causing this problem?
Regards,
James
I’m leaning more towards an interaction with the MODBUS wing. I had one station that produced -9999’s constantly when the Turbidity sensor was plugged in, and operated fine when I removed the MODBUS wing. This drove me nuts until Anthony pointed me towards the complex loop code where I set the Turbidity sensor to low after each reading to avoid bleeding voltage. I have subsequently uploaded the new code to all stations, which I assumed would fix the intermittent problems, but that doesn’t seem to be the case.
Other factors: there is no damage to the cables, no corrosion, and no perceivable storm damage.
Shannon, I’m using v0.5b and the sensor is powered from the grove slot (D10/D11). I changed the voltage jumper to 5v because 3.3v was resulting in -9999 values (I assume because of brownout?).
I haven’t tried unplugging the MODBUS wing, but I bet the CTD record would be perfect if I did. I can test this later this week if we don’t find another solution.
Perhaps it’s my code (see below)? Can either of you see any obvious errors?
Thanks for your help.
James
C++123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546/*****************************************************************************simple_logging.inoWritten By: Sara Damiano (sdamiano@stroudcenter.org)Development Environment: PlatformIOHardware Platform: EnviroDIY Mayfly Arduino DataloggerSoftware License: BSD-3.Copyright (c) 2017, Stroud Water Research Center (SWRC)and the EnviroDIY Development TeamThis sketch is an example of logging data to an SD cardDISCLAIMER:THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN.*****************************************************************************/// ==========================================================================// Defines for the Arduino IDE// In PlatformIO, set these build flags in your platformio.ini// ==========================================================================#ifndef TINY_GSM_RX_BUFFER#define TINY_GSM_RX_BUFFER 64#endif#ifndef TINY_GSM_YIELD_MS#define TINY_GSM_YIELD_MS 2#endif#ifndef MQTT_MAX_PACKET_SIZE#define MQTT_MAX_PACKET_SIZE 240#endif// ==========================================================================// Include the base required libraries// ==========================================================================#include <Arduino.h> // The base Arduino library#include <EnableInterrupt.h> // for external and pin change interrupts#include <LoggerBase.h> // The modular sensors library//#include <Adafruit_ADS1015.h>//Adafruit_ADS1115 ads; /* Use this for the Mayfly because of the onboard 16-bit ADS1115 *///#include <AltSoftSerial.h>//#include <YosemitechModbus.h>// ==========================================================================// Data Logger Settings// ==========================================================================// The name of this fileconst char *sketchName = "05_Patiki.ino";// Logger ID, also becomes the prefix for the name of the data file on SD cardconst char *LoggerID = "Patiki";// How frequently (in minutes) to log dataconst uint8_t loggingInterval = 15;// Your logger's timezone.const int8_t timeZone = 12; // Eastern Standard Time// NOTE: Daylight savings time will not be applied! Please use standard time!// ==========================================================================// Primary Arduino-Based Board and Processor// ==========================================================================#include <sensors/ProcessorStats.h>const long serialBaud = 115200; // Baud rate for the primary serial port for debuggingconst int8_t greenLED = 8; // MCU pin for the green LED (-1 if not applicable)const int8_t redLED = 9; // MCU pin for the red LED (-1 if not applicable)const int8_t buttonPin = 21; // MCU pin for a button to use to enter debugging mode (-1 if not applicable)const int8_t wakePin = A7; // MCU interrupt/alarm pin to wake from sleep// Set the wake pin to -1 if you do not want the main processor to sleep.// In a SAMD system where you are using the built-in rtc, set wakePin to 1const int8_t sdCardPwrPin = -1; // MCU SD card power pin (-1 if not applicable)const int8_t sdCardSSPin = 12; // MCU SD card chip select/slave select pin (must be given!)const int8_t sensorPowerPin = 22; // MCU pin controlling main sensor power (-1 if not applicable)// Create the main processor chip "sensor" - for general metadataconst char *mcuBoardVersion = "v0.5b";ProcessorStats mcuBoard(mcuBoardVersion);// ==========================================================================// Wifi/Cellular Modem Settings// ==========================================================================// Create a reference to the serial port for the modemHardwareSerial &modemSerial = Serial1; // Use hardware serial if possible// Modem Pins - Describe the physical pin connection of your modem to your boardconst int8_t modemVccPin = -1; // MCU pin controlling modem power (-1 if not applicable)//const bool useCTSforStatus = false; // Flag to use the XBee CTS pin for statusconst int8_t modemStatusPin = 19; // MCU pin used to read modem status (-1 if not applicable)const int8_t modemResetPin = 20; // MCU pin connected to modem reset pin (-1 if unconnected)const int8_t modemSleepRqPin = 23; // MCU pin used for modem sleep/wake request (-1 if not applicable)const int8_t modemLEDPin = redLED; // MCU pin connected an LED to show modem status (-1 if unconnected)// // Network connection information// Network connection informationconst char *apn = "m2m"; // The APN for the gprs connection// const char *wifiId = "Dare_Family"; // The WiFi access point, unnecessary for gprs// const char *wifiPwd = "119HarveyStreet"; // The password for connecting to WiFi, unnecessary for gprs// ==========================================================================// The modem object// Note: Don't use more than one!// ==========================================================================//#elif defined MS_BUILD_TESTING && defined MS_BUILD_TEST_XBEE_LTE_B// For the u-blox SARA R410M based Digi LTE-M XBee3// NOTE: According to the manual, this should be less stable than transparent// mode, but my experience is the complete reverse.#include <modems/DigiXBeeLTEBypass.h>//#include <modems/SodaqDigiXBeeLTEBypass.h>const long modemBaud = 9600; // All XBee's use 9600 by defaultconst bool useCTSforStatus = false; // Flag to use the XBee CTS pin for status// NOTE: If possible, use the STATUS/SLEEP_not (XBee pin 13) for status, but// the CTS pin can also be used if necessaryDigiXBeeLTEBypass modemXBLTEB(&modemSerial,modemVccPin, modemStatusPin, useCTSforStatus,modemResetPin, modemSleepRqPin,apn);// Create an extra reference to the modem by a generic name (not necessary)DigiXBeeLTEBypass modem = modemXBLTEB;// ==========================================================================// ==========================================================================// Maxim DS3231 RTC (Real Time Clock)// ==========================================================================#include <sensors/MaximDS3231.h> // Includes wrapper functions for Maxim DS3231 RTC// Create a DS3231 sensor object, using this constructor function:MaximDS3231 ds3231(1);// ==========================================================================// Meter Hydros 21 Conductivity, Temperature, and Depth Sensor// ==========================================================================/** Start [hydros21] */#include <sensors/DecagonCTD.h>const char* CTDSDI12address = "1"; // The SDI-12 Address of the CTDconst uint8_t CTDNumberReadings = 6; // The number of readings to averageconst int8_t CTDPower = sensorPowerPin; // Power pin (-1 if unconnected)const int8_t CTDData = 11; // The SDI12 data pin// Create a Decagon CTD sensor objectDecagonCTD ctd(*CTDSDI12address, CTDPower, CTDData, CTDNumberReadings);// Create conductivity, temperature, and depth variable pointers for the CTD//Variable* ctdCond = new DecagonCTD_Cond(&ctd,// "12345678-abcd-1234-ef00-1234567890ab");//Variable* ctdTemp = new DecagonCTD_Temp(&ctd,// "12345678-abcd-1234-ef00-1234567890ab");//Variable* ctdDepth =// new DecagonCTD_Depth(&ctd, "12345678-abcd-1234-ef00-1234567890ab");/** End [hydros21] */// ==========================================================================// Yosemitech Y511 Turbidity Sensor with Wiper// ==========================================================================/** Start [y511] */#include <sensors/YosemitechY511.h>#include <AltSoftSerial.h>AltSoftSerial altSoftSerial;// Create a reference to the serial port for modbus// Extra hardware and software serial ports are created in the "Settings for// Additional Serial Ports" section#if defined ARDUINO_ARCH_SAMD || defined ATMEGA2560HardwareSerial& y511modbusSerial = Serial2; // Use hardware serial if possible#elseAltSoftSerial& y511modbusSerial = altSoftSerial; // For software serial// NeoSWSerial& y511modbusSerial = neoSSerial1; // For software serial#endifbyte y511ModbusAddress = 0x01; // The modbus address of the Y511const int8_t y511AdapterPower =sensorPowerPin; // RS485 adapter power pin (-1 if unconnected)const int8_t y511SensorPower = -1; // Sensor power pinconst int8_t y511EnablePin = -1; // Adapter RE/DE pin (-1 if not applicable)const uint8_t y511NumberReadings = 5;// The manufacturer recommends averaging 10 readings, but we take 5 to minimize// power consumption// Create a Y511-A Turbidity sensor objectYosemitechY511 y511(y511ModbusAddress, y511modbusSerial, y511AdapterPower,y511SensorPower, y511EnablePin, y511NumberReadings);// Create turbidity and temperature variable pointers for the Y511//Variable* y511Turb =// new YosemitechY511_Turbidity(&y511, "12345678-abcd-1234-ef00-1234567890ab");//Variable* y511Temp =// new YosemitechY511_Temp(&y511, "12345678-abcd-1234-ef00-1234567890ab");/** End [y511] */// ==========================================================================// Creating the Variable Array[s] and Filling with Variable Objects// ==========================================================================Variable *variableList[] = {//new ProcessorStats_SampleNumber(&mcuBoard),//new ProcessorStats_FreeRam(&mcuBoard),new ProcessorStats_Battery(&mcuBoard,"03c5abcd-dfd6-4c58-b028-5cf6e2c95d57"),new MaximDS3231_Temp(&ds3231,"1cd4ab1f-507a-4072-a8dc-e2927658f59e"),new DecagonCTD_Cond(&ctd, "777c00d8-4beb-4075-94bb-b24889d0d7b6"),new DecagonCTD_Temp(&ctd, "bafbbb51-9d2d-4cd9-aa30-e90911bd0bb5"),new DecagonCTD_Depth(&ctd, "93faac2a-9db2-45cc-808e-d26935e0c3b3"),new YosemitechY511_Turbidity(&y511, "ced82100-f7bb-4cfb-994c-0981c1bb92ca"),new YosemitechY511_Temp(&y511, "833d69ef-c52f-4480-8e80-151322fb8532")// Additional sensor variables can be added here, by copying the syntax// for creating the variable pointer (FORM1) from the <code>menu_a_la_carte.ino</code> example// The example code snippets in the wiki are primarily FORM2.};// Count up the number of pointers in the arrayint variableCount = sizeof(variableList) / sizeof(variableList[0]);// Create the VariableArray objectVariableArray varArray(variableCount, variableList);// ==========================================================================// The Logger Object[s]// ==========================================================================// Create a logger instanceLogger dataLogger(LoggerID, loggingInterval, &varArray);// ==========================================================================// A Publisher to Monitor My Watershed / EnviroDIY Data Sharing Portal// ==========================================================================// Device registration and sampling feature information can be obtained after// registration at https://monitormywatershed.org or https://data.envirodiy.orgconst char *registrationToken = "9ce32f4c-faeb-4657-8fdb-31c515b66348"; // Device registration tokenconst char *samplingFeature = "65c04ec5-acd2-46fa-8c09-3a1ebd05672f"; // Sampling feature UUID// const char *UUIDs[] = // UUID array for device sensors// {// "0bc19c50-67d8-4012-9e17-fb32db82f1ca", // Temperature (Maxim_DS18B20_Temp)// "846f84dc-4455-47f3-bd38-51a21e20fa50" // Temperature (Maxim_DS3231_Temp)// };// Create a data publisher for the EnviroDIY/WikiWatershed POST endpoint#include <publishers/EnviroDIYPublisher.h>EnviroDIYPublisher EnviroDIYPOST(dataLogger, &modem.gsmClient, registrationToken, samplingFeature);// ==========================================================================// Working Functions// ==========================================================================// Flashes the LED's on the primary boardvoid greenredflash(uint8_t numFlash = 4, uint8_t rate = 75){for (uint8_t i = 0; i < numFlash; i++) {digitalWrite(greenLED, HIGH);digitalWrite(redLED, LOW);delay(rate);digitalWrite(greenLED, LOW);digitalWrite(redLED, HIGH);delay(rate);}digitalWrite(redLED, LOW);}// Read's the battery voltage// NOTE: This will actually return the battery level from the previous update!float getBatteryVoltage(){if (mcuBoard.sensorValues[0] == -9999) mcuBoard.update();return mcuBoard.sensorValues[0];}//Median Funtion// calculate a median for set of values in bufferint getMedianNum(int bArray[], int iFilterLen){ int bTab[iFilterLen];for (byte i = 0; i<iFilterLen; i++)bTab[i] = bArray[i]; // copy input array into BTab[] arrayint i, j, bTemp;for (j = 0; j < iFilterLen - 1; j++) // put array in ascending order{ for (i = 0; i < iFilterLen - j - 1; i++){ if (bTab[i] > bTab[i + 1]){ bTemp = bTab[i];bTab[i] = bTab[i + 1];bTab[i + 1] = bTemp;}}}if ((iFilterLen & 1) > 0) // check to see if iFilterlen is odd or even using & (bitwise AND) i.e if length &AND 1 is TRUE (>0)bTemp = bTab[(iFilterLen - 1) / 2]; // then then it is odd, and should take the central valueelsebTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2; // if even then take aveage of two central valuesreturn bTemp;} //end getmedianNum// ==========================================================================// Main setup function// ==========================================================================void setup(){// Wait for USB connection to be established by PC// NOTE: Only use this when debugging - if not connected to a PC, this// could prevent the script from starting#if defined SERIAL_PORT_USBVIRTUALwhile (!SERIAL_PORT_USBVIRTUAL && (millis() < 10000)){}#endif// Start the primary serial connectionSerial.begin(serialBaud);// Print a start-up note to the first serial portSerial.print(F("Now running "));Serial.print(sketchName);Serial.print(F(" on Logger "));Serial.println(LoggerID);Serial.println();Serial.print(F("Using ModularSensors Library version "));Serial.println(MODULAR_SENSORS_VERSION);Serial.print(F("TinyGSM Library version "));Serial.println(TINYGSM_VERSION);Serial.println();// Allow interrupts for software serial#if defined SoftwareSerial_ExtInts_henableInterrupt(softSerialRx, SoftwareSerial_ExtInts::handle_interrupt, CHANGE);#endif#if defined NeoSWSerial_henableInterrupt(neoSSerial1Rx, neoSSerial1ISR, CHANGE);#endif// Start the serial connection with the modemmodemSerial.begin(modemBaud);// Start the stream for the modbus sensors; all currently supported modbus sensors use 9600 baudy511modbusSerial.begin(9600);// Set up pins for the LED'spinMode(greenLED, OUTPUT);digitalWrite(greenLED, LOW);pinMode(redLED, OUTPUT);digitalWrite(redLED, LOW);// Blink the LEDs to show the board is on and starting upgreenredflash();// Set the timezones for the logger/data and the RTC// Logging in the given time zoneLogger::setLoggerTimeZone(timeZone);// It is STRONGLY RECOMMENDED that you set the RTC to be in UTC (UTC+0)Logger::setRTCTimeZone(0);// Attach the modem and information pins to the loggerdataLogger.attachModem(modem);modem.setModemLED(modemLEDPin);dataLogger.setLoggerPins(wakePin, sdCardSSPin, sdCardPwrPin, buttonPin, greenLED);// Begin the loggerdataLogger.begin();// Note: Please change these battery voltages to match your battery// Set up the sensors, except at lowest battery levelif (getBatteryVoltage() > 3.4){Serial.println(F("Setting up sensors..."));varArray.setupSensors();}// Sync the clock if it isn't valid or we have battery to spareif (getBatteryVoltage() > 3.55 || !dataLogger.isRTCSane()){// Synchronize the RTC with NIST// This will also set up the modemdataLogger.syncRTC();}// Create the log file, adding the default header to it// Do this last so we have the best chance of getting the time correct and// all sensor names correct// Writing to the SD card can be power intensive, so if we're skipping// the sensor setup we'll skip this too.if (getBatteryVoltage() > 3.4){Serial.println(F("Setting up file on SD card"));dataLogger.turnOnSDcard(true); // true = wait for card to settle after power updataLogger.createLogFile(true); // true = write a new headerdataLogger.turnOffSDcard(true); // true = wait for internal housekeeping after write}// Set up some of the power pins so the board boots up with them off// NOTE: This isn't necessary at all. The logger begin() function// should leave all power pins off when it finishes.if (modemVccPin >= 0){pinMode(modemVccPin, OUTPUT);digitalWrite(modemVccPin, LOW);pinMode(modemSleepRqPin, OUTPUT); // <- AddeddigitalWrite(modemSleepRqPin, HIGH); // <- Added}// Call the processor sleepSerial.println(F("Putting processor to sleep\n"));dataLogger.systemSleep();}// ==========================================================================// Main loop function// ==========================================================================/** Start [complex_loop] */// Use this long loop when you want to do something special// Because of the way alarms work on the RTC, it will wake the processor and// start the loop every minute exactly on the minute.// The processor may also be woken up by another interrupt or level change on a// pin - from a button or some other input.// The "if" statements in the loop determine what will happen - whether the// sensors update, testing mode starts, or it goes back to sleep.void loop() {// Reset the watchdogdataLogger.watchDogTimer.resetWatchDog();// Assuming we were woken up by the clock, check if the current time is an// even interval of the logging interval// We're only doing anything at all if the battery is above 3.4Vif (dataLogger.checkInterval() && getBatteryVoltage() > 3.4) {// Flag to notify that we're in already awake and logging a pointLogger::isLoggingNow = true;dataLogger.watchDogTimer.resetWatchDog();// Print a line to show new readingSerial.println(F("------------------------------------------"));// Turn on the LED to show we're taking a readingdataLogger.alertOn();// Power up the SD Card, but skip any waits after power updataLogger.turnOnSDcard(false);dataLogger.watchDogTimer.resetWatchDog();// Turn on the modem to let it start searching for the network// Only turn the modem on if the battery at the last interval was high// enough// NOTE: if the modemPowerUp function is not run before the// completeUpdate// function is run, the modem will not be powered and will not// return a signal strength reading.if (getBatteryVoltage() > 3.6) modem.modemPowerUp();// Start the stream for the modbus sensors, if your RS485 adapter bleeds// current from data pins when powered off & you stop modbus serial// connection with digitalWrite(5, LOW), below.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833altSoftSerial.begin(9600);// Do a complete update on the variable array.// This this includes powering all of the sensors, getting updated// values, and turing them back off.// NOTE: The wake function for each sensor should force sensor setup// to run if the sensor was not previously set up.varArray.completeUpdate();dataLogger.watchDogTimer.resetWatchDog();// Reset modbus serial pins to LOW, if your RS485 adapter bleeds power// on sleep, because Modbus Stop bit leaves these pins HIGH.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833digitalWrite(5, LOW); // Reset AltSoftSerial Tx pin to LOWdigitalWrite(6, LOW); // Reset AltSoftSerial Rx pin to LOW// Create a csv data record and save it to the log filedataLogger.logToSD();dataLogger.watchDogTimer.resetWatchDog();// Connect to the network// Again, we're only doing this if the battery is doing wellif (getBatteryVoltage() > 3.55) {//Serial.println(F("Waking up modem-------"));//Serial.println(F("Waking up") + modem.getModemName() + F("..."));modem.modemWake();dataLogger.watchDogTimer.resetWatchDog();if (modem.connectInternet()) {dataLogger.watchDogTimer.resetWatchDog();// Publish data to remotesSerial.println(F("Modem connected to internet."));dataLogger.publishDataToRemotes();// Sync the clock at midnightdataLogger.watchDogTimer.resetWatchDog();if (Logger::markedEpochTime != 0 &&Logger::markedEpochTime % 86400 == 0) {Serial.println(F("Running a daily clock sync..."));dataLogger.setRTClock(modem.getNISTTime());dataLogger.watchDogTimer.resetWatchDog();modem.updateModemMetadata();dataLogger.watchDogTimer.resetWatchDog();}// Disconnect from the networkmodem.disconnectInternet();dataLogger.watchDogTimer.resetWatchDog();}// Turn the modem offmodem.modemSleepPowerDown();dataLogger.watchDogTimer.resetWatchDog();}// Cut power from the SD card - without additional housekeeping waitdataLogger.turnOffSDcard(false);dataLogger.watchDogTimer.resetWatchDog();// Turn off the LEDdataLogger.alertOff();// Print a line to show reading endedSerial.println(F("------------------------------------------\n"));// Unset flagLogger::isLoggingNow = false;}// Check if it was instead the testing interrupt that woke us upif (Logger::startTesting) {// Start the stream for the modbus sensors, if your RS485 adapter bleeds// current from data pins when powered off & you stop modbus serial// connection with digitalWrite(5, LOW), below.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833altSoftSerial.begin(9600);dataLogger.testingMode();}// Reset modbus serial pins to LOW, if your RS485 adapter bleeds power// on sleep, because Modbus Stop bit leaves these pins HIGH.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833digitalWrite(5, LOW); // Reset AltSoftSerial Tx pin to LOWdigitalWrite(6, LOW); // Reset AltSoftSerial Rx pin to LOW// Call the processor sleepdataLogger.systemSleep();}2022-01-18 at 3:19 PM in reply to: Interference between HYDROS CTD and Yosemitech Turbidity Sensor #16287Okay, after a good night’s sleep I decided to tackle this again and I think I have fixed it. I simply added a line before the internet connection loop:
1modem.modemWake();It’s now logging to MMW. Please let me know if this is fundamentally wrong or will cause problems in the future.
James
2022-01-17 at 7:50 PM in reply to: Interference between HYDROS CTD and Yosemitech Turbidity Sensor #16281Hi @aufdenkampe,
I have followed your advice and I think this is working, i.e., I am no longer having problems with -9999 values for the CTD.
However, the complex loop code is preventing publication of data to MMW. I’m sure this is something simple, but I can’t seem to figure it out.
I have tracked the issue to line 483 where the code checks to see if the modem is connected to the internet, i.e., ‘if(modem.connectInternet())’. The lights on the modem don’t seem to power up at all, and the loop just continues reading sensor values and storing it on the SD card. Am I missing something in the setup loop?
Thanks again for your help.
James
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540/*****************************************************************************simple_logging.inoWritten By: Sara Damiano (sdamiano@stroudcenter.org)Development Environment: PlatformIOHardware Platform: EnviroDIY Mayfly Arduino DataloggerSoftware License: BSD-3.Copyright (c) 2017, Stroud Water Research Center (SWRC)and the EnviroDIY Development TeamThis sketch is an example of logging data to an SD cardDISCLAIMER:THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN.*****************************************************************************/// ==========================================================================// Defines for the Arduino IDE// In PlatformIO, set these build flags in your platformio.ini// ==========================================================================#ifndef TINY_GSM_RX_BUFFER#define TINY_GSM_RX_BUFFER 64#endif#ifndef TINY_GSM_YIELD_MS#define TINY_GSM_YIELD_MS 2#endif#ifndef MQTT_MAX_PACKET_SIZE#define MQTT_MAX_PACKET_SIZE 240#endif// ==========================================================================// Include the base required libraries// ==========================================================================#include <Arduino.h> // The base Arduino library#include <EnableInterrupt.h> // for external and pin change interrupts#include <LoggerBase.h> // The modular sensors library//#include <Adafruit_ADS1015.h>//Adafruit_ADS1115 ads; /* Use this for the Mayfly because of the onboard 16-bit ADS1115 *///#include <AltSoftSerial.h>//#include <YosemitechModbus.h>// ==========================================================================// Data Logger Settings// ==========================================================================// The name of this fileconst char *sketchName = "08_Kokako.ino";// Logger ID, also becomes the prefix for the name of the data file on SD cardconst char *LoggerID = "Kokako";// How frequently (in minutes) to log dataconst uint8_t loggingInterval = 2;// Your logger's timezone.const int8_t timeZone = 12; // Eastern Standard Time// NOTE: Daylight savings time will not be applied! Please use standard time!// ==========================================================================// Primary Arduino-Based Board and Processor// ==========================================================================#include <sensors/ProcessorStats.h>const long serialBaud = 115200; // Baud rate for the primary serial port for debuggingconst int8_t greenLED = 8; // MCU pin for the green LED (-1 if not applicable)const int8_t redLED = 9; // MCU pin for the red LED (-1 if not applicable)const int8_t buttonPin = 21; // MCU pin for a button to use to enter debugging mode (-1 if not applicable)const int8_t wakePin = A7; // MCU interrupt/alarm pin to wake from sleep// Set the wake pin to -1 if you do not want the main processor to sleep.// In a SAMD system where you are using the built-in rtc, set wakePin to 1const int8_t sdCardPwrPin = -1; // MCU SD card power pin (-1 if not applicable)const int8_t sdCardSSPin = 12; // MCU SD card chip select/slave select pin (must be given!)const int8_t sensorPowerPin = 22; // MCU pin controlling main sensor power (-1 if not applicable)// Create the main processor chip "sensor" - for general metadataconst char *mcuBoardVersion = "v0.5b";ProcessorStats mcuBoard(mcuBoardVersion);// ==========================================================================// Wifi/Cellular Modem Settings// ==========================================================================// Create a reference to the serial port for the modemHardwareSerial &modemSerial = Serial1; // Use hardware serial if possible// Modem Pins - Describe the physical pin connection of your modem to your boardconst int8_t modemVccPin = -1; // MCU pin controlling modem power (-1 if not applicable)//const bool useCTSforStatus = false; // Flag to use the XBee CTS pin for statusconst int8_t modemStatusPin = 19; // MCU pin used to read modem status (-1 if not applicable)const int8_t modemResetPin = 20; // MCU pin connected to modem reset pin (-1 if unconnected)const int8_t modemSleepRqPin = 23; // MCU pin used for modem sleep/wake request (-1 if not applicable)const int8_t modemLEDPin = redLED; // MCU pin connected an LED to show modem status (-1 if unconnected)// // Network connection information// Network connection informationconst char *apn = "m2m"; // The APN for the gprs connection// const char *wifiId = "Dare_Family"; // The WiFi access point, unnecessary for gprs// const char *wifiPwd = "119HarveyStreet"; // The password for connecting to WiFi, unnecessary for gprs// ==========================================================================// The modem object// Note: Don't use more than one!// ==========================================================================//#elif defined MS_BUILD_TESTING && defined MS_BUILD_TEST_XBEE_LTE_B// For the u-blox SARA R410M based Digi LTE-M XBee3// NOTE: According to the manual, this should be less stable than transparent// mode, but my experience is the complete reverse.#include <modems/DigiXBeeLTEBypass.h>//#include <modems/SodaqDigiXBeeLTEBypass.h>const long modemBaud = 9600; // All XBee's use 9600 by defaultconst bool useCTSforStatus = false; // Flag to use the XBee CTS pin for status// NOTE: If possible, use the STATUS/SLEEP_not (XBee pin 13) for status, but// the CTS pin can also be used if necessaryDigiXBeeLTEBypass modemXBLTEB(&modemSerial,modemVccPin, modemStatusPin, useCTSforStatus,modemResetPin, modemSleepRqPin,apn);// Create an extra reference to the modem by a generic name (not necessary)DigiXBeeLTEBypass modem = modemXBLTEB;// ==========================================================================// ==========================================================================// Maxim DS3231 RTC (Real Time Clock)// ==========================================================================#include <sensors/MaximDS3231.h> // Includes wrapper functions for Maxim DS3231 RTC// Create a DS3231 sensor object, using this constructor function:MaximDS3231 ds3231(1);// ==========================================================================// Meter Hydros 21 Conductivity, Temperature, and Depth Sensor// ==========================================================================/** Start [hydros21] */#include <sensors/DecagonCTD.h>const char* CTDSDI12address = "1"; // The SDI-12 Address of the CTDconst uint8_t CTDNumberReadings = 6; // The number of readings to averageconst int8_t CTDPower = sensorPowerPin; // Power pin (-1 if unconnected)const int8_t CTDData = 11; // The SDI12 data pin// Create a Decagon CTD sensor objectDecagonCTD ctd(*CTDSDI12address, CTDPower, CTDData, CTDNumberReadings);// Create conductivity, temperature, and depth variable pointers for the CTD//Variable* ctdCond = new DecagonCTD_Cond(&ctd,// "12345678-abcd-1234-ef00-1234567890ab");//Variable* ctdTemp = new DecagonCTD_Temp(&ctd,// "12345678-abcd-1234-ef00-1234567890ab");//Variable* ctdDepth =// new DecagonCTD_Depth(&ctd, "12345678-abcd-1234-ef00-1234567890ab");/** End [hydros21] */// ==========================================================================// Yosemitech Y511 Turbidity Sensor with Wiper// ==========================================================================/** Start [y511] */#include <sensors/YosemitechY511.h>#include <AltSoftSerial.h>AltSoftSerial altSoftSerial;// Create a reference to the serial port for modbus// Extra hardware and software serial ports are created in the "Settings for// Additional Serial Ports" section#if defined ARDUINO_ARCH_SAMD || defined ATMEGA2560HardwareSerial& y511modbusSerial = Serial2; // Use hardware serial if possible#elseAltSoftSerial& y511modbusSerial = altSoftSerial; // For software serial// NeoSWSerial& y511modbusSerial = neoSSerial1; // For software serial#endifbyte y511ModbusAddress = 0x01; // The modbus address of the Y511const int8_t y511AdapterPower =sensorPowerPin; // RS485 adapter power pin (-1 if unconnected)const int8_t y511SensorPower = -1; // Sensor power pinconst int8_t y511EnablePin = -1; // Adapter RE/DE pin (-1 if not applicable)const uint8_t y511NumberReadings = 5;// The manufacturer recommends averaging 10 readings, but we take 5 to minimize// power consumption// Create a Y511-A Turbidity sensor objectYosemitechY511 y511(y511ModbusAddress, y511modbusSerial, y511AdapterPower,y511SensorPower, y511EnablePin, y511NumberReadings);// Create turbidity and temperature variable pointers for the Y511//Variable* y511Turb =// new YosemitechY511_Turbidity(&y511, "12345678-abcd-1234-ef00-1234567890ab");//Variable* y511Temp =// new YosemitechY511_Temp(&y511, "12345678-abcd-1234-ef00-1234567890ab");/** End [y511] */// ==========================================================================// Creating the Variable Array[s] and Filling with Variable Objects// ==========================================================================Variable *variableList[] = {//new ProcessorStats_SampleNumber(&mcuBoard),//new ProcessorStats_FreeRam(&mcuBoard),new ProcessorStats_Battery(&mcuBoard,"3cafc793-59d4-4a89-aaa4-f0f55aaa2a43"),new MaximDS3231_Temp(&ds3231,"85322878-f3c6-4013-bb70-f5d05a2bd3d4"),new DecagonCTD_Cond(&ctd, "30b1000a-90f3-40e9-8782-0ce03291a89a"),new DecagonCTD_Temp(&ctd, "4940af20-f35f-4d96-9eb4-09064d1ebf6a"),new DecagonCTD_Depth(&ctd, "a72b2617-9d34-43e0-8429-17e817a0d686"),new YosemitechY511_Turbidity(&y511, "6a179ddf-7d16-4b1b-98cd-ab3ed468e70d"),new YosemitechY511_Temp(&y511, "c01965dd-8952-4e0c-9201-f83fcfdc2bc8")// Additional sensor variables can be added here, by copying the syntax// for creating the variable pointer (FORM1) from the <code>menu_a_la_carte.ino</code> example// The example code snippets in the wiki are primarily FORM2.};// Count up the number of pointers in the arrayint variableCount = sizeof(variableList) / sizeof(variableList[0]);// Create the VariableArray objectVariableArray varArray(variableCount, variableList);// ==========================================================================// The Logger Object[s]// ==========================================================================// Create a logger instanceLogger dataLogger(LoggerID, loggingInterval, &varArray);// ==========================================================================// A Publisher to Monitor My Watershed / EnviroDIY Data Sharing Portal// ==========================================================================// Device registration and sampling feature information can be obtained after// registration at https://monitormywatershed.org or https://data.envirodiy.orgconst char *registrationToken = "3f8eb19c-11b1-4d81-a80d-e3443728ab03"; // Device registration tokenconst char *samplingFeature = "89551d76-a825-4357-94f2-23aa82b52cfe"; // Sampling feature UUID// const char *UUIDs[] = // UUID array for device sensors// {// "0bc19c50-67d8-4012-9e17-fb32db82f1ca", // Temperature (Maxim_DS18B20_Temp)// "846f84dc-4455-47f3-bd38-51a21e20fa50" // Temperature (Maxim_DS3231_Temp)// };// Create a data publisher for the EnviroDIY/WikiWatershed POST endpoint#include <publishers/EnviroDIYPublisher.h>EnviroDIYPublisher EnviroDIYPOST(dataLogger, &modem.gsmClient, registrationToken, samplingFeature);// ==========================================================================// Working Functions// ==========================================================================// Flashes the LED's on the primary boardvoid greenredflash(uint8_t numFlash = 4, uint8_t rate = 75){for (uint8_t i = 0; i < numFlash; i++) {digitalWrite(greenLED, HIGH);digitalWrite(redLED, LOW);delay(rate);digitalWrite(greenLED, LOW);digitalWrite(redLED, HIGH);delay(rate);}digitalWrite(redLED, LOW);}// Read's the battery voltage// NOTE: This will actually return the battery level from the previous update!float getBatteryVoltage(){if (mcuBoard.sensorValues[0] == -9999) mcuBoard.update();return mcuBoard.sensorValues[0];}//Median Funtion// calculate a median for set of values in bufferint getMedianNum(int bArray[], int iFilterLen){ int bTab[iFilterLen];for (byte i = 0; i<iFilterLen; i++)bTab[i] = bArray[i]; // copy input array into BTab[] arrayint i, j, bTemp;for (j = 0; j < iFilterLen - 1; j++) // put array in ascending order{ for (i = 0; i < iFilterLen - j - 1; i++){ if (bTab[i] > bTab[i + 1]){ bTemp = bTab[i];bTab[i] = bTab[i + 1];bTab[i + 1] = bTemp;}}}if ((iFilterLen & 1) > 0) // check to see if iFilterlen is odd or even using & (bitwise AND) i.e if length &AND 1 is TRUE (>0)bTemp = bTab[(iFilterLen - 1) / 2]; // then then it is odd, and should take the central valueelsebTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2; // if even then take aveage of two central valuesreturn bTemp;} //end getmedianNum// ==========================================================================// Main setup function// ==========================================================================void setup(){// Wait for USB connection to be established by PC// NOTE: Only use this when debugging - if not connected to a PC, this// could prevent the script from starting#if defined SERIAL_PORT_USBVIRTUALwhile (!SERIAL_PORT_USBVIRTUAL && (millis() < 10000)){}#endif// Start the primary serial connectionSerial.begin(serialBaud);// Print a start-up note to the first serial portSerial.print(F("Now running "));Serial.print(sketchName);Serial.print(F(" on Logger "));Serial.println(LoggerID);Serial.println();Serial.print(F("Using ModularSensors Library version "));Serial.println(MODULAR_SENSORS_VERSION);Serial.print(F("TinyGSM Library version "));Serial.println(TINYGSM_VERSION);Serial.println();// Allow interrupts for software serial#if defined SoftwareSerial_ExtInts_henableInterrupt(softSerialRx, SoftwareSerial_ExtInts::handle_interrupt, CHANGE);#endif#if defined NeoSWSerial_henableInterrupt(neoSSerial1Rx, neoSSerial1ISR, CHANGE);#endif// Start the serial connection with the modemmodemSerial.begin(modemBaud);// Start the stream for the modbus sensors; all currently supported modbus sensors use 9600 baudy511modbusSerial.begin(9600);// Set up pins for the LED'spinMode(greenLED, OUTPUT);digitalWrite(greenLED, LOW);pinMode(redLED, OUTPUT);digitalWrite(redLED, LOW);// Blink the LEDs to show the board is on and starting upgreenredflash();// Set the timezones for the logger/data and the RTC// Logging in the given time zoneLogger::setLoggerTimeZone(timeZone);// It is STRONGLY RECOMMENDED that you set the RTC to be in UTC (UTC+0)Logger::setRTCTimeZone(0);// Attach the modem and information pins to the loggerdataLogger.attachModem(modem);modem.setModemLED(modemLEDPin);dataLogger.setLoggerPins(wakePin, sdCardSSPin, sdCardPwrPin, buttonPin, greenLED);// Begin the loggerdataLogger.begin();// Note: Please change these battery voltages to match your battery// Set up the sensors, except at lowest battery levelif (getBatteryVoltage() > 3.4){Serial.println(F("Setting up sensors..."));varArray.setupSensors();}// Sync the clock if it isn't valid or we have battery to spareif (getBatteryVoltage() > 3.55 || !dataLogger.isRTCSane()){// Synchronize the RTC with NIST// This will also set up the modemdataLogger.syncRTC();}// Create the log file, adding the default header to it// Do this last so we have the best chance of getting the time correct and// all sensor names correct// Writing to the SD card can be power intensive, so if we're skipping// the sensor setup we'll skip this too.if (getBatteryVoltage() > 3.4){Serial.println(F("Setting up file on SD card"));dataLogger.turnOnSDcard(true); // true = wait for card to settle after power updataLogger.createLogFile(true); // true = write a new headerdataLogger.turnOffSDcard(true); // true = wait for internal housekeeping after write}// Set up some of the power pins so the board boots up with them off// NOTE: This isn't necessary at all. The logger begin() function// should leave all power pins off when it finishes.if (modemVccPin >= 0){pinMode(modemVccPin, OUTPUT);digitalWrite(modemVccPin, LOW);pinMode(modemSleepRqPin, OUTPUT); // <- AddeddigitalWrite(modemSleepRqPin, HIGH); // <- Added}// Call the processor sleepSerial.println(F("Putting processor to sleep\n"));dataLogger.systemSleep();}// ==========================================================================// Main loop function// ==========================================================================/** Start [complex_loop] */// Use this long loop when you want to do something special// Because of the way alarms work on the RTC, it will wake the processor and// start the loop every minute exactly on the minute.// The processor may also be woken up by another interrupt or level change on a// pin - from a button or some other input.// The "if" statements in the loop determine what will happen - whether the// sensors update, testing mode starts, or it goes back to sleep.void loop() {// Reset the watchdogdataLogger.watchDogTimer.resetWatchDog();// Assuming we were woken up by the clock, check if the current time is an// even interval of the logging interval// We're only doing anything at all if the battery is above 3.4Vif (dataLogger.checkInterval() && getBatteryVoltage() > 3.4) {// Flag to notify that we're in already awake and logging a pointLogger::isLoggingNow = true;dataLogger.watchDogTimer.resetWatchDog();// Print a line to show new readingSerial.println(F("------------------------------------------"));// Turn on the LED to show we're taking a readingdataLogger.alertOn();// Power up the SD Card, but skip any waits after power updataLogger.turnOnSDcard(false);dataLogger.watchDogTimer.resetWatchDog();// Turn on the modem to let it start searching for the network// Only turn the modem on if the battery at the last interval was high// enough// NOTE: if the modemPowerUp function is not run before the// completeUpdate// function is run, the modem will not be powered and will not// return a signal strength reading.if (getBatteryVoltage() > 3.6) modem.modemPowerUp();// Start the stream for the modbus sensors, if your RS485 adapter bleeds// current from data pins when powered off & you stop modbus serial// connection with digitalWrite(5, LOW), below.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833altSoftSerial.begin(9600);// Do a complete update on the variable array.// This this includes powering all of the sensors, getting updated// values, and turing them back off.// NOTE: The wake function for each sensor should force sensor setup// to run if the sensor was not previously set up.varArray.completeUpdate();dataLogger.watchDogTimer.resetWatchDog();// Reset modbus serial pins to LOW, if your RS485 adapter bleeds power// on sleep, because Modbus Stop bit leaves these pins HIGH.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833digitalWrite(5, LOW); // Reset AltSoftSerial Tx pin to LOWdigitalWrite(6, LOW); // Reset AltSoftSerial Rx pin to LOW// Create a csv data record and save it to the log filedataLogger.logToSD();dataLogger.watchDogTimer.resetWatchDog();// Connect to the network// Again, we're only doing this if the battery is doing wellif (getBatteryVoltage() > 3.55) {// Serial.println(F("Trying to connect to internet-------"));dataLogger.watchDogTimer.resetWatchDog();if (modem.connectInternet()) {dataLogger.watchDogTimer.resetWatchDog();// Publish data to remotesSerial.println(F("Modem connected to internet."));dataLogger.publishDataToRemotes();// Sync the clock at midnightdataLogger.watchDogTimer.resetWatchDog();if (Logger::markedEpochTime != 0 &&Logger::markedEpochTime % 86400 == 0) {Serial.println(F("Running a daily clock sync..."));dataLogger.setRTClock(modem.getNISTTime());dataLogger.watchDogTimer.resetWatchDog();modem.updateModemMetadata();dataLogger.watchDogTimer.resetWatchDog();}// Disconnect from the networkmodem.disconnectInternet();dataLogger.watchDogTimer.resetWatchDog();}// Turn the modem offmodem.modemSleepPowerDown();dataLogger.watchDogTimer.resetWatchDog();}// Cut power from the SD card - without additional housekeeping waitdataLogger.turnOffSDcard(false);dataLogger.watchDogTimer.resetWatchDog();// Turn off the LEDdataLogger.alertOff();// Print a line to show reading endedSerial.println(F("------------------------------------------\n"));// Unset flagLogger::isLoggingNow = false;}// Check if it was instead the testing interrupt that woke us upif (Logger::startTesting) {// Start the stream for the modbus sensors, if your RS485 adapter bleeds// current from data pins when powered off & you stop modbus serial// connection with digitalWrite(5, LOW), below.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833altSoftSerial.begin(9600);dataLogger.testingMode();}// Reset modbus serial pins to LOW, if your RS485 adapter bleeds power// on sleep, because Modbus Stop bit leaves these pins HIGH.// https://github.com/EnviroDIY/ModularSensors/issues/140#issuecomment-389380833digitalWrite(5, LOW); // Reset AltSoftSerial Tx pin to LOWdigitalWrite(6, LOW); // Reset AltSoftSerial Rx pin to LOW// Call the processor sleepdataLogger.systemSleep();}2021-12-23 at 3:57 PM in reply to: Interference between HYDROS CTD and Yosemitech Turbidity Sensor #16207Thank you Anthony. It sounds like this may be the problem. It seems strange that I have 9 of 10 sites operating perfectly, but this site refuses to play nice. I will try your solution when I get some time over the Christmas break.
Have a great Christmas and New Year.
James
-
AuthorPosts