Лень, как известно, двигатель прогресса и захотелось мне немного автоматизировать дачу. Вводная стояла такая:
1. Управление освещением в двух местах дублируя настенные выключатели
2. Управление двумя клапанами для полива
3. Управление посредством телефона
4. Никакого блютуза
5. Мониторинг температуры внутри помещения (атмосферного давления, влажности...)
6. Питание от батарей с мониторингом на случай отключения ЭЭ
Материалы: Wemos D1 mini + BME280 + релейный блок на 4 реле
Собственно всё работает, НО при подборке корпуса попался настенный светильник и захотелось мне ещё и света от данного гибрида. Вклеил кусок WS2812 на 22 диода ну и хочется добавить ttp223 для включения - выключения руками.
В процессе тестов, написания и отладки - я перегорел (устал, замучился, ушатался ... нужное подчеркнуть)
Поэтому прошу помощи в добавлении кода. В идеале хотелось бы менять цвета в 4х преднастроенных вариантах и ползунок яркости ну и вкл-выкл само собой там-же (ttp223 должна дублировать этот функционал, например: включение и выключение - одинарное нажатие., смена преднастроенного свечения - двойное, держание ttp223 - плавная смена яркости циклично ).
1. Управление освещением в двух местах дублируя настенные выключатели
2. Управление двумя клапанами для полива
3. Управление посредством телефона
4. Никакого блютуза
5. Мониторинг температуры внутри помещения (атмосферного давления, влажности...)
6. Питание от батарей с мониторингом на случай отключения ЭЭ
Материалы: Wemos D1 mini + BME280 + релейный блок на 4 реле
Собственно всё работает, НО при подборке корпуса попался настенный светильник и захотелось мне ещё и света от данного гибрида. Вклеил кусок WS2812 на 22 диода ну и хочется добавить ttp223 для включения - выключения руками.
В процессе тестов, написания и отладки - я перегорел (устал, замучился, ушатался ... нужное подчеркнуть)
Поэтому прошу помощи в добавлении кода. В идеале хотелось бы менять цвета в 4х преднастроенных вариантах и ползунок яркости ну и вкл-выкл само собой там-же (ttp223 должна дублировать этот функционал, например: включение и выключение - одинарное нажатие., смена преднастроенного свечения - двойное, держание ttp223 - плавная смена яркости циклично ).
C++:
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
//For BATTERY read
unsigned int raw=0;
float volt=0.0;
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
// Replace with your network credentials
const char* ssid = "ABCDEF";
const char* password = "12345678";
// Auxiliary variables to store the current output state
String output14State = "off";
String output12State = "off";
String output13State = "off";
String output15State = "off";
// Assign output variables to GPIO pins
const int output14 = 14;
const int output12 = 12;
const int output13 = 13;
const int output15 = 15;
//статический IP
//IPAddress ip(192,168,87,217);
//IPAddress gateway(192,168,87,1);
//IPAddress subnet(255,255,255,0);
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
void setup() {
Serial.begin(115200);
// Setup A0 to work with BATTERY
pinMode(A0, INPUT);
raw = analogRead(A0);
volt=raw/1023.0;
volt=volt*4.2;
// Initialize the output variables as outputs
pinMode(output14, OUTPUT);
pinMode(output12, OUTPUT);
pinMode(output13, OUTPUT);
pinMode(output15, OUTPUT);
// Set outputs to LOW
digitalWrite(output14, LOW);
digitalWrite(output12, LOW);
digitalWrite(output13, LOW);
digitalWrite(output15, LOW);
// default settings
// (you can also pass in a Wire library object like &Wire2)
//status = bme.begin();
if (!bme.begin(0x76)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) {
currentTime = millis();
previousTime = currentTime;
// If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
currentTime = millis();
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
if (header.indexOf("GET /12/on") >= 0) {
Serial.println("GPIO 12 on");
output12State = "on";
digitalWrite(output12, HIGH);
} else if (header.indexOf("GET /12/off") >= 0) {
Serial.println("GPIO 12 off");
output12State = "off";
digitalWrite(output12, LOW);
} else if (header.indexOf("GET /13/on") >= 0) {
Serial.println("GPIO 13 on");
output13State = "on";
digitalWrite(output13, HIGH);
} else if (header.indexOf("GET /13/off") >= 0) {
Serial.println("GPIO 13 off");
output13State = "off";
digitalWrite(output13, LOW);
} else if (header.indexOf("GET /14/on") >= 0) {
Serial.println("GPIO 14 on");
output14State = "on";
digitalWrite(output14, HIGH);
} else if (header.indexOf("GET /14/off") >= 0) {
Serial.println("GPIO 14 off");
output14State = "off";
digitalWrite(output14, LOW);
} else if (header.indexOf("GET /15/on") >= 0) {
Serial.println("GPIO 15 on");
output15State = "on";
digitalWrite(output15, HIGH);
} else if (header.indexOf("GET /15/off") >= 0) {
Serial.println("GPIO 15 off");
output15State = "off";
digitalWrite(output15, LOW);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the table
//client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: left;}");
client.println("h1 { text-align: center; }");
client.println("table { border-collapse: collapse; width:80%; margin-left:auto; margin-right:auto; }");
client.println("th { padding: 12px; background-color: #0043af; color: white; }");
client.println("tr { border: 1px solid #ddd; padding: 12px; }");
client.println("tr:hover { background-color: #bcbcbc; }");
client.println("td { border: none; padding: 12px; }");
client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
client.println(".buttons { display: flex; justify-content: center; }");
client.println(".buttons .button-block { padding: 15px; }");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println(".button { background-color: #c23030; border: none; color: white; padding: 8px 20px;");
client.println("text-decoration: none; font-size: 15px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #4CAF50;}</style></head>");
// Web Page Heading
client.println("</style></head><body><h1>Умная Дача</h1>");
// Buttons
client.println("<div class=\"buttons\">");
client.println("<div class=\"button-block\">");
// Display current state, and ON/OFF buttons for GPIO 14
client.println("<div class=\"title\">Веранда</div>");
// If the output14State is off, it displays the ON button
if (output14State=="off") {
client.println("<a href=\"/14/on\"><button class=\"button\">ВЫКЛ</button></a>");
} else {
client.println("<a href=\"/14/off\"><button class=\"button button2\">ВКЛ</button></a>");
}
client.println("</div>");
client.println("<div class=\"button-block\">");
// Display current state, and ON/OFF buttons for GPIO 12
client.println("<div class=\"title\">Зал</div>");
// If the output12State is off, it displays the ON button
if (output12State=="off") {
client.println("<a href=\"/12/on\"><button class=\"button\">ВЫКЛ</button></a>");
} else {
client.println("<a href=\"/12/off\"><button class=\"button button2\">ВКЛ</button></a>");
}
client.println("</div>");
client.println("<div class=\"button-block\">");
// Display current state, and ON/OFF buttons for GPIO 13
client.println("<div class=\"title\">Полив 1</div>");
// If the output13State is off, it displays the ON button
if (output13State=="off") {
client.println("<a href=\"/13/on\"><button class=\"button\">ВЫКЛ</button></a>");
} else {
client.println("<a href=\"/13/off\"><button class=\"button button2\">ВКЛ</button></a>");
}
client.println("</div>");
client.println("<div class=\"button-block\">");
// Display current state, and ON/OFF buttons for GPIO 15
client.println("<div class=\"title\">Полив 2</div>");
// If the output15State is off, it displays the ON button
if (output15State=="off") {
client.println("<a href=\"/15/on\"><button class=\"button\">ВЫКЛ</button></a>");
} else {
client.println("<a href=\"/15/off\"><button class=\"button button2\">ВКЛ</button></a>");
}
client.println("</div>");
client.println("</div>");
// Info table
client.println("<table><tr><th>Параметр</th><th>Значение</th></tr>");
client.println("<tr><td>Температура, °C</td><td><span class=\"sensor\">");
client.println(bme.readTemperature());
client.println("</span></td></tr>");
client.println("<tr><td>Давление, мм.рт.ст</td><td><span class=\"sensor\">");
client.println(bme.readPressure() / 133.32239F);
client.println("</span></td></tr>");
client.println("<tr><td>Высота над уровнем моря, м</td><td><span class=\"sensor\">");
client.println(bme.readAltitude(SEALEVELPRESSURE_HPA));
client.println("</span></td></tr>");
client.println("<tr><td>Влажность, %</td><td><span class=\"sensor\">");
client.println(bme.readHumidity());
client.println("</span></td></tr>");
client.println("<tr><td>Напряжение батареи, В</td><td><span class=\"sensor\">");
client.println (volt);
client.println("</span></td></tr>");
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}