Почему не работает кнопка
Почему не работает кнопка
Здравствуйте.
Может кто объяснит, не пойму почему не работает кнопка в схеме.
Собрано на ESP-01s. Пины менял, не получается.
Может кто объяснит, не пойму почему не работает кнопка в схеме.
Собрано на ESP-01s. Пины менял, не получается.
У вас нет необходимых прав для просмотра вложений в этом сообщении.
- kulibinsvv
- Лейтенант
- Сообщения: 486
- Зарегистрирован: 18 сен 2015, 10:04
- Откуда: Омск
- Благодарил (а): 3 раза
- Поблагодарили: 5 раз
Почему не работает кнопка
Мой змей, этот ползучий соблазн сомнения,всё шевелится, побуждая «искать концы»... (Станислав Ермаков)
Почему не работает кнопка
Спасибо за ответы.
Исключающее ИЛИ вряд ли подойдёт, программно всё вроде правильно (я пробовал разные варианты), тут всё дело во входах.
Вот как раз ссылка из предыдущего сообщения "Kulibinsvv" навела на мысль о расширении входов по I2C.
Как появится под рукой MCP23017, хочу попробовать.
Исключающее ИЛИ вряд ли подойдёт, программно всё вроде правильно (я пробовал разные варианты), тут всё дело во входах.
Вот как раз ссылка из предыдущего сообщения "Kulibinsvv" навела на мысль о расширении входов по I2C.

