Ok so I .have asked this a few times in different ways but have yet to get a response. I used your code to produce a door sensor that i was hoping to use on my remote shed to let me know if the door was left open or not. Your code was the perfect answer to what i wanted to do. I have posted the code here , I have not shared my credentials on it but be assured that they are in the code when i download to the 8266.
So what is happening is if I use the magnetic contacts and the contact’s are closed i do indeed get a message that the door is open but then immediately after within seconds it responds with door is closed. If I open the door I get the exact same message door is open then closed. Not sure why this is happening and was looking for a answer, ,its almost like it would need a de bounce circuit ,but there is none on this program. Can you please tell me what I need to do to resolve this?
Start your code here
/* Rui Santos Complete project details at https://RandomNerdTutorials.com/telegram-control-esp32-esp8266-nodemcu-outputs/ Project created using Brian Lough's Universal Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot Example based on the Universal Arduino Telegram Bot Library: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/blob/master/examples/ESP8266/FlashLED/FlashLED.ino */ #ifdef ESP32 #include <WiFi.h> #else #include <ESP8266WiFi.h> #endif #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot #include <ArduinoJson.h> // Replace with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Initialize Telegram BOT #define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // your Bot Token (Get from Botfather) // Use @myidbot to find out the chat ID of an individual or a group // Also note that you need to click "start" on a bot before it can // message you #define CHAT_ID "XXXXXXXXXX" #ifdef ESP8266 X509List cert(TELEGRAM_CERTIFICATE_ROOT); #endif WiFiClientSecure client; UniversalTelegramBot bot(BOTtoken, client); // Checks for new messages every 1 second. int botRequestDelay = 1000; unsigned long lastTimeBotRan; const int ledPin = 2; bool ledState = LOW; // Handle what happens when you receive new messages void handleNewMessages(int numNewMessages) { Serial.println("handleNewMessages"); Serial.println(String(numNewMessages)); for (int i=0; i<numNewMessages; i++) { // Chat id of the requester String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Unauthorized user", ""); continue; } // Print the received message String text = bot.messages[i].text; Serial.println(text); String from_name = bot.messages[i].from_name; if (text == "/start") { String welcome = "Welcome, " + from_name + ".\n"; welcome += "Use the following commands to control your outputs.\n\n"; welcome += "/led_on to turn GPIO ON \n"; welcome += "/led_off to turn GPIO OFF \n"; welcome += "/state to request current GPIO state \n"; bot.sendMessage(chat_id, welcome, ""); } if (text == "/led_on") { bot.sendMessage(chat_id, "LED state set to ON", ""); ledState = HIGH; digitalWrite(ledPin, ledState); } if (text == "/led_off") { bot.sendMessage(chat_id, "LED state set to OFF", ""); ledState = LOW; digitalWrite(ledPin, ledState); } if (text == "/state") { if (digitalRead(ledPin)){ bot.sendMessage(chat_id, "LED is ON", ""); } else{ bot.sendMessage(chat_id, "LED is OFF", ""); } } } } void setup() { Serial.begin(115200); #ifdef ESP8266 configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org #endif pinMode(ledPin, OUTPUT); digitalWrite(ledPin, ledState); // Connect to Wi-Fi WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); #ifdef ESP32 client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org #endif while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); } void loop() { if (millis() > lastTimeBotRan + botRequestDelay) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); while(numNewMessages) { Serial.println("got response"); handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } lastTimeBotRan = millis(); } }
Hi Larry.
I don’t think the code you posted is the correct one.
Can you double-check what is the code that you are referring to?
Regards,
Sara
This is what I put on my esp8266 , i may haver posted the wrong one when I was trying to cut and paste the code for the question. This is the code currently loaded on the device, between G and D2 I have a 10K resistor, also I have a jumper between the 3.3v and junction of the 10k to D2 to simulate a contact.
So to reiterate , If I remove the jumper I get on the telegram door is open 11:47 am and door is closed at 11:47am. If I connect the jumper I get door is open at 11:48am and and door is closed at 11:48am,thanks
Start your code here
/*
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-door-status-telegram/
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.
*/
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// Set GPIOs for LED and reedswitch
const int reedSwitch = 4;
const int led = 2; //optional
// Detects whenever the door changed state
bool changeState = false;
// Holds reedswitch state (1=opened, 0=close)
bool state;
String doorState;
// Auxiliary variables (it will only detect changes that are 1500 milliseconds apart)
unsigned long previousMillis = 0;
const long interval = 1500;
const char* ssid = “xxxxxxxxx”;
const char* password = “xxxxxxxxxxxx”;
// Initialize Telegram BOT
#define BOTtoken “xxxxxxxxxxxxxxxxxxxxxxxxxxxx” // your Bot Token (Get from Botfather)
// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click “start” on a bot before it can
// message you
#define CHAT_ID “xxxxxxxxxxxx”
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
// Runs whenever the reedswitch changes state
ICACHE_RAM_ATTR void changeDoorStatus() {
Serial.println(“State changed”);
changeState = true;
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
configTime(0, 0, “pool.ntp.org”); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
// Read the current door state
pinMode(reedSwitch, INPUT_PULLUP);
state = digitalRead(reedSwitch);
// Set LED state to match door state
pinMode(led, OUTPUT);
digitalWrite(led, state);
// Set the reedswitch pin as interrupt, assign interrupt function and set CHANGE mode
attachInterrupt(digitalPinToInterrupt(reedSwitch), changeDoorStatus, CHANGE);
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);
bot.sendMessage(CHAT_ID, “Bot started up”, “”);
}
void loop() {
if (changeState){
unsigned long currentMillis = millis();
if(currentMillis – previousMillis >= interval) {
previousMillis = currentMillis;
// If a state has occured, invert the current door state
state = !state;
if(state) {
doorState = “closed”;
}
else{
doorState = “open”;
}
digitalWrite(led, state);
changeState = false;
Serial.println(state);
Serial.println(doorState);
//Send notification
bot.sendMessage(CHAT_ID, “The door is ” + doorState, “”);
}
}
}
Hi.
Can you increase the value of the interval variable to check if that makes any difference?
For example:
const long interval = 2000;
Regards,
Sara
Thanks, I will try that , kept thinking it was a bounce so by changing that value could work.
Sara;
Tried changing value from 1500 to 2000, no change to the way it reports status.
Hi.
One of our readers mentioned the following in that project:
“From that moment it started to work but the switch generated many bounces. I modified the “delay” but little change. So I added a 2.2 microfarad capacitor parallel to the switch and now it’s OK.”
Tomorrow I can try to test that project again and try to understand what might be wrong with your setup.
Regards,
Sara
didn’t have a 2.2 cap so I paralleled 2 1uf caps and added this to the circuit across the resistor so resistor and 2 caps are in parallel. Still getting the same results, am I connecting this wrong?
Hi.
I just tested the project again to be sure it was working as expected.
Everything worked fine by following the tutorial as it is.
Maybe your sensor is different than mine?
I’m not sure what might be wrong on your side.
Regards,
Sara
Ok thanks, stumped here , using the right ESP Board ESP -12E . Just using a jumper wire to simulate a contact so that should work. Thanks for trying, just thought that something it off because I have read others had similar issues.
Hi.
You mentioned the jumper wire.
I tested right now with a jumper wire and everything works as expected too.
Have you tried using another GPIO?
Regards,
Sara
For some reason after I went from D2 to D3 , downloaded the program and it does indeed work. Curiosity got me so I went back to original sketch after powering down , and it now works. Don’t quite understand it , maybe after power cycling it , it reset and now works as you said. Possibly it didn’t download correctly , something I really should have tried. Also found an electrolytic 2.2 cap and paralleled to the 10K resistor , all is working now,thanks again.
I also tried this on a Model Doiting ESP -12F and it works just fine . Thanks again for all the help Sara
Great!
I’m glad you solved the issue.
I’ll mark this issue as resolved.
If you need further help, you just need to open a new question in our forum.
Regards,
Sara