SOnOff NSPanel
Table of Contents
Links
Overview Page for Sonoff NSPanel and Tasmota installation.
Starter Code Still in Progress
–
Overview Page for Sonoff NSPanel and Tasmota installation.
–
Just some Links I don’t want to forget!
–
Some testing for Savable Settings via a WebServer
// _ ___ __ _ _
// | || \ \ / / | | (_)
// | || |\ \ /\ / /__ | |__ _
// |__ _\ \/ \/ / _ \| '_ \| |
// | | \ /\ / (_) | |_) | |
// |_| \/ \/ \___/|_.__/|_|.com
//
// Import required libraries
#include
#include
#include
#include "EEPROM.h"
#include "html.h"
const char* PARAM_INPUT_1 = "output";
const char* PARAM_INPUT_2 = "state";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Replaces placeholder with button section in your web page
String processor(const String& var) {
//Serial.println(var);
if (var == "BUTTONPLACEHOLDER") {
String buttons = "";
buttons += "Output - GPIO 2
";
buttons += "Output - GPIO 0
";
buttons += "Output - GPIO 4
";
return buttons;
}
return String();
}
String outputState(int output) {
if (digitalRead(output)) {
return "checked";
}
else {
return "";
}
}
void EEPROMSetup() {
// STARTING EEPROM
if (!EEPROM.begin(1000)) {
Serial.println("Failed to initialise EEPROM");
Serial.println("Restarting...");
delay(1000);
ESP.restart();
}
int address = 0;
EEPROM.writeFloat(address, 421321.134123);
address += sizeof(float);
String sentence = "I love ESP32.";
EEPROM.writeInt(address, sentence.length());
address += sizeof(int);
EEPROM.writeString(address, sentence);
address += sentence.length() + 1;
EEPROM.writeDouble(address, -123456789.123456789);
address += sizeof(double);
EEPROM.commit();
address = 0;
Serial.println(EEPROM.readFloat(address), 4);
address += sizeof(float);
int i = EEPROM.readInt(address);
Serial.println(i);
address += sizeof(int);
Serial.println(EEPROM.readString(address));
address += i + 1;
Serial.println(EEPROM.readDouble(address), 8);
address += sizeof(double);
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
while (!Serial) continue;
pinMode(5, OUTPUT);
digitalWrite(5, LOW);
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
pinMode(4 , OUTPUT);
digitalWrite(4, LOW);
EEPROMSetup();
// Connect to Wi-Fi
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
WiFiManager wm;
//wm.resetSettings();
bool res; // WifiManager
res = wm.autoConnect("AutoConnectAP", "password"); // password protected ap
if (!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
// Print ESP Local IP Address
// Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send_P(200, "text/html", index_html, processor);
});
// Send a GET request to /update?output=&state=
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest * request) {
String inputMessage1;
String inputMessage2;
// GET input1 value on /update?output=&state=
if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
inputMessage1 = request->getParam(PARAM_INPUT_1)->value();
inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
digitalWrite(inputMessage1.toInt(), inputMessage2.toInt());
}
else {
inputMessage1 = "No message sent";
inputMessage2 = "No message sent";
}
Serial.print("GPIO: ");
Serial.print(inputMessage1);
Serial.print(" - Set to: ");
Serial.println(inputMessage2);
request->send(200, "text/plain", "OK");
});
// Start server
server.begin();
}
void loop() {
}
#ifndef HTML_H
#define HTML_H
const char index_html[] PROGMEM = R"rawliteral(
ESP Web Server
ESP Wobi Web Server
%BUTTONPLACEHOLDER%
)rawliteral";
#endif
–
Some demo form Adafruit_AHTx0.h
/*
I used this code with a ESP32c3
*/
#include
Adafruit_AHTX0 aht;
// change in pins_arduino.h if you want other i2c Pins! PATH: C:\Users\:userName:\AppData\Local\Arduino15\packages\esp32\hardware\esp32\2.0.3-RC1\variants\esp32c3
// static const uint8_t SDA = 7;
// static const uint8_t SCL = 8;
Adafruit_Sensor *aht_humidity, *aht_temp;
void setup(void) {
Serial.begin(115200);
while (!Serial)
delay(10); // will pause Zero, Leonardo, etc until serial console opens
Serial.println("Adafruit AHT10/AHT20 test!");
if (!aht.begin()) {
Serial.println("Failed to find AHT10/AHT20 chip");
while (1) {
delay(10);
}
}
Serial.println("AHT10/AHT20 Found!");
aht_temp = aht.getTemperatureSensor();
aht_temp->printSensorDetails();
aht_humidity = aht.getHumiditySensor();
aht_humidity->printSensorDetails();
}
void loop() {
// /* Get a new normalized sensor event */
sensors_event_t humidity;
sensors_event_t temp;
aht_humidity->getEvent(&humidity);
aht_temp->getEvent(&temp);
Serial.print("\tHumidity: \t");
Serial.print(humidity.relative_humidity);
Serial.println(" % rH");
Serial.print("\tTemperature: \t");
Serial.print(temp.temperature);
Serial.println(" degrees C");
Serial.println();
delay(1000);
}
–
Some testing with ezButton.h
#include
#define BUTTON_PIN 9
#define DEBOUNCE_TIME 50
const int SHORT_PRESS_TIME = 1000;
const int LONG_PRESS_TIME = 1000;
const int MULTI_PRESS_TIME = 500;
unsigned long multiPressTimer = 0;
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
bool isPressing = false;
bool isLongDetected = false;
int multiPressCount = 0;
ezButton button(BUTTON_PIN);
void setup() {
button.setDebounceTime(DEBOUNCE_TIME);
button.setCountMode(COUNT_FALLING);
Serial.begin(115200);
Serial.println();
}
void loop() {
button.loop();
int btnState = button.getState();
// Serial.println(btnState);
unsigned long count = button.getCount();
if (count >= 100) {
Serial.println(count);
button.resetCount();
}
if (button.isPressed())
Serial.println("The button is pressed");
if (button.isReleased())
Serial.println("The button is released");
if (button.isPressed()) {
pressedTime = millis();
isPressing = true;
isLongDetected = false;
}
if (button.isReleased()) {
isPressing = false;
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if ( pressDuration < SHORT_PRESS_TIME ) {
Serial.println("A short press is detected");
++multiPressCount;
Serial.println(multiPressCount);
multiPressTimer = millis();
}
}
unsigned long now = millis();
if (isPressing == false && now - multiPressTimer > MULTI_PRESS_TIME) {
multiPressCount = 0;
}
//if (isPressing == true && multiPressCount > 0) {
// Serial.println(multiPressCount);
//}
if (isPressing == true && isLongDetected == false) {
long pressDuration = millis() - pressedTime;
if ( pressDuration > LONG_PRESS_TIME ) {
Serial.println("A long press is detected");
isLongDetected = true;
}
}
}
–
Some testing with ArduinoJson.h
All Code is tested with a ESP32C3!
// https://arduinojson.org/v6/api/json/
#include "ArduinoJson.h"
unsigned int valueJson = 0;
String jsonStart = "{\"SensorType\": \"Temperature\", \"Value\": ";
String jsonEnding = "}";
void setup() {
Serial.begin(115200);
Serial.println();
delay(10);
Serial.println(F("__________________________________________"));
Serial.println(F(""));
Serial.println(F(" _ _ __ v0.1 __ _ _ "));
Serial.println(F(" | || |\\ \\ / / | | (_)"));
Serial.println(F(" | || |_\\ \\ /\\ / /___ | |__ _ "));
Serial.println(F(" |__ _|\\ \\/ \\/ // _ \\ | '_ \\ | |"));
Serial.println(F(" | | \\ /\\ /| (_) || |_) || |"));
Serial.println(F(" |_| \\/ \\/ \\___/ |_.__/ |_|"));
Serial.println(F(""));
Serial.println(F("__________________________________________"));
Serial.println(F(""));
}
void loop() {
// CREATE JSON MESSAGE
char b[2];
String str;
str = jsonStart + String(valueJson) + jsonEnding;
str.toCharArray(b, 2);
valueJson += 1;
StaticJsonDocument<300> parsed;
DeserializationError err = deserializeJson(parsed, str); // CHANGE JSONMessage to "!!NOT JSON!!" for err
if (err) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(err.c_str());
delay(5000);
return;
}
Serial.println("JsonObj");
serializeJsonPretty(parsed, Serial);
Serial.println();
const char * sensorType = parsed["SensorType"];
int value = parsed["Value"];
printTypeVal(sensorType, value);
delay(1000);
}
void printTypeVal(const char *type, int val) {
Serial.println("Parsed");
Serial.print("Sensor type: ");
Serial.println(type);
Serial.print("Sensor value: ");
Serial.println(val);
Serial.println();
}
#include
#include
#include
const String endpoint = "https://api.openweathermap.org/data/2.5/onecall?lat=47.506904&lon=7.732428&exclude=alerts,minutely,daily,hourly&appid=";
const String key = "YOURKEY";
const String unitsSystem = "&units=metric";
void setup() {
Serial.begin(115200);
while (!Serial) continue;
WiFi.mode(WIFI_STA);
WiFiManager wm;
// wm.resetSettings();
bool res;
res = wm.autoConnect("AutoConnectAP", "password"); // password protected ap
if (!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
else {
Serial.println("connected...yeey :)");
}
}
void loop() {
if ((WiFi.status() == WL_CONNECTED)) {
HTTPClient http;
http.begin(endpoint + key + unitsSystem);
int httpCode = http.GET();
if (httpCode > 0) {
// String payload = http.getString();
// const size_t capacity = JSON_ARRAY_SIZE(5) + 5 * JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + 200;
// DynamicJsonDocument doc(capacity);
StaticJsonDocument<512> doc;
DeserializationError err = deserializeJson(doc, http.getStream() );
if (err) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(err.f_str());
}
serializeJsonPretty(doc, Serial);
Serial.println();
float lat = doc["lat"]; // 47.5069
float lon = doc["lon"]; // 7.7324
const char* timezone = doc["timezone"]; // "Europe/Zurich"
int timezone_offset = doc["timezone_offset"]; // 7200
JsonObject current = doc["current"];
long current_dt = current["dt"]; // 1650728898
long current_sunrise = current["sunrise"]; // 1650687959
long current_sunset = current["sunset"]; // 1650738510
float current_temp = current["temp"]; // 15.01
float current_feels_like = current["feels_like"]; // 14.13
int current_pressure = current["pressure"]; // 990
int current_humidity = current["humidity"]; // 60
float current_dew_point = current["dew_point"]; // 7.32
float current_uvi = current["uvi"]; // 0.73
int current_clouds = current["clouds"]; // 75
int current_visibility = current["visibility"]; // 10000
float current_wind_speed = current["wind_speed"]; // 5.14
int current_wind_deg = current["wind_deg"]; // 350
JsonObject current_weather_0 = current["weather"][0];
int current_weather_0_id = current_weather_0["id"]; // 803
const char* current_weather_0_main = current_weather_0["main"]; // "Clouds"
const char* current_weather_0_description = current_weather_0["description"]; // "broken clouds"
const char* current_weather_0_icon = current_weather_0["icon"]; // "04d"
Serial.print("TheTemp: ");
Serial.print(current_temp);
Serial.println(" °C");
Serial.println(doc["lat"].as());
}
else {
Serial.println("Error on HTTP request");
}
http.end();
}
delay(120000);
}
–
Short Example to controll onBoard Butt0n and LED’s.
// ESP32 BOARDS PACKAGE
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
// https://4wobi.com/2022/04/14/esp32-esp-c3-32s-kit/
//
// Install ESP32 Board Package
// https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
//
// ESP32C3 Dev Module
// Flash Frequency: 40Mhz
// Flash Size: 2MB(16Mb)
//
// Source: https://microcontrollerslab.com/esp32-rgb-led-web-server/
//
/* Ai-Thinker ESP-C3-32S-Kit
* RGB LED: IO5 RGB blue;
* IO3 RGB red;
* IO4 RGB green;
* WARLM LED: IO19
* COLD LED: IO18
* RIGHT BUTTON: IO9
*/
#include
#include
String webpage = ""
"RGB control "
""
""
"";
// WIFI SETTINGS
const char* ssid = "WIFI";
const char* password = "PW";
const byte DNS_PORT = 53;
// BUTTON SETTINGS
const int buttonPin = 9;
int buttonState = 1;
int lastButtonState = 1;
// LED SETTINGS
const int warmPin = 18;
const int coldPin = 19;
int lampState = 0;
unsigned int ledTimer = 5000;
unsigned long ledLastTimer = 0;
// RGB LED SETTINGS
const int red_pin = 3;
const int green_pin = 4;
const int blue_pin = 5;
// Setting PWM frequency, channels and bit resolution
const int frequency = 5000;
const int redChannel = 0;
const int greenChannel = 1;
const int blueChannel = 2;
const int resolution = 8;
WebServer webServer(80);
void handleRoot() {
String red_pin = webServer.arg(0);
String green_pin = webServer.arg(1);
String blue_pin = webServer.arg(2);
if ((red_pin != "") && (green_pin != "") && (blue_pin != ""))
{
ledcWrite(redChannel, 1023 - red_pin.toInt());
ledcWrite(greenChannel, 1023 - green_pin.toInt());
ledcWrite(blueChannel, 1023 - blue_pin.toInt());
}
Serial.print("Red: ");
Serial.println(red_pin.toInt());
Serial.print("Green: ");
Serial.println(green_pin.toInt());
Serial.print("Blue: ");
Serial.println(blue_pin.toInt());
Serial.println();
webServer.send(200, "text/html", webpage);
}
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(warmPin, OUTPUT);
pinMode(coldPin, OUTPUT);
ledcSetup(redChannel, frequency, resolution);
ledcSetup(greenChannel, frequency, resolution);
ledcSetup(blueChannel, frequency, resolution);
ledcAttachPin(red_pin, redChannel);
ledcAttachPin(green_pin, greenChannel);
ledcAttachPin(blue_pin, blueChannel);
delay(1000);
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
webServer.on("/", handleRoot);
webServer.begin();
}
void loop() {
webServer.handleClient();
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && lastButtonState == 0) {
Serial.println("Button HIGH");
lastButtonState = 1;
} else if (buttonState == LOW && lastButtonState == 1) {
Serial.println("Button LOW");
lastButtonState = 0;
}
unsigned long now = millis();
if (now - ledLastTimer > ledTimer) {
ledLastTimer = now;
if (lampState == 0) {
lampState = 1;
Serial.println("Cold High");
digitalWrite(warmPin, LOW);
digitalWrite(coldPin, HIGH);
}
else {
lampState = 0;
Serial.println("Warm High");
digitalWrite(coldPin, LOW);
digitalWrite(warmPin, HIGH);
}
}
}
–
#include // https://github.com/tzapu/WiFiManager
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
// it is a good practice to make sure your code sets wifi mode how you want it.
// put your setup code here, to run once:
Serial.begin(115200);
//WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wm;
// reset settings - wipe stored credentials for testing
// these are stored by the esp library
//wm.resetSettings();
// Automatically connect using saved credentials,
// if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
// if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
// then goes into a blocking loop awaiting configuration and will return success result
bool res;
// res = wm.autoConnect(); // auto generated AP name from chipid
// res = wm.autoConnect("AutoConnectAP"); // anonymous ap
res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
if(!res) {
Serial.println("Failed to connect");
// ESP.restart();
}
else {
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
–
For single-phase circuits:
Wire Circular mm2= (Conductor Resistivity)(2)(Amps)(One Way Distance in inch) / Allowable Voltage Drop
For 3-phase circuits:
Wire Circular mm2= (Conductor Resistivity)(2)(Amps)(One Way Distance in inch)(.866) / Allowable Voltage Drop
This is at a temp of 20°C!
Connect to your new flashed Sonoff over WiFi
SSID will be something like that "tasmota_xxxxxx-xxxx" without a password
Now connect in browser to 192.168.4.1
The tasmota interface will show up
add your WiFi credentials
if an error showsup restart device
ifnot get the
button function_____________________________
setoption14 0
pulsetime1 10
MY Switch settings
_____________________________
savedata 1
SetOption13 1
setoption1 1
switchmode 5
setoption32 4
statetext4 Hold
buttontopic 1
setoption11 1
_____________________________