Home › Forums › Mayfly Data Logger › RS485 without auto direction control › Reply To: RS485 without auto direction control
2019-12-18 at 4:43 AM
#13483
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
/***************************************************************************** logging_to_thingSpeak.ino Written By: Sara Damiano (sdamiano@stroudcenter.org) Development Environment: PlatformIO Hardware Platform: EnviroDIY Mayfly Arduino Datalogger Software License: BSD-3. Copyright (c) 2017, Stroud Water Research Center (SWRC) and the EnviroDIY Development Team This example sketch is written for ModularSensors library version 0.23.16 This sketch is an example of logging data to an SD card and sending the data to ThingSpeak. DISCLAIMER: 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 // ========================================================================== // Data Logger Settings // ========================================================================== // The library version this example was written for const char *libraryVersion = "0.23.16"; // The name of this file const char *sketchName = "Thingspeak"; // Logger ID, also becomes the prefix for the name of the data file on SD card const char *LoggerID = "00002"; // How frequently (in minutes) to log data const uint8_t loggingInterval = 1; // Your logger's timezone. const int8_t timeZone = 1; // CET // 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 debugging //int BEE_CTS_PIN = 19; // Bee CTS Pin (Clear to Send) const 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 1 const 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!) 12 for Mayfly const int8_t sensorPowerPin = 22; // MCU pin controlling main sensor power (-1 if not applicable) // Create the main processor chip "sensor" - for general metadata const char *mcuBoardVersion = "v0.4"; ProcessorStats mcuBoard(mcuBoardVersion); // ========================================================================== // Settings for Additional Serial Ports // ========================================================================== /// The modem and a number of sensors communicate over UART/TTL - often called "serial". // "Hardware" serial ports (automatically controlled by the MCU) are generally // the most accurate and should be configured and used for as many peripherals // as possible. In some cases (ie, modbus communication) many sensors can share // the same serial port. #if not defined ARDUINO_ARCH_SAMD && not defined ATMEGA2560 // For AVR boards // Unfortunately, most AVR boards have only one or two hardware serial ports, // so we'll set up three types of extra software serial ports to use // AltSoftSerial by Paul Stoffregen (https://github.com/PaulStoffregen/AltSoftSerial) // is the most accurate software serial port for AVR boards. // AltSoftSerial can only be used on one set of pins on each board so only one // AltSoftSerial port can be used. // Not all AVR boards are supported by AltSoftSerial. #include <AltSoftSerial.h> AltSoftSerial altSoftSerial; // NeoSWSerial (https://github.com/SRGDamia1/NeoSWSerial) is the best software // serial that can be used on any pin supporting interrupts. // You can use as many instances of NeoSWSerial as you want. // Not all AVR boards are supported by NeoSWSerial. #include <NeoSWSerial.h> // for the stream communication const int8_t neoSSerial1Rx = 11; // data in pin const int8_t neoSSerial1Tx = -1; // data out pin NeoSWSerial neoSSerial1(neoSSerial1Rx, neoSSerial1Tx); // To use NeoSWSerial in this library, we define a function to receive data // This is just a short-cut for later void neoSSerial1ISR() { NeoSWSerial::rxISR(*portInputRegister(digitalPinToPort(neoSSerial1Rx))); } const int8_t softSerialRx = A3; // data in pin const int8_t softSerialTx = A4; // data out pin #include <SoftwareSerial_ExtInts.h> // for the stream communication SoftwareSerial_ExtInts softSerial1(softSerialRx, softSerialTx); #endif // End software serial for avr boards // ========================================================================== // Wifi/Cellular Modem Settings // ========================================================================== // Create a reference to the serial port for the modem HardwareSerial &modemSerial = Serial1; // Use hardware serial if possible // Modem Pins - Describe the physical pin connection of your modem to your board const int8_t modemVccPin = 23; // MCU pin controlling modem power (-1 if not applicable) const 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 = -1; // 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 const char *apn = "xxxxx"; // The APN for the gprs connection #include <modems/Sodaq2GBeeR6.h> const long modemBaud = 9600; // SIM800 does auto-bauding by default Sodaq2GBeeR6 modem2GB(&modemSerial, modemVccPin, modemStatusPin, apn); // Create an extra reference to the modem by a generic name (not necessary) Sodaq2GBeeR6 modem = modem2GB; //const char *BEE_TYPE = "GPRS"; // The type of XBee, either "GPRS" or "WIFI" //const char* APN = "online.telia.se"; // The APN for the GPRSBee // ========================================================================== // Maxim DS3231 RTC (Real Time Clock) // ========================================================================== #include <sensors/MaximDS3231.h> // Create a DS3231 sensor object MaximDS3231 ds3231(1); // ========================================================================== // Yosemitech Y504 Dissolved Oxygen Sensor // ========================================================================== #include <sensors/YosemitechY504.h> // 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 ATMEGA2560 HardwareSerial &modbusSerial = Serial2; // Use hardware serial if possible #else AltSoftSerial &modbusSerial = altSoftSerial; // For software serial if needed //NeoSWSerial &modbusSerial = neoSSerial1; // For software serial if needed //SoftwareSerial_ExtInts &modbusSerial =softSerial1; // For software serial if needed #endif byte y504ModbusAddress1 = 0x01; // The modbus address of the Y504 byte y504ModbusAddress2 = 0x05; // The modbus address of the Y504 TODO->Set adress const int8_t rs485AdapterPower = sensorPowerPin; // Pin to switch RS485 adapter power on and off (-1 if unconnected) const int8_t modbusSensorPower = -1; // Pin to switch sensor power on and off (-1 if unconnected) const int8_t max485EnablePin = 4; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y504NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption // Create a Yosemitech Y504 dissolved oxygen sensor object YosemitechY504 y504_1(y504ModbusAddress1, modbusSerial, modbusSensorPower, max485EnablePin, y504NumberReadings); YosemitechY504 y504_2(y504ModbusAddress2, modbusSerial, modbusSensorPower, max485EnablePin, y504NumberReadings); // Create the dissolved oxygen percent, dissolved oxygen concentration, and // temperature variable pointers for the Y504 //Variable *y504DOpct = new YosemitechY504_DOpct(&y504, "12345678-abcd-1234-ef00-1234567890ab"); //Variable *y504DOmgL = new YosemitechY504_DOmgL(&y504, "12345678-abcd-1234-ef00-1234567890ab"); //Variable *y504Temp = new YosemitechY504_Temp(&y504, "12345678-abcd-1234-ef00-1234567890ab"); // ========================================================================== // Creating the Variable Array[s] and Filling with Variable Objects // ========================================================================== Variable *variableList[] = { new YosemitechY504_DOpct(&y504_1, "4d202b9c-1b23-11ea-978f-2e728ce88125"), new YosemitechY504_Temp(&y504_1, "4d202cdc-1b23-11ea-978f-2e728ce88125"), new YosemitechY504_DOmgL(&y504_1, "4d202e1c-1b23-11ea-978f-2e728ce88125"), new YosemitechY504_DOpct(&y504_2, "4d202f5c-1b23-11ea-978f-2e728ce88125"), new YosemitechY504_Temp(&y504_2, "4d203290-1b23-11ea-978f-2e728ce88125"), new YosemitechY504_DOmgL(&y504_2, "4d203128-1b23-11ea-978f-2e728ce88125"), new Modem_SignalPercent(&modem, "cc731ad3-a201-4160-bc15-4aa80f530fba"), new ProcessorStats_Battery(&mcuBoard, "f4fcc3cb-5a89-4436-984f-6b48612eb7fa"), new MaximDS3231_Temp(&ds3231, "61a93cdb-6c9f-46b3-a3ed-892ccd97a08f"), new Modem_RSSI(&modem, "6486cb74-ed40-4340-805e-f9a8fd1af77e") }; // Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray; // ========================================================================== // The Logger Object[s] // ========================================================================== // Create a logger instance Logger dataLogger; // ========================================================================== // ThingSpeak Data Publisher // ========================================================================== // Create a channel with fields on ThingSpeak in advance // The fields will be sent in exactly the order they are in the variable array. // Any custom name or identifier given to the field on ThingSpeak is irrelevant. // No more than 8 fields of data can go to any one channel. Any fields beyond the // eighth in the array will be ignored. const char *thingSpeakMQTTKey = "XXXXXXXXXXXXXXXX"; // Your MQTT API Key from Account > MyProfile. const char *thingSpeakChannelID = "######"; // The numeric channel id for your channel const char *thingSpeakChannelKey = "XXXXXXXXXXXXXXXX"; // The Write API Key for your channel // Create a data publisher for ThingSpeak #include <publishers/ThingSpeakPublisher.h> ThingSpeakPublisher TsMqtt; // ========================================================================== // Working Functions // ========================================================================== // Flashes the LED's on the primary board void 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]; } // ========================================================================== // Main setup function // ========================================================================== void setup() { // Start the primary serial connection Serial.begin(serialBaud); // Print a start-up note to the first serial port Serial.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); if (String(MODULAR_SENSORS_VERSION) != String(libraryVersion)) Serial.println(F( "WARNING: THIS EXAMPLE WAS WRITTEN FOR A DIFFERENT VERSION OF MODULAR SENSORS!!")); // Start the serial connection with the modem modemSerial.begin(modemBaud); // Start the stream for the modbus sensors; all currently supported modbus sensors use 9600 baud modbusSerial.begin(9600); // Set up pins for the LED's pinMode(greenLED, OUTPUT); digitalWrite(greenLED, LOW); pinMode(redLED, OUTPUT); digitalWrite(redLED, LOW); // Blink the LEDs to show the board is on and starting up greenredflash(); // Set the timezones for the logger/data and the RTC // Logging in the given time zone Logger::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 logger dataLogger.attachModem(modem); modem.setModemLED(modemLEDPin); dataLogger.setLoggerPins(wakePin, sdCardSSPin, sdCardPwrPin, buttonPin, greenLED); // Begin the variable array[s], logger[s], and publisher[s] varArray.begin(variableCount, variableList); dataLogger.begin(LoggerID, loggingInterval, &varArray); TsMqtt.begin(dataLogger, &modem.gsmClient, thingSpeakMQTTKey, thingSpeakChannelID, thingSpeakChannelKey); // Note: Please change these battery voltages to match your battery // Check that the battery is OK before powering the modem if (getBatteryVoltage() > 3.55 || !dataLogger.isRTCSane()) { modem.modemPowerUp(); modem.wake(); // Synchronize the RTC with NIST Serial.println(F("Attempting to connect to the internet and synchronize RTC with NIST")); if (modem.connectInternet(120000L)) { dataLogger.setRTClock(modem.getNISTTime()); } else { Serial.println(F("Could not connect to internet for clock sync.")); } } // Set up the sensors, except at lowest battery level if (getBatteryVoltage() > 3.4) { Serial.println(F("Setting up sensors...")); varArray.setupSensors(); } // Power down the modem modem.disconnectInternet(); modem.modemSleepPowerDown(); // 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) { dataLogger.turnOnSDcard(true); // true = wait for card to settle after power up dataLogger.createLogFile(true); // true = write a new header dataLogger.turnOffSDcard(true); // true = wait for internal housekeeping after write } // Call the processor sleep dataLogger.systemSleep(); } // ========================================================================== // Main loop function // ========================================================================== // Use this short loop for simple data logging and sending void loop() { // Note: Please change these battery voltages to match your battery // At very low battery, just go back to sleep if (getBatteryVoltage() < 3.4) { dataLogger.systemSleep(); } // At moderate voltage, log data but don't send it over the modem else if (getBatteryVoltage() < 3.55) { dataLogger.logData(); } // If the battery is good, send the data to the world else { dataLogger.logDataAndPublish(); } } |