From 564df3d0272e3a97dac9bdb9940d1705241dba97 Mon Sep 17 00:00:00 2001 From: James Hughes Date: Mon, 11 Apr 2022 02:57:18 -0600 Subject: [PATCH] Develop is now v 1.3 (#11) * testing esp_wifi header file to allow for lower curent when deep sleep happens * some refactoring and esp_wifi_stop added * refactor and clean up readBattery. Remove commented WiFi.h #include from weather.ino * rainfall data now full 24h and minor cleanup of unused code * updated comments and release to reflect v1.3 work * 24h rainfall tracking WIP * 60min rainfall tracking WIP * 60min rainfall tracking WIP * 60min rainfall tracking WIP * ESPcoreF and ESPcoreC added for MQTT publish topics * 60 min rainfall WIP * alternate PCB support, low battery flag correction, railfall 60 min WIP * load switch support and capability to drive IO12 while in deep sleep * remove deep sleep header file * #include<> tweaks for clearer identification of system headers. Increased battery_low multiplier from 4 to 10 * added uv.begin to properly initialize sensor * rainfallData struct rename and mqtt topic added for rainfall interval accumulation * rssi topic added * v 1.3 pre-merge/pre-release. Sensor error management better handled (making use of return results from .begin functions * MQTT checks now point to app variable, not #define * correct compile error * %l to %li for format specifier on RSSI topic * #define MQTT removed * minor cleanup of debug statements --- eeprom.ino | 16 ++--- mqtt.ino | 34 ++++++++++- rainfall.ino | 97 ++++++++++++++++++++++++++++- sec.h | 13 ++-- sensors.ino | 92 +++++++++++++++++++++------- time.ino | 11 ++-- weather.ino | 169 +++++++++++++++++++++++++++++++++++++++------------ wifi.ino | 17 +++--- wind.ino | 2 - 9 files changed, 358 insertions(+), 93 deletions(-) diff --git a/eeprom.ino b/eeprom.ino index be8c82e..0494c27 100644 --- a/eeprom.ino +++ b/eeprom.ino @@ -4,7 +4,7 @@ //======================================================================== // readEEPROM: Read historicalData from NVM //======================================================================== -void readEEPROM(struct historicalData *rainfall) +void readEEPROM(struct rainfallData *rainfall) { int structSize; byte buffer[200]; @@ -12,7 +12,7 @@ void readEEPROM(struct historicalData *rainfall) bool nonZero = false; int address = 0x0000; - structSize = sizeof(historicalData); + structSize = sizeof(rainfallData); memset(buffer, 0, sizeof(structSize)); //Send dummy write to set addpress register of NVM @@ -51,7 +51,7 @@ void readEEPROM(struct historicalData *rainfall) // boot must be >1 in order for a write to take place, array will never // be written on boot = 1 //======================================================================== -void writeEEPROM(struct historicalData *rainfall) +void writeEEPROM(struct rainfallData *rainfall) { byte buffer[200]; int structSize; @@ -61,7 +61,7 @@ void writeEEPROM(struct historicalData *rainfall) int page = 0; - structSize = sizeof(historicalData); + structSize = sizeof(rainfallData); memcpy(buffer, rainfall, structSize); for (page = 0; (page * pageSize) < structSize; page++) { @@ -91,7 +91,7 @@ void initEEPROM(void) { int structSize; int x; - structSize = sizeof(historicalData); + structSize = sizeof(rainfallData); MonPrintf("sizeof int: %i\n", sizeof(int)); for (x = 0; x < structSize; x++) { @@ -107,14 +107,14 @@ void initEEPROM(void) //======================================================================== // conditionalWriteEEPROM: Only write EEPROM if something has changed //======================================================================== -void conditionalWriteEEPROM(struct historicalData *rainfall) +void conditionalWriteEEPROM(struct rainfallData *rainfall) { - struct historicalData historyBuffer; + struct rainfallData historyBuffer; bool match = true; int structSize; int x; - structSize = sizeof(historicalData); + structSize = sizeof(rainfallData); readEEPROM(&historyBuffer); diff --git a/mqtt.ino b/mqtt.ino index 2975399..8f3f3fc 100644 --- a/mqtt.ino +++ b/mqtt.ino @@ -36,16 +36,19 @@ void SendDataMQTT (struct sensorData *environment) } } MQTTPublishInt("boot/", (int)bootCount, true); + MQTTPublishLong("rssi/", rssi, true); MQTTPublishInt("temperatureF/", (int)environment->temperatureF, true); MQTTPublishInt("temperatureC/", (int)environment->temperatureC, true); - MQTTPublishInt("windSpeed/", (int)environment->windSpeed, true); + MQTTPublishFloat("windSpeed/", environment->windSpeed, true); MQTTPublishInt("windDirection/", (int)environment->windDirection, true); MQTTPublishString("windCardinalDirection/", environment->windCardinalDirection, true); MQTTPublishInt("photoresistor/", (int)environment->photoresistor, true); #ifndef METRIC + MQTTPublishFloat("rainfallInterval/", rainfall.intervalRainfall * 0.011, true); MQTTPublishFloat("rainfall/", rainfall.hourlyRainfall[hourPtr] * 0.011, true); MQTTPublishFloat("rainfall24/", last24() * 0.011, true); #else + MQTTPublishFloat("rainfallInterval/", rainfall.intervalRainfall * 0.011 * 25.4, true); MQTTPublishFloat("rainfall/", rainfall.hourlyRainfall[hourPtr] * 0.011 * 25.4, true); MQTTPublishFloat("rainfall24/", last24() * 0.011 * 25.4, true); #endif @@ -57,6 +60,9 @@ void SendDataMQTT (struct sensorData *environment) MQTTPublishFloat("pressure/", environment->barometricPressure, true); MQTTPublishFloat("caseTemperature/", environment->BMEtemperature, true); MQTTPublishInt("batteryADC/", (int)environment->batteryADC, true); + MQTTPublishInt("ESPcoreF/", (int)environment->coreF, true); + MQTTPublishInt("ESPcoreC/", (int)environment->coreC, true); + MQTTPublishInt("timeEnabled/", (int)elapsedTime, true); MQTTPublishBool("lowBattery/", lowBattery, true); MonPrintf("Issuing mqtt disconnect\n"); client.disconnect(); @@ -113,6 +119,32 @@ void MQTTPublishInt(const char topic[], int value, bool retain) } } + +//======================================================================= +// MQTTPublishLong: routine to publish int values as strings +//======================================================================= +void MQTTPublishLong(const char topic[], long value, bool retain) +{ + char topicBuffer[256]; + char payload[256]; + int retryCount = 0; + int status = 0; + + strcpy(topicBuffer, mainTopic); + strcat(topicBuffer, topic); + if (!client.connected()) reconnect(); + client.loop(); + sprintf(payload, "%li", value); + MonPrintf("%s: %s\n", topicBuffer, payload); + while (!status && retryCount < 5) + { + status = client.publish(topicBuffer, payload, retain); + MonPrintf("MQTT status: %i\n", status); + delay(50); + retryCount++; + } +} + //======================================================================= // MQTTPublishFloat: routine to publish float values as strings //======================================================================= diff --git a/rainfall.ino b/rainfall.ino index 515c3f9..ee592b4 100644 --- a/rainfall.ino +++ b/rainfall.ino @@ -11,12 +11,30 @@ void clearRainfall(void) memset(&rainfall, 0x00, sizeof(rainfall)); } + + +//======================================================================= +// +// Hourly accumulation routines +// +//======================================================================= + + //======================================================================= // clearRainfallHour: zero out specific hour element of rainfall structure array //======================================================================= void clearRainfallHour(int hourPtr) { + //Clear carryover if hourPtr is not matching prior hourPtr value (we have a new hour) + if (rainfall.priorHour != hourPtr) + { + rainfall.hourlyCarryover = 0; + } + //move contents of oldest hour to the carryover location and set hour to zero + rainfall.hourlyCarryover += rainfall.hourlyRainfall[hourPtr % 24]; rainfall.hourlyRainfall[hourPtr % 24] = 0; + + rainfall.priorHour = hourPtr; } //======================================================================= @@ -41,7 +59,7 @@ void printHourlyArray (void) } //======================================================================= -// last24: return tip counter for last 24h (technically 23h) +// last24: return tip counter for last 24h //======================================================================= int last24(void) { @@ -51,10 +69,85 @@ int last24(void) { totalRainfall += rainfall.hourlyRainfall[hour]; } - MonPrintf("Total rainfall: %i\n", totalRainfall); + //add carryover value + totalRainfall += rainfall.hourlyCarryover; + + MonPrintf("Total rainfall (last 24 hours): %i\n", totalRainfall); return totalRainfall; } + +//======================================================================= +// +// Minute accumulation routines +// +//======================================================================= +// NOTE: When speaking of minutes and minute array, we use 5 min as +// minimum grouping for minute-by-minute rainfall + + + +//======================================================================= +// clearRainfallMinute: zero out specific minute element of rainfall structure array +//======================================================================= +void clearRainfallMinute(int minutePtr) +{ + int minuteIndex; + minuteIndex = (int)minutePtr / 12 + 1; + //Clear carryover if hourPtr is not matching prior hourPtr value (we have a new hour) + if (rainfall.priorHour != minutePtr) + { + rainfall.hourlyCarryover = 0; + } + //move contents of oldest hour to the carryover location and set hour to zero + rainfall.hourlyCarryover += rainfall.hourlyRainfall[minutePtr % 24]; + rainfall.hourlyRainfall[minutePtr % 24] = 0; + + //rainfall.priorHour = hourPtr; +} + +//======================================================================= +// addTipsToMinute: increment current hour tip count +//======================================================================= +void addTipsToMinute(int count) +{ + int minute = timeinfo.tm_hour; + rainfall.current60MinRainfall[minute] = rainfall.current60MinRainfall[minute] + count; +} + +//======================================================================= +// printMinuteArray: diagnostic routine to print minute rainfall array to terminal +//======================================================================= +void printMinuteArray (void) +{ + int minute = 0; + for (minute = 0; minute < 12; minute++) + { + MonPrintf("Minute %i: %u\n", minute * 5, rainfall.current60MinRainfall[minute]); + } +} + +//======================================================================= +// last60min: return tip counter for last 60 minutes +//======================================================================= +int last60min(void) +{ + int minute; + int totalRainfall = 0; + for (minute = 0; minute < 12; minute++) + { + totalRainfall += rainfall.current60MinRainfall[minute]; + } + //add carryover value + totalRainfall += rainfall.minuteCarryover; + + MonPrintf("Total rainfall (last 60 minutes): %i\n", totalRainfall); + return totalRainfall; +} + + + + //======================================================================= // rainTick: ISR for rain tip gauge count //======================================================================= diff --git a/sec.h b/sec.h index 374bcc5..3fb9e0f 100644 --- a/sec.h +++ b/sec.h @@ -69,14 +69,17 @@ const int UpdateIntervalSeconds = 5 * 60; //Sleep timer (60s) testing //=========================================== //Battery calibration //=========================================== -//measured battery voltage/ADC reading -#define batteryCalFactor .001167 - +//batteryCalFactor = measured battery voltage/ADC reading +#define batteryCalFactor .0011804 +//=========================================== +//Timezone information +//=========================================== +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = -7 * 3600; +const int daylightOffset_sec = 3600; //========================= Enable Blynk, MQTT or Thingspeak =================================== - -// configuration control constant for use of either Blynk or Thingspeak //const String App = "BLYNK"; // alternative is line below //const String App = "Thingspeak"; // alternative is line above const String App = "MQTT"; // alternative is line below diff --git a/sensors.ino b/sensors.ino index b00c650..79c46be 100644 --- a/sensors.ino +++ b/sensors.ino @@ -1,6 +1,11 @@ OneWire oneWire(TEMP_PIN); DallasTemperature temperatureSensor(&oneWire); +extern "C" +{ + uint8_t temprature_sens_read(); +} + //======================================================= // readSensors: Read all sensors and battery voltage //======================================================= @@ -15,6 +20,7 @@ void readSensors(struct sensorData *environment) readBME(environment); readUV(environment); readBattery(environment); + readESPCoreTemp(environment); } //======================================================= @@ -24,7 +30,6 @@ void readTemperature (struct sensorData *environment) { MonPrintf("Requesting temperatures...\n"); temperatureSensor.requestTemperatures(); - MonPrintf("DONE"); environment->temperatureC = temperatureSensor.getTempCByIndex(0); // Check if reading was successful @@ -46,14 +51,9 @@ void readTemperature (struct sensorData *environment) //======================================================= void readBattery (struct sensorData *environment) { - int val; - float Vout; - val = analogRead(VOLT_PIN); - //this value may need tweaking for your voltage divider - //cabibration = 4.2V/analog value read @ 4.2V - environment->batteryADC = val; - environment->batteryVoltage = val * batteryCalFactor; - MonPrintf("Battery digital :%i voltage: %6.2f\n", val, environment->batteryVoltage); + environment->batteryADC = analogRead(VOLT_PIN); + environment->batteryVoltage = environment->batteryADC * batteryCalFactor; + MonPrintf("Battery digital ADC :%i voltage: %6.2f\n", environment->batteryADC, environment->batteryVoltage); //check for low battery situation if (environment->batteryVoltage < 3.78) { @@ -65,13 +65,40 @@ void readBattery (struct sensorData *environment) } } +//======================================================= +// checkBatteryVoltage: set/reset low voltage flag only +//======================================================= +void checkBatteryVoltage (void) +{ + int adc; + float voltage; + adc = analogRead(VOLT_PIN); + voltage = adc * batteryCalFactor; + //MonPrintf("Battery digital ADC :%i voltage: %6.2f\n", environment->batteryADC, environment->batteryVoltage); + //check for low battery situation + if (voltage < 3.78) + { + lowBattery = true; + } + else + { + lowBattery = false; + } +} //======================================================= // readLux: LUX sensor read //======================================================= void readLux(struct sensorData *environment) { #ifdef BH1750Enable - environment->lux = lightMeter.readLightLevel(); + if (status.lightMeter) + { + environment->lux = lightMeter.readLightLevel(); + } + else + { + environment->lux = -1; + } #else environment->lux = -3; #endif @@ -79,7 +106,7 @@ void readLux(struct sensorData *environment) } //======================================================= -// readPR: LUX sensor read +// readPR: photoresistor ADC read //======================================================= void readPR(struct sensorData *environment) { @@ -95,12 +122,24 @@ void readPR(struct sensorData *environment) //======================================================= void readBME(struct sensorData *environment) { + if (status.bme) + { #ifndef METRIC - bme.read(environment->barometricPressure, environment->BMEtemperature, environment->humidity, BME280::TempUnit_Fahrenheit, BME280::PresUnit_inHg); + bme.read(environment->barometricPressure, environment->BMEtemperature, environment->humidity, BME280::TempUnit_Fahrenheit, BME280::PresUnit_inHg); #else - bme.read(environment->barometricPressure, environment->BMEtemperature, environment->humidity, BME280::TempUnit_Celsius, BME280::PresUnit_Pa); + bme.read(environment->barometricPressure, environment->BMEtemperature, environment->humidity, BME280::TempUnit_Celsius, BME280::PresUnit_Pa); #endif + + } + else + { + //set to insane values + environment->barometricPressure = -100; + environment->BMEtemperature = -100; + environment->humidity = -100; + } MonPrintf("BME barometric pressure: %6.2f BME temperature: %6.2f BME humidity: %6.2f\n", environment->barometricPressure, environment->BMEtemperature, environment->humidity); + } //======================================================= @@ -108,14 +147,25 @@ void readBME(struct sensorData *environment) //======================================================= void readUV(struct sensorData *environment) { - if (! uv.begin()) { - Serial.println("Didn't find Si1145"); - environment->UVIndex = -1; - } - else{ + if (status.uv) + { environment->UVIndex = uv.readUV() / 100; - MonPrintf("UV Index: %f\n", environment->UVIndex); - MonPrintf("Vis: %i\n", uv.readVisible()); - MonPrintf("IR: %i\n", uv.readIR()); } + else + { + environment->UVIndex = -1; + } + MonPrintf("UV Index: %f\n", environment->UVIndex); + MonPrintf("Vis: %i\n", uv.readVisible()); + MonPrintf("IR: %i\n", uv.readIR()); } + +void readESPCoreTemp(struct sensorData *environment) +{ + unsigned int coreF, coreC; + coreF = temprature_sens_read(); + coreC = (coreF - 32) * 5 / 9; + + environment->coreF = coreF; + environment->coreC = coreC; +} \ No newline at end of file diff --git a/time.ino b/time.ino index 27018d0..c845742 100644 --- a/time.ino +++ b/time.ino @@ -1,7 +1,3 @@ - -const char* ntpServer = "pool.ntp.org"; -const long gmtOffset_sec = -7 * 3600; -const int daylightOffset_sec = 3600; struct tm timeinfo; //======================================================================= @@ -10,7 +6,7 @@ struct tm timeinfo; void printLocalTime() { if (!getLocalTime(&timeinfo)) { - MonPrintf("Failed to obtain time"); + MonPrintf("Failed to obtain time\n"); return; } Serial.printf("Date:%02i %02i %i Time: %02i:%02i:%02i\n", timeinfo.tm_mday, timeinfo.tm_mon + 1, timeinfo.tm_year + 1900, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec); @@ -30,10 +26,13 @@ void printTimeNextWake( void) //======================================================================= void updateWake (void) { + MonPrintf("Checking for low battery\n"); + checkBatteryVoltage(); int muliplierBatterySave = 1; if (lowBattery) { - muliplierBatterySave = 4; + MonPrintf("Flag set for low battery\n"); + muliplierBatterySave = 10; } getLocalTime(&timeinfo); //180 added to wipe out any RTC timing error vs NTP server - causing 2 WAKES back to back diff --git a/weather.ino b/weather.ino index 643103b..3281eae 100644 --- a/weather.ino +++ b/weather.ino @@ -4,38 +4,72 @@ // //Supporting the following project: https://www.instructables.com/Solar-Powered-WiFi-Weather-Station-V30/ -#define VERSION "1.2.2" +//version 1.3 RC1 +#define VERSION 1.3 -// 1.2.1 1-1-2022 hotfix to remove esp_deep_sleep.h (legacy header from ESP8266 project). Many users do not have the file if they've never compiled an 8266 project -// 1.2.2 4-4-2022 pull request from https://github.com/tkoeberl -// 1. Makes MQTT an official choice, not an afterthought -// 2. uv.begin was missing, now present -// 3. I changed sec.h to reflect new MQTT choice +//============================================= +// Changelog +//============================================= +/* v1.3 supports 24h rainfall data, not 23h + supports current 60 min rainfall, not + current "hour" that looses data at top + of the hour. + + lowBattery flag fix and multiplies wake time by 10 + when battery is < 15 % remaining + + Alternate pinout for Thomas Krebs PCB + design that does not use devkit ESP32 + + remove esp_deep_sleep.h as it is not needed + + modified the #include to clearly discern system includes + + uv.begin added to sensorEnable() + + renamed historicalData to rainfallData and added rainfallInterval as an additional mqtt topic for non historical accumulation + + addred rssi topic on mqtt publish listing + + clearer reporting to console on sensor.begin statuses. Program should run with no sensors now and not hang + + + + + + + + +*/ //=========================================== // Includes //=========================================== #include "secrets.h" -#include +#include #include #include #include #include -#include "Wire.h" +#include #ifdef BH1750Enable #include #endif #include -#include "Adafruit_SI1145.h" +#include #include #include -#include "soc/soc.h" -#include "soc/rtc_cntl_reg.h" +#include +#include #include +#include +#include //=========================================== // Defines //=========================================== +//If you are using a Thomas Krebs designed PCB that does not use a standard devkit, place a #define KREBS_PCB in your secrets.h +#ifndef KREBS_PCB #define WIND_SPD_PIN 14 //reed switch based anemometer count #define RAIN_PIN 25 //reed switch based tick counter on tip bucket #define WIND_DIR_PIN 35 //variable voltage divider output based on varying R network with reed switches @@ -44,7 +78,18 @@ #define TEMP_PIN 4 // DS18B20 hooked up to GPIO pin 4 #define LED_BUILTIN 2 //Diagnostics using built-in LED, may be set to 12 for newer boards that do not use devkit sockets #define SEC 1E6 //Multiplier for uS based math -#define WDT_TIMEOUT 60 +#define WDT_TIMEOUT 60 //watchdog timer + +#else +#define WIND_SPD_PIN 26 //reed switch based anemometer count +#define RAIN_PIN 25 //reed switch based tick counter on tip bucket +#define WIND_DIR_PIN 35 //variable voltage divider output based on varying R network with reed switches +#define PR_PIN 34 //photoresistor pin +#define VOLT_PIN 33 //voltage divider for battery monitor +#define TEMP_PIN 15 // DS18B20 hooked up to GPIO pin 15 +#define LED_PIN 14 //Diagnostics using built-in LED +//#define MODE_PIN 12 //Load Switch +#endif //=========================================== // Externs @@ -73,13 +118,28 @@ struct sensorData int photoresistor; float batteryVoltage; int batteryADC; + unsigned int coreF; + unsigned int coreC; }; //rainfall is stored here for historical data uses RTC -struct historicalData +struct rainfallData { + unsigned int intervalRainfall; unsigned int hourlyRainfall[24]; unsigned int current60MinRainfall[12]; + unsigned int hourlyCarryover; + unsigned int priorHour; + unsigned int minuteCarryover; + unsigned int priorMinute; +}; + +struct sensorStatus +{ + int uv; + int bme; + int lightMeter; + int temperature; }; @@ -89,8 +149,9 @@ struct historicalData RTC_DATA_ATTR volatile int rainTicks = 0; RTC_DATA_ATTR int lastHour = 0; RTC_DATA_ATTR time_t nextUpdate; -RTC_DATA_ATTR struct historicalData rainfall; +RTC_DATA_ATTR struct rainfallData rainfall; RTC_DATA_ATTR int bootCount = 0; +RTC_DATA_ATTR unsigned int elapsedTime = 0; //=========================================== // Global instantiation @@ -102,6 +163,8 @@ BME280I2C bme; Adafruit_SI1145 uv = Adafruit_SI1145(); bool lowBattery = false; bool WiFiEnable = false; +struct sensorStatus status; +long rssi = 0; //=========================================== // ISR Prototypes @@ -116,6 +179,11 @@ void setup() { long UpdateIntervalModified = 0; + setCpuFrequencyMhz (80); + rtc_gpio_init(GPIO_NUM_12); + rtc_gpio_set_direction(GPIO_NUM_12, RTC_GPIO_MODE_OUTPUT_ONLY); + rtc_gpio_set_level(GPIO_NUM_12, 1); + esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts esp_task_wdt_add(NULL); //add current thread to WDT watch @@ -124,7 +192,6 @@ void setup() pinMode(RAIN_PIN, INPUT); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); - Serial.begin(115200); delay(25); @@ -134,25 +201,24 @@ void setup() BlinkLED(1); bootCount++; - //Initialize i2c and 1w sensors - Wire.begin(); - bme.begin(); -#ifdef BH1750Enable - lightMeter.begin(); -#endif - temperatureSensor.begin(); - - updateWake(); wakeup_reason(); if (WiFiEnable) { - MonPrintf("Connecting to WiFi\n"); + rssi = wifi_connect(); + sensorEnable(); + sensorStatusToConsole(); + //Calibrate Clock - My ESP RTC is noticibly fast + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + printTimeNextWake(); processSensorUpdates(); + WiFi.disconnect(); + esp_wifi_stop(); } UpdateIntervalModified = nextUpdate - mktime(&timeinfo); - if (UpdateIntervalModified <= 0) + if (UpdateIntervalModified < 3) { UpdateIntervalModified = 3; } @@ -179,32 +245,30 @@ void processSensorUpdates(void) #ifdef USE_EEPROM readEEPROM(&rainfall); #endif - wifi_connect(); - //Calibrate Clock - My ESP RTC is noticibly fast - configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); - printLocalTime(); - printTimeNextWake(); - //Get Sensor data readSensors(&environment); + //move rainTicks into interval container + rainfall.intervalRainfall = rainTicks; + //move rainTicks into hourly containers MonPrintf("Current Hour: %i\n\n", timeinfo.tm_hour); - addTipsToHour(rainTicks); - clearRainfallHour(timeinfo.tm_hour + 1); - rainTicks = 0; - //Start sensor housekeeping addTipsToHour(rainTicks); clearRainfallHour(timeinfo.tm_hour + 1); rainTicks = 0; + //Conditional write of rainfall data to EEPROM #ifdef USE_EEPROM conditionalWriteEEPROM(&rainfall); #endif //send sensor data to IOT destination sendData(&environment); - WiFi.disconnect(); + //send sensor data to MQTT + if (App == "MQTT") + { + SendDataMQTT(&environment); + } } //=========================================================== @@ -243,6 +307,7 @@ void wakeup_reason() default : MonPrintf("Wakeup was not caused by deep sleep: %d\n", wakeup_reason); WiFiEnable = true; + //I manually call this line to zero out EEPROM array once and only once, then remove this line //jh initEEPROM(); //my debug only break; } @@ -256,9 +321,11 @@ void sleepyTime(long UpdateIntervalModified) { Serial.println("\n\n\nGoing to sleep now..."); Serial.printf("Waking in %i seconds\n\n\n\n\n\n\n\n\n\n", UpdateIntervalModified); - //updateWake(); + + rtc_gpio_set_level(GPIO_NUM_12, 0); esp_sleep_enable_timer_wakeup(UpdateIntervalModified * SEC); esp_sleep_enable_ext0_wakeup(GPIO_NUM_25, 0); + elapsedTime = (int)millis() / 1000; esp_deep_sleep_start(); } @@ -297,3 +364,29 @@ void BlinkLED(int count) delay(500); } } + +//=========================================== +// sensorEnable: Initialize i2c and 1w sensors +//=========================================== +void sensorEnable(void) +{ + status.temperature = Wire.begin(); + status.bme = bme.begin(); + status.uv = uv.begin(); +#ifdef BH1750Enable + status.lightMeter = lightMeter.begin(); +#endif + temperatureSensor.begin(); //returns void - cannot directly check +} + +//=========================================== +// sensorStatusToConsole: Output .begin return values +//=========================================== +void sensorStatusToConsole(void) +{ + MonPrintf("----- Sensor Statuses -----\n"); + MonPrintf("BME status: %i\n", status.bme); + MonPrintf("UV status: %i\n", status.uv); + MonPrintf("lightMeter status: %i\n", status.lightMeter); + MonPrintf("temperature status: %i\n\n", status.temperature); +} diff --git a/wifi.ino b/wifi.ino index 4585a37..53c53aa 100644 --- a/wifi.ino +++ b/wifi.ino @@ -1,29 +1,26 @@ //======================================================================= // wifi_connect: connect to WiFi or explicitly connect to Blynk, if used //======================================================================= -void wifi_connect() +long wifi_connect() { + long wifi_signal = 0; - //delay(5000); + MonPrintf("Connecting to %s\n", App); if (App == "BLYNK") // for posting datas to Blynk App { - MonPrintf("Connecting to %s\n", App); + Blynk.begin(auth, ssid, pass); } - else if (App == "Thingspeak") // for posting datas to Thingspeak website + else if ((App == "Thingspeak") || (App == "MQTT")) // for posting datas to Thingspeak website { MonPrintf("Connecting to WiFi\n"); WiFi.begin(ssid, pass); - //WiFi.persistent(false); - //WiFi.setAutoConnect(false); - //WiFi.setAutoReconnect(true); - //WiFi.setTxPower(WIFI_POWER_2dBm); - while (WiFi.status() != WL_CONNECTED) { delay(500); } MonPrintf("WiFi connected\n"); + wifi_signal = WiFi.RSSI(); } else if (App == "MQTT") // for posting datas to Thingspeak website { @@ -38,7 +35,7 @@ void wifi_connect() } else { - //WiFi.begin(ssid, pass); MonPrintf(" is not a valid application"); } + return wifi_signal; } diff --git a/wind.ino b/wind.ino index 6a51acb..2a40496 100644 --- a/wind.ino +++ b/wind.ino @@ -13,7 +13,6 @@ void readWindSpeed(struct sensorData *environment ) { float windSpeed = 0; int position; - //int msBetweenSamples = 0; long msTotal = 0; int samples = 0; @@ -24,7 +23,6 @@ void readWindSpeed(struct sensorData *environment ) { for (position = 1; position < 7; position++) { - //msBetweenSamples = tickTime[position + 1] - tickTime[position]; if (tickTime[position]) { msTotal += tickTime[position];