Как появится под рукой MCP23017, хочу попробовать.
Почему не работает кнопка
Доброго дня, уважаемые. Не буду плодить еще одну тему с идентичным заголовком и спрошу тут. В общем-то, тоже самое.
Есть небольшой проект, термостат для курятника - я его, наверное, буду строить до гробовой доски
Проект построен на ESP8266 марки NodeMCU3. Внутри крутится убогий веб-серверок для "посмотреть не выходя из теплого дома", есть одно реле для управления обогревом, есть LCD экран, подключенный по шине I2C, датчик DS18B20. Это все работает стабильно, корректно и не вызывало трудностей. Потом я решил добавить три кнопки, чтбы корректировать температуру в помещении, находясь непосредственно на месте. А то пока домой прибегу из сарайчика, уже забуду о намерении поправить температуру. Добавил эти кнопки - и тут-то началось.
В общем, что-то никак не работают кнопки. В одном включении удалось получить "жалкое подобие левой", но настолько жалкое, что выпускать ЭТО - было никак нельзя. Если сможете - натолкните на мысль/решение, пожалуйста
Уже и пивом поливал платку, и даже корпус смастерил из вонючего пластика - а все равно не работает! Согласитесь, это уже черезчур
Подключено все так:
GPIO Connection
D1, D2..........LCD_I2C
D4...............DS18B20
D5...............Rele
D6, D7, D8.....Buttons
Код такой:
[spoiler]
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-e ... eb-server/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#else
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "LiquidCrystal_I2C.h"
#include <EEPROM.h>
#include <sbutton.h>
//==================================================================================================
//==================================================================================================
// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "r23";
const char* password = "123456789";
IPAddress ip(192,168,0,104); //статический IP ESP8266
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
// Default Threshold Temperature Value
//String inputMessage = "25.0";
String T_ON_Message = "25";
String T_OFF_Message = "27";
String lastTemperature;
String heater_state_str = "OFF";
String inputMessage2 = "true";
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
<meta http-equiv="refresh" content="5">
<title>Chickens WEB control page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<h3>Chickens WEB</h2>
<h3>Current temperature: %CURRENT_TEMPERATURE% °C</h3>
<h2>Heater setup: </h2>
<form action="/get">
Heater ON: <input type="number" step="1" name="T_ON_input" value="%T_ON_Message%" required><br>
Heater OFF: <input type="number" step="1" name="T_OFF_input" value="%T_OFF_Message%" required><br>
<input type="submit" value="Submit">
</form>
<h3>Heater is %HEATER_STATE%</h3>
</body></html>)rawliteral";
//---------------------------------------------------------------------------------------------------------------
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
AsyncWebServer server(80);
// Replaces placeholder with DS18B20 values
String processor(const String& var){
//Serial.println(var);
if(var == "CURRENT_TEMPERATURE"){return lastTemperature;}
else if(var == "T_ON_Message"){return T_ON_Message;}
else if(var == "T_OFF_Message"){return T_OFF_Message;}
else if(var == "HEATER_STATE"){return heater_state_str;}
return String();
}
//const char* PARAM_INPUT_2 = "enable_arm_input";
const char* PARAM_INPUT_1 = "T_ON_input";
const char* PARAM_INPUT_2 = "T_OFF_input";
// Interval between sensor readings. Learn more about ESP32 timers: https://RandomNerdTutorials.com/esp32-p ... ts-timers/
unsigned long previousMillis = 0;
const long interval = 3000; //3 seconds
// GPIO where the Rele is connected to
const int rele_pin = 14; //D5
// GPIO where the Buttons is connected to
const int button_ok_pin = 12; //D6
const int button_mns_pin = 13; //D7
const int button_pls_pin = 15; //D8
// GPIO where the DS18B20 is connected to
const int oneWireBus = 2; //D4
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
LiquidCrystal_I2C lcd(0x27, 16, 2);
Button button_pls(button_pls_pin, 300);
Button button_mns(button_mns_pin, 300);
Button button_ok(button_ok_pin, 300);
float temperature = 125;
int temp_on_addr = 0;
int temp_off_addr = 2;
float heater_on_temp;
float heater_off_temp;
bool heater_state = false;
int counter = 0;
//==================================================================================================
//--------------------------------------------------------------------------------------------------
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("ESP IP Address: http://");
Serial.println(WiFi.localIP());
pinMode(rele_pin, OUTPUT);
digitalWrite(rele_pin, LOW);
pinMode(button_pls_pin, INPUT_PULLUP);
pinMode(button_mns_pin, INPUT_PULLUP);
pinMode(button_ok_pin, INPUT_PULLUP);
if (digitalRead (button_ok_pin)==LOW)
{
EEPROM.put (temp_on_addr,25); EEPROM.put (temp_off_addr,27);
heater_on_temp = 25; heater_off_temp = 27;
};
// Start the DS18B20 sensor
sensors.begin();
// Send web page to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);});
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
// GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage>
if (request->hasParam(PARAM_INPUT_1)) {T_ON_Message = request->getParam(PARAM_INPUT_1)->value();
// GET enable_arm_input value on <ESP_IP>/get?enable_arm_input=<inputMessage2>
if (request->hasParam(PARAM_INPUT_2)) {T_OFF_Message = request->getParam(PARAM_INPUT_2)->value();}
}
request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
heater_on_temp = T_ON_Message.toFloat ();
heater_off_temp = T_OFF_Message.toFloat();
});
server.onNotFound(notFound);
server.begin();
EEPROM.get (temp_on_addr, heater_on_temp);
EEPROM.get (temp_off_addr, heater_off_temp);
T_ON_Message = String(heater_on_temp);
T_OFF_Message = String(heater_off_temp);
//heater_off_temp = eeprom_read_word (temp_off_addr);
lcd.init();
lcd.backlight();
lcd.clear ();
temperature = sensors.getTempCByIndex(0);
lcd.print ("Current T:");
lcd.print(temperature, 1);
lcd.setCursor (1,1); lcd.print ("ON:"); lcd.print(heater_on_temp, 0);
lcd.setCursor (7,1); lcd.print (" OFF:"); lcd.print(heater_off_temp, 0);
}
//==================================================================================================
void loop() {
button_pls.scanState();
button_mns.scanState();
button_ok.scanState();
if (button_pls.push == true) {counter = counter + 1;};
if (button_mns.push == true) {counter = counter - 1;};
if (button_ok.push == true) {counter = 0;};
lcd.setCursor (0,1);
lcd.print (counter); lcd.print (" ");
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
sensors.requestTemperatures();
// Temperature in Celsius degrees
temperature = sensors.getTempCByIndex(0);
lcd.clear ();
lcd.print ("Current T: "); lcd.print (temperature);
//lcd.setCursor (1,1); lcd.print ("ON:"); lcd.print(heater_on_temp, 0);
//lcd.setCursor (7,1); lcd.print (" OFF:"); lcd.print(heater_off_temp, 0);
lcd.setCursor (0,1);
lcd.print (counter);
lastTemperature = String(temperature);
// Check if temperature is above threshold and if it needs to trigger output
if(temperature <= T_ON_Message.toFloat()){
heater_state = true;
heater_state_str = "ON";
digitalWrite(rele_pin, HIGH);
};
// Check if temperature is below threshold and if it needs to trigger output
if((temperature > T_OFF_Message.toFloat())) {
heater_state = false;
heater_state_str = "OFF";
digitalWrite(rele_pin, LOW);
}
if (heater_state==true) {lcd.setCursor (15,1); lcd.print ("h");} else {lcd.setCursor (7,1); lcd.print (" ");};
}
}
[/spoiler]
Спасибо за внимание
П.С. Омайгадебля, я научился использовать спойлеры вместо безумных простыней кода
Есть небольшой проект, термостат для курятника - я его, наверное, буду строить до гробовой доски

В общем, что-то никак не работают кнопки. В одном включении удалось получить "жалкое подобие левой", но настолько жалкое, что выпускать ЭТО - было никак нельзя. Если сможете - натолкните на мысль/решение, пожалуйста


Подключено все так:
GPIO Connection
D1, D2..........LCD_I2C
D4...............DS18B20
D5...............Rele
D6, D7, D8.....Buttons
Код такой:
[spoiler]
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-e ... eb-server/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#else
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "LiquidCrystal_I2C.h"
#include <EEPROM.h>
#include <sbutton.h>
//==================================================================================================
//==================================================================================================
// REPLACE WITH YOUR NETWORK CREDENTIALS
const char* ssid = "r23";
const char* password = "123456789";
IPAddress ip(192,168,0,104); //статический IP ESP8266
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
// Default Threshold Temperature Value
//String inputMessage = "25.0";
String T_ON_Message = "25";
String T_OFF_Message = "27";
String lastTemperature;
String heater_state_str = "OFF";
String inputMessage2 = "true";
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
<meta http-equiv="refresh" content="5">
<title>Chickens WEB control page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<h3>Chickens WEB</h2>
<h3>Current temperature: %CURRENT_TEMPERATURE% °C</h3>
<h2>Heater setup: </h2>
<form action="/get">
Heater ON: <input type="number" step="1" name="T_ON_input" value="%T_ON_Message%" required><br>
Heater OFF: <input type="number" step="1" name="T_OFF_input" value="%T_OFF_Message%" required><br>
<input type="submit" value="Submit">
</form>
<h3>Heater is %HEATER_STATE%</h3>
</body></html>)rawliteral";
//---------------------------------------------------------------------------------------------------------------
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
AsyncWebServer server(80);
// Replaces placeholder with DS18B20 values
String processor(const String& var){
//Serial.println(var);
if(var == "CURRENT_TEMPERATURE"){return lastTemperature;}
else if(var == "T_ON_Message"){return T_ON_Message;}
else if(var == "T_OFF_Message"){return T_OFF_Message;}
else if(var == "HEATER_STATE"){return heater_state_str;}
return String();
}
//const char* PARAM_INPUT_2 = "enable_arm_input";
const char* PARAM_INPUT_1 = "T_ON_input";
const char* PARAM_INPUT_2 = "T_OFF_input";
// Interval between sensor readings. Learn more about ESP32 timers: https://RandomNerdTutorials.com/esp32-p ... ts-timers/
unsigned long previousMillis = 0;
const long interval = 3000; //3 seconds
// GPIO where the Rele is connected to
const int rele_pin = 14; //D5
// GPIO where the Buttons is connected to
const int button_ok_pin = 12; //D6
const int button_mns_pin = 13; //D7
const int button_pls_pin = 15; //D8
// GPIO where the DS18B20 is connected to
const int oneWireBus = 2; //D4
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
LiquidCrystal_I2C lcd(0x27, 16, 2);
Button button_pls(button_pls_pin, 300);
Button button_mns(button_mns_pin, 300);
Button button_ok(button_ok_pin, 300);
float temperature = 125;
int temp_on_addr = 0;
int temp_off_addr = 2;
float heater_on_temp;
float heater_off_temp;
bool heater_state = false;
int counter = 0;
//==================================================================================================
//--------------------------------------------------------------------------------------------------
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("ESP IP Address: http://");
Serial.println(WiFi.localIP());
pinMode(rele_pin, OUTPUT);
digitalWrite(rele_pin, LOW);
pinMode(button_pls_pin, INPUT_PULLUP);
pinMode(button_mns_pin, INPUT_PULLUP);
pinMode(button_ok_pin, INPUT_PULLUP);
if (digitalRead (button_ok_pin)==LOW)
{
EEPROM.put (temp_on_addr,25); EEPROM.put (temp_off_addr,27);
heater_on_temp = 25; heater_off_temp = 27;
};
// Start the DS18B20 sensor
sensors.begin();
// Send web page to client
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);});
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
// GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage>
if (request->hasParam(PARAM_INPUT_1)) {T_ON_Message = request->getParam(PARAM_INPUT_1)->value();
// GET enable_arm_input value on <ESP_IP>/get?enable_arm_input=<inputMessage2>
if (request->hasParam(PARAM_INPUT_2)) {T_OFF_Message = request->getParam(PARAM_INPUT_2)->value();}
}
request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
heater_on_temp = T_ON_Message.toFloat ();
heater_off_temp = T_OFF_Message.toFloat();
});
server.onNotFound(notFound);
server.begin();
EEPROM.get (temp_on_addr, heater_on_temp);
EEPROM.get (temp_off_addr, heater_off_temp);
T_ON_Message = String(heater_on_temp);
T_OFF_Message = String(heater_off_temp);
//heater_off_temp = eeprom_read_word (temp_off_addr);
lcd.init();
lcd.backlight();
lcd.clear ();
temperature = sensors.getTempCByIndex(0);
lcd.print ("Current T:");
lcd.print(temperature, 1);
lcd.setCursor (1,1); lcd.print ("ON:"); lcd.print(heater_on_temp, 0);
lcd.setCursor (7,1); lcd.print (" OFF:"); lcd.print(heater_off_temp, 0);
}
//==================================================================================================
void loop() {
button_pls.scanState();
button_mns.scanState();
button_ok.scanState();
if (button_pls.push == true) {counter = counter + 1;};
if (button_mns.push == true) {counter = counter - 1;};
if (button_ok.push == true) {counter = 0;};
lcd.setCursor (0,1);
lcd.print (counter); lcd.print (" ");
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
sensors.requestTemperatures();
// Temperature in Celsius degrees
temperature = sensors.getTempCByIndex(0);
lcd.clear ();
lcd.print ("Current T: "); lcd.print (temperature);
//lcd.setCursor (1,1); lcd.print ("ON:"); lcd.print(heater_on_temp, 0);
//lcd.setCursor (7,1); lcd.print (" OFF:"); lcd.print(heater_off_temp, 0);
lcd.setCursor (0,1);
lcd.print (counter);
lastTemperature = String(temperature);
// Check if temperature is above threshold and if it needs to trigger output
if(temperature <= T_ON_Message.toFloat()){
heater_state = true;
heater_state_str = "ON";
digitalWrite(rele_pin, HIGH);
};
// Check if temperature is below threshold and if it needs to trigger output
if((temperature > T_OFF_Message.toFloat())) {
heater_state = false;
heater_state_str = "OFF";
digitalWrite(rele_pin, LOW);
}
if (heater_state==true) {lcd.setCursor (15,1); lcd.print ("h");} else {lcd.setCursor (7,1); lcd.print (" ");};
}
}
[/spoiler]
Спасибо за внимание

П.С. Омайгадебля, я научился использовать спойлеры вместо безумных простыней кода

- Dryundel
- Полковник
- Сообщения: 2405
- Зарегистрирован: 22 май 2017, 23:15
- Откуда: Ярославль
- Имя: Андрей
- Поблагодарили: 15 раз
Почему не работает кнопка
Начнем с того, что с пинами на NodeMCU не все так однозначно. Некоторые из них подтянуты на плате внешними резисторами. К примеру пин D8 который Вы пытаетесь пуллапить в коде, на плате имеет подтяжку на землю, которая сильней внутренней. Соответственно так работать не будет. Попробуйте убрать с него PULLUP и замыкать на VCC. Должно сработать.
И так надо разбираться с каждым пином.
Почему не работает кнопка
Да, тысячу раз согласен, что с пинами там цирк с конями
На счет D8 - Вы правы, так и есть. Но в свою защиту скажу, что пробовал закомментировать эту ногу вообще, т.е. использовать две оставшиеся кнопки - результат тоже никакой. А так же на другие ноги вешать эту бедную кнопку. Вообще изначально на этой ноге было реле, кторое тоже как-то хреновенько работало. Поэтому перевесил туда кнопку, что роли не сыграло. Попробую на VCC замыкать, как Вы рекомендуете, тем более, что была такая мысль. Просто я хотел схитрить и не добавлять внешние резисторы. Увы, хитрость не удалась. На паленость модуля не думаю, он у меня как совесть - лежит под подушкой, я им не пользуюсь 


- Dryundel
- Полковник
- Сообщения: 2405
- Зарегистрирован: 22 май 2017, 23:15
- Откуда: Ярославль
- Имя: Андрей
- Поблагодарили: 15 раз
Почему не работает кнопка
А вот это зря. С NodeMCU лучше отказаться от всех программных PULLUP-ов и вешать конкретные (физические) подтяжки, на землю на VCC и тестить по разному.
Вот вам одна напоминалка, может поможет. Отправлено спустя 4 минуты 5 секунд:
И не забывайте, некоторые подтяжки не дадут залить скетч, т.к. конкретные пины при заливке должны быть свободны от подтяжек при заливке.
У вас нет необходимых прав для просмотра вложений в этом сообщении.
Почему не работает кнопка
По этой-то напоминалке и проводил свои исследования
В общем, я склонен прислушаться к вашим добрым советам, навешаю внешних резисторов (на обе шины питания, в зависимости от ноги) и все это пусть ляжет на плечи программной обработки. Пользователю-то пофигу, куда там чего подтянуто, курам так вообще глубоко фиолетово
Спасибо за отклики 



Почему не работает кнопка
Может кому пригодится.
Прошло более 2х лет и вот работая с другими платами и проектами вдруг вспомнил про данную тему и проблему.
И теперь немного нахватавшись знаний и поигравши с ПИНами различными контроллерами, могу дополнить данную тему победой.
Смысл данной задумки был в следующем:
На даче -
1. измерять темп. воздуха на улице
2. управлять прожектором на въезде при помощи Блинк.
3. максимально просто и дёшево.
Собрал из Китайской реле с ЕСПшкой в распред коробке, припаял 18В20 и изначально когда не получилось с кнопкой был проходной выключатель. Прилабонил на уличный столб.
Теперь всё работает и даже передаю темп. в Народный мониторинг.
Как победил и где были затыки:
1. кнопку вешать только на IO3 с подтяжкой к земле (тогда при перезагрузке контроллер не зависает)
2. перед заливкой в Arduino IDE удаляем строку Serial.begin(115200);
3. в Инструментах Debug port: "Disabled"
4. не забываем про новый сервер Blynk, добавляем (, "blynk.tk", 8080)
ВСЁ! Всем спасибо кто принимал участие.
Прошло более 2х лет и вот работая с другими платами и проектами вдруг вспомнил про данную тему и проблему.
И теперь немного нахватавшись знаний и поигравши с ПИНами различными контроллерами, могу дополнить данную тему победой.
Смысл данной задумки был в следующем:
На даче -
1. измерять темп. воздуха на улице
2. управлять прожектором на въезде при помощи Блинк.
3. максимально просто и дёшево.
Собрал из Китайской реле с ЕСПшкой в распред коробке, припаял 18В20 и изначально когда не получилось с кнопкой был проходной выключатель. Прилабонил на уличный столб.
Теперь всё работает и даже передаю темп. в Народный мониторинг.
Как победил и где были затыки:
1. кнопку вешать только на IO3 с подтяжкой к земле (тогда при перезагрузке контроллер не зависает)
2. перед заливкой в Arduino IDE удаляем строку Serial.begin(115200);
3. в Инструментах Debug port: "Disabled"
4. не забываем про новый сервер Blynk, добавляем (, "blynk.tk", 8080)
ВСЁ! Всем спасибо кто принимал участие.
У вас нет необходимых прав для просмотра вложений в этом сообщении.
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и 2 гостя