From f5068b555f2d4153f1be69bb0d7ef73f97f71f00 Mon Sep 17 00:00:00 2001 From: lexa Date: Tue, 29 Jun 2021 17:52:41 +0300 Subject: [PATCH] ESP Electro MCP, ExtSens smoothing --- ESP_Electro/platformio.ini | 15 ++- ESP_Electro/src/main.cpp | 233 ++++++++++++++++++++----------------- ExtSens/platformio.ini | 1 + ExtSens/src/main.cpp | 68 ++++++----- 4 files changed, 180 insertions(+), 137 deletions(-) diff --git a/ESP_Electro/platformio.ini b/ESP_Electro/platformio.ini index d29f8a8..3947054 100644 --- a/ESP_Electro/platformio.ini +++ b/ESP_Electro/platformio.ini @@ -10,9 +10,14 @@ [env:esp07] platform = espressif8266 -;board = nodemcuv2 -board = esp07 +board = nodemcuv2 +;board = esp07 framework = arduino -board_build.ldscript = eagle.flash.1m.ld -upload_protocol = espota -upload_port = 192.168.1.136 +;board_build.ldscript = eagle.flash.1m.ld +;upload_protocol = espota +;upload_port = 192.168.1.136 +;upload_port = 192.168.1.95 +monitor_speed = 115200 +lib_deps = + sstaub/Ticker @ ^4.3.0 + knolleary/PubSubClient @ ^2.8 diff --git a/ESP_Electro/src/main.cpp b/ESP_Electro/src/main.cpp index fdf54b2..97f9830 100644 --- a/ESP_Electro/src/main.cpp +++ b/ESP_Electro/src/main.cpp @@ -1,179 +1,200 @@ #include #include #include -#include -#include +#include +#include -#define LED_WF (14) -#define LED_MQ (12) -#define LED_WRK (13) +#define LED_WF (2) //Blue +#define LED_WRK (3) //Green +#define LED_MQ (4) //Red + +#define HOST_NAME "ElectroT" +#define MAIN_TOPIC "/home/kort/" + +/* Hardware: + MCP3201 Pin ---------------- ESP8266 Pin +- 1-VREF ---------------- 3,3V +- 2-IN+ ---------------- ANALOG SIGNAL + +- 3-IN- ---------------- ANALOG SIGNAL - +- 4-GND ---------------- GND +- 5-CS ----CS---------- GPIO15 / CS +- 6-Dout(MISO)----MISO-------- GPIO12 / MISO +- 7-CLK ----SCLK-------- GPIO14 +- 8-VDD ---------------- 3.3V +*/ const char* ssid = "wf-home"; const char* password = "0ndthnrf"; const char* mqtt_server = "192.168.1.250"; + +const int scePin = 15; // SCE - Chip select + +const double vRef = 3.3; +const int period = 1000; //us + unsigned long cRun = millis(); -double curr; +double curr = 0.0; +double currT = 0.0; +double currM = 0.0; int nSec, nSampl; -EnergyMonitor emon1; +void connectToWifi(); +void connectToMqtt(); + +WiFiClient espClient; +PubSubClient mClient(espClient); +void reconnect(); -AsyncMqttClient mqttClient; -Ticker mqttReconnectTimer; WiFiEventHandler wifiConnectHandler; WiFiEventHandler wifiDisconnectHandler; -Ticker wifiReconnectTimer; + +void spiBegin(); +void mcp_output(); + +Ticker tckrElcnt(mcp_output, period, 0, MILLIS); void connectToWifi() { Serial.println("Connecting to Wi-Fi..."); WiFi.begin(ssid, password); -} - -void connectToMqtt() { - Serial.println("Connecting to MQTT..."); - mqttClient.connect(); + while (!WiFi.isConnected()){ + Serial.print("."); + delay(1000); + } } void onWifiConnect(const WiFiEventStationModeGotIP& event) { Serial.println("Connected to Wi-Fi."); Serial.print("IP: "); Serial.println(WiFi.localIP()); - connectToMqtt(); + Serial.println("Connecting to MQTT..."); + //reconnect(); digitalWrite(LED_WF, HIGH); } void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { Serial.println("Disconnected from Wi-Fi."); - mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi - wifiReconnectTimer.once(2, connectToWifi); digitalWrite(LED_WF, LOW); } -void onMqttConnect(bool sessionPresent) { - Serial.println("Connected to MQTT."); - Serial.print("Session present: "); - Serial.println(sessionPresent); - digitalWrite(LED_MQ, HIGH); -} - -void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { - //Serial.println("Disconnected from MQTT."); - - if (WiFi.isConnected()) { - mqttReconnectTimer.once(2, connectToMqtt); - } - digitalWrite(LED_MQ, LOW); -} void setup(){ Serial.begin(9600); WiFi.mode(WIFI_STA); - WiFi.hostname("Electro"); - Serial.begin(9600); + WiFi.hostname(HOST_NAME); + Serial.begin(115200); - emon1.current(0, 30.0); - - ArduinoOTA.onStart([]() { - Serial1.println("Start Update"); // "Начало OTA-апдейта" - }); - ArduinoOTA.onEnd([]() { - Serial1.println("\nEnd Update"); // "Завершение OTA-апдейта" - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - //Serial1.printf("Progress: %u%%\r", (progress / (total / 100))); - }); - ArduinoOTA.onError([](ota_error_t error) { - Serial1.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) Serial1.println("Auth Failed"); - // "Ошибка при аутентификации" - else if (error == OTA_BEGIN_ERROR) Serial1.println("Begin Failed"); - // "Ошибка при начале OTA-апдейта" - else if (error == OTA_CONNECT_ERROR) Serial1.println("Connect Failed"); - // "Ошибка при подключении" - else if (error == OTA_RECEIVE_ERROR) Serial1.println("Receive Failed"); - // "Ошибка при получении данных" - else if (error == OTA_END_ERROR) Serial1.println("End Failed"); - // "Ошибка при завершении OTA-апдейта" - }); ArduinoOTA.begin(); + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); - mqttClient.onConnect(onMqttConnect); - mqttClient.onDisconnect(onMqttDisconnect); - mqttClient.setServer(mqtt_server, 1883); - mqttClient.setClientId("Electro"); + mClient.setServer("192.168.1.250", 1883); pinMode(LED_WF, OUTPUT); pinMode(LED_MQ, OUTPUT); pinMode(LED_WRK, OUTPUT); - //pinMode(5, INPUT_PULLUP); + pinMode(scePin, OUTPUT); + digitalWrite(scePin, HIGH); + //spiBegin(); digitalWrite(LED_WF, LOW); digitalWrite(LED_MQ, LOW); digitalWrite(LED_WRK, LOW); + connectToWifi(); nSec = 0; curr = -1; nSampl = 0; + //tckrElcnt.start(); } void loop(){ static bool led_wrk = false; - + //tckrElcnt.update(); ArduinoOTA.handle(); - yield(); + if(!mClient.connected()){ + reconnect(); + } + mClient.loop(); if(cRun + 999 < millis()){ cRun = millis(); - double Irms = 0; + mcp_output(); + nSampl++; + currM += curr; if(WiFi.isConnected()){ - Irms = emon1.calcIrms(1480) - 0.5; - if(curr < 0){ - curr = Irms; - } - else{ - //curr += (Irms - curr) / 60; - curr += (Irms); - } - // Serial.print("Sec: "); - // yield(); - // Serial.print(nSec); - // yield(); + Serial.printf("Sec: %d\t%.2f\n", nSec, curr); // Serial.print("\t"); - // yield(); - // Serial.print(Irms); - // yield(); - // Serial.print("\t"); - // yield(); - // Serial.println(Irms * 233); + // Serial.println(curr * 233); led_wrk = !led_wrk; digitalWrite(LED_WRK, led_wrk); - nSampl++; } if(++nSec > 59){ nSec = 0; - // Serial.print("Millis: "); - // yield(); - // Serial.print(millis()); - // yield(); - // Serial.print("\t"); - // yield(); - // Serial.print(curr); - // yield(); - // Serial.print("\t"); - // yield(); - // Serial.println(curr * 233); - if(nSampl > 0){ - //Serial.println("Publish"); - curr = curr / (double)nSampl; - char v[7]; - sprintf(v, "%.2f", curr); - mqttClient.publish("/home/kor/curr", 1, false, v); - } - nSampl = 0; - curr = -1; + currM = currM / 60.0; + char v[7]; + Serial.printf("Publish min, curr=%.2f\n", currM); + sprintf(v, "%.2f", curr); + mClient.publish(MAIN_TOPIC "curr", v); + //mqttClient.publish(MAIN_TOPIC "curr", 1, false, v); + currM = 0.0; } } } +void mcp_output(){ + double currTI = 0.0; + int sampl = 0; + int out = 0; + unsigned long start = micros(); + //while((start + 20000) >= micros()){ + SPI.begin(); + SPI.setDataMode(SPI_MODE0); + SPI.setBitOrder(MSBFIRST); + SPI.setFrequency(800000); + digitalWrite(scePin, LOW); + out = SPI.transfer16(0x0000); + digitalWrite(scePin, HIGH); + //yield(); + //delayMicroseconds(5); + out = out << 3; //Must shift out the 3 MSB's (trash bits) + out = out >> 4; + currTI += out;// * (vRef / 4096); // Using VRef + sampl++; + //} + Serial.printf("Time=%d, Out = %d, Samples=%d\n", int(micros() - start), out, sampl); + //curr = 30.0 * sqrt(currTI / sampl); + curr = currTI / sampl; +} + + +void spiBegin(void) +{ + pinMode(scePin, OUTPUT); + + SPI.begin(); + SPI.setDataMode(SPI_MODE0); + SPI.setBitOrder(MSBFIRST); + SPI.setFrequency(800000); + digitalWrite(scePin, HIGH); +} + +void reconnect() { + // Loop until we're reconnected + if(!WiFi.isConnected()) return; + while (!mClient.connected()) { + Serial.print("Attempting MQTT connection..."); + // Attempt to connect + if (mClient.connect(HOST_NAME)) { + Serial.println("connected"); + // Once connected, publish an announcement... + } else { + Serial.print("failed, rc="); + Serial.print(mClient.state()); + Serial.println(" try again in 5 seconds"); + // Wait 0.5 seconds before retrying + delay(500); + } + } +} diff --git a/ExtSens/platformio.ini b/ExtSens/platformio.ini index b835a88..52a65cc 100644 --- a/ExtSens/platformio.ini +++ b/ExtSens/platformio.ini @@ -16,3 +16,4 @@ monitor_speed = 115200 lib_deps = enjoyneering/AHT10@^1.1.0 mysensors/MySensors @ ^2.3.2 + robtillaart/RunningMedian @ ^0.3.3 diff --git a/ExtSens/src/main.cpp b/ExtSens/src/main.cpp index fbfcafd..50a0668 100644 --- a/ExtSens/src/main.cpp +++ b/ExtSens/src/main.cpp @@ -10,6 +10,7 @@ #define MY_DEFAULT_LED_BLINK_PERIOD 5 #include #include +#include "RunningMedian.h" uint32_t cRun; int BATTERY_SENSE_PIN = A0; @@ -28,20 +29,27 @@ void sendData(MyMessage msg, bool status); void sendData(MyMessage msg, uint32_t status); AHT10 myAHT10(AHT10_ADDRESS_0X38); +#define TIME_SLEEP 300000 + +RunningMedian tempRM = RunningMedian(4); +RunningMedian humRM = RunningMedian(4); void setup() { - analogReference(INTERNAL); - sensorValue = analogRead(BATTERY_SENSE_PIN); - v = sensorValue * 0.004659498; - batteryPcnt = (v-3.0 * 100) / 1.2; + float temp, hum; + //analogReference(INTERNAL); + //sensorValue = analogRead(BATTERY_SENSE_PIN); + //v = sensorValue * 0.004659498; + //batteryPcnt = (v-3.0 * 100) / 1.2; while (myAHT10.begin() != true) { Serial.println(F("AHT10 not connected or fail to load calibration coefficient")); //(F()) save string to flash & keeps dynamic memory free delay(5000); } Serial.println(F("AHT10 OK")); - Serial.print(F("T: ")); Serial.print(myAHT10.readTemperature(AHT10_FORCE_READ_DATA));// Serial.println(F(" +-0.3C")); - Serial.print(F("H: ")); Serial.print(myAHT10.readHumidity(AHT10_USE_READ_DATA));// Serial.println(F(" +-2%")); + Serial.print(F("T: ")); Serial.print(temp = myAHT10.readTemperature(AHT10_FORCE_READ_DATA));// Serial.println(F(" +-0.3C")); + Serial.print(F("H: ")); Serial.print(hum = myAHT10.readHumidity(AHT10_USE_READ_DATA));// Serial.println(F(" +-2%")); + sendData(msgTemp, temp, 1); + sendData(msgHum, hum, 1); cRun = 0; sendData(msgMillis, cRun); @@ -49,28 +57,36 @@ void setup() { } void loop() { - float temp, hum; - unsigned long t = millis(); - temp = myAHT10.readTemperature(AHT10_FORCE_READ_DATA); - hum = myAHT10.readHumidity(AHT10_USE_READ_DATA); - Serial.print(F("T: ")); Serial.println(temp);// Serial.println(F(" +-0.3C")); - Serial.print(F("H: ")); Serial.println(hum);// Serial.println(F(" +-2%")); - if (temp < 200){ - sendData(msgTemp, temp, 1); - sendData(msgHum, hum, 1); - // send(msgTemp.set(temp, 1)); - // send(msgHum.set(hum, 1)); - } - sensorValue = analogRead(BATTERY_SENSE_PIN); - v = sensorValue * 0.004659498; - //batteryPcnt = ((v-3.0) * 100) / 1.2; - //sendBatteryLevel(batteryPcnt); + float temp, hum; + static uint8_t nRun = 0; + unsigned long t = millis(); + + temp = myAHT10.readTemperature(AHT10_FORCE_READ_DATA); + hum = myAHT10.readHumidity(AHT10_USE_READ_DATA); + //Serial.print(F("T: ")); Serial.println(temp);// Serial.println(F(" +-0.3C")); + //Serial.print(F("H: ")); Serial.println(hum);// Serial.println(F(" +-2%")); + if (temp < 200){ + tempRM.add(temp); + humRM.add(hum); + // send(msgTemp.set(temp, 1)); + // send(msgHum.set(hum, 1)); + } + unsigned long battMV = hwCPUVoltage(); + v = battMV / 1000.0; + //sensorValue = analogRead(BATTERY_SENSE_PIN); + //v = sensorValue * 0.004659498; + //batteryPcnt = ((v-3.0) * 100) / 1.2; + //sendBatteryLevel(batteryPcnt); + if(nRun == 3){ + sendData(msgTemp, tempRM.getMedian(), 1); + sendData(msgHum, humRM.getMedian(), 1); sendData(msgVolts, v, 2); //send(msgVolts.set(v, 2)); - Serial.println(F("Tm run")); Serial.println(millis() - t); - sendData(msgMillis, cRun++); - //send(msgMillis.set(cRun++)); - sleep(120000 - (millis() - t)); + //Serial.println(F("Tm run")); Serial.println(millis() - t); + sendData(msgMillis, ++cRun * TIME_SLEEP / 60000); + } + //send(msgMillis.set(cRun++)); + sleep((TIME_SLEEP / 4) - (millis() - t)); } void presentation()