Door sensors with WiFi

So I am attempting to create a door circuit that will notify me if one of my doors are open . I would like it to send notifications upon state changes ie: door was opened but if it is closed it should report door closed.

I would also like this to work on battery using a battery pack and a Wemos d1 mini. I want it only to report a door left open so as to not have the Wemos send a million messages and kill the battery .

2 Likes

Hi Larry,

If you remove the ``` from the start and end of your topic it will make it much easier to read

What parts have you got so far? And are you in a rental (they usually don’t like you attaching stuff to the walls etc.

I’d take a look into using IFTTT! There are plenty of tutorials around for using it with an ESP based module.

2 Likes
 First off, I don’t see the ‘’’ so I don’t know how that is in the message. 
 What I have to work with is Wemos d1 and am using Arduino IDE to program. 
 I don’t live in a rental, so that isn’t a problem. I have a program written using reedSwitch and reedSwitch1 . Tried using case: 0 , case: 1 , pull-up resistors in sketch. Can’t get the switches to respond independently. Not a programmer but attempting to learn so that’s the reason for the program. Thanks 

Hopefully there won’t be the 3 ticks in this one.

3 Likes

Hi @Larry197870, our forum uses markdown styling; it seems that 4+ spaces has a similar effect as the 3x back quotes. I removed the spaces on your first post and it appeared normal after that :slight_smile:

3 Likes

Thanks Graham, don’t know where or how those spaces got in my post. I wonder if it is because I indent when I posted the message.
I usually indent to make things easier to follow or make it more readable. I personally don’t want to read one long post it it isn’t broken down into sections. Thanks

3 Likes

Hi Larry,

Sounds like an awesome project!!

It sounds like you have the brains of the project figured out. To handle the sensing of the system I’d use a switch like this: Magnetic Door Switch Set | Sparkfun COM-13247 | Core Electronics Australia

It’s based on a reed switch so works on a binary signal - which in turn can trigger what’s called an interrupt(with a rising and falling edge condition).

For tips on programming it in, I’d take a look at Core’s tutorial on programming in Arduino: https://core-electronics.com.au/courses/arduino-workshop-for-beginners/
Note there are changes to functions between different MCUs.

Would it be possible to paste your code in?
There are a couple of ways to handle the logic, if you’re graphically oriented I’d use a truth table to draw out what you want your program to do.

To get the most battery life definitely make use of the deep sleep modes available for low power usage, (depending on the MCU certain pins can wake the board upon receiving a signal).

The notifications are a bit harder - I’d check out Adafruit.io!

Liam

2 Likes

So I pretty much got it working but run into a problem monitoring the digital switches independently . With door switch (on bread board using jumper) made , door 1 is closed , and door 2 jumped shows door2 open . If I remove the jumper on door 2 , still shows door 2 open. I know it is not seeing or correctly monitoring the second door. I have tried several methods but my programming skills are severely lacking. Code is a snippet of code found created by others.

#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>

// Set GPIOs for LED and reedswitch
const int reedSwitch = 4;
const int reedSwitch2 = 5;
const int led = 2; //optional

// Detects whenever the door changed state
bool changeState = false;

// Holds reedswitch state (1=opened, 0=close)
bool state;
bool state2;
String doorState;
String doorState2;

// Auxiliary variables (it will only detect changes that are 1500 milliseconds apart)
unsigned long previousMillis = 0;
const long interval = 1500;

const char* ssid = "*****";
const char* password = "************";

// Initialize Telegram BOT
#define BOTtoken "********:************"   // 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 "**********"

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);
  pinMode(reedSwitch2, INPUT_PULLUP);
  state = digitalRead(reedSwitch);
  state2 = digitalRead(reedSwitch2);
  //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);
  attachInterrupt(digitalPinToInterrupt(reedSwitch2), 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;
      state2 = !state2;
      if (state    ) {
        doorState = "Door 1 closed";
      
      }
      else {
        doorState = "Door 1 open";
       
      }

      if (state2 ) {
        doorState2 = "Door 2 closed";
      }
      else {
        doorState2 = "Door 2 open";
      }
      digitalWrite(led, !state);
      changeState = false;
      Serial.println(state);
      Serial.println(state2);
      Serial.println(doorState);
      Serial.println(doorState2);


      //Send notification
      bot.sendMessage(CHAT_ID, "The door is " + doorState, "");
    }
  }
}
3 Likes

Hi Larry,

Without everything setup infront of me its a little hard understand what exactly might be happening. Were you able to get this working with just one of the sensors?
The interupt seems to be setup correctly (based on the Arduino reference).

Liam

2 Likes

Yes I can get one working but as soon as I put the second one in it doesn’t work. So I also moved the the inputs to different pins from D1 to D3 and so on and it didn’t make any difference in the way it worked. Thinking about abandoning it I could just use 2 separate boards and get what I want but that’s just silly :joy:

2 Likes

Can you get both of them working without the other, or is there only one that works on its own, and one that doesn’t work at all, and stops the other one from working?

A diagram of the wiring from the switches to the controller would reveal if there are any issues with the way it is connected up.

2 Likes

How do I send a diagram on this site to show the way it is wired? Actually pretty simple, using a 10 k resistor for each input where the resistor is tied to ground and 3.3 to the open side of the switch.

1 Like

So either switch works on its own, but it doesn’t work when both are connected. Is that what happens? When you have one switch working, can you connect it to either D1 or D3 and it works in both cases?

I would recommend writing a simple test program than confirmed that each switch is changing state as it switches, without interrupts or any logic to work out what that means for the doors. Once you know that they are connected and switching correctly, modify that program to confirm that they behave the same when both are connected. As you only have one LED available, use console output to display the state of both switches If that proves that the wiring is OK, then the problem will be in the logic of the code.

Also, it’s not clear how your switch condition relates to the door position. Does the switch close and then open as the door swings past it, or is the switch closed when the door is closed and open when the door is open (or vice versa), or are they each arranged differently?

1 Like

So if I wire one switch at a time the Serial monitor sees the switch change state independent of each. I write Door1 open, door 1 close for each switch and they respond that way as well.

The onboard led just showing the switch activity, when the door is shut the led will be off and the switch will be made, seeing how the door would be closed more than open and saving power consumption. Currently I am using on board led but may or may not use any when this circuit and code is proven out.

I believe it’s the way the code is written is the problem, not sure about how to write in the code that the condition changes ( rising edge) and keep track of it . Attached interrupts , state code, bool. Am I supposed to use each one of those codes for each switch like bool and boll1 . If I use only 1 switch weather it be mechanical or magnetic it works fine , soon as I duplicate code fit second switch I have the problem.

I used internal pull-up in code as well as a 10k resistor on the switch. Have you seen the code as written? Many thanks for looking at this project for me , I know I could make it work with 2 ESP 8266 but that seems like a waste of a board with the option to use more GPIOs .

1 Like

The code is written to detect changes in the switches, not whether the switches are open or closed. You can do it this way, but it is more complicated than is needed.

To simply know whether the doors are open or closed you don’t need interrupts. The code can simply read each input as open or closed, and compare it to what it previously thought the state of the switch was. If it’s the same, then do nothing - just end the loop.

But if the current state of the switch is not what was previously recorded for it, then you need to send the notification, and then record the new state of the switch. You can choose to send the notification for open to close, close to open, or both.

Duplicate that logic for the other switch, being careful to record the previous state of the door in a separate variable for each.

A small delay at the end of each loop will protect against multiple notifications for each opening or closing. The fact that the loop runs continuously and is checking the switches many thousands of times per second doesn’t matter - it hasn’t got anything else that it needs to be doing…

2 Likes

Thanks, not sure I know how to do that but will try when I get back in town, thanks again.

2 Likes

It looks to me as though you interrupt on either switch changing state and then invert BOTH state variables.

But this is way over complex for such a simple task I think.

I haven’t written any Arduino code for years so cut me some slack, but I think this is about all you need.

void loop() {
	
		current_state1 = digitalRead(reedSwitch1);
		if (current_state1 != state1) {
			current_state1 = state1;
			Serial.println ("Door 1 ");
			Serial.println (state1 ? "closed" : "open");
		}

		current_state2 = digitalRead(reedSwitch2);
		if (current_state2 != state2) {
			current_state2 = state2;
			Serial.println ("Door 2 ");
			Serial.println (state2 ? "closed" : "open");
		}
	}
	wait (interval);
}

Rob

2 Likes

Thanks I will try it , looking easier than what I was attempting. Will let you know.

2 Likes

Hi Larry

You can’t have it both ways. Either a 10k pulling the input to ground or “Pull Up” pulling the input to VCC but not both. Fix this and your problem might go away. Maybe, I have not attempted to digest your sketch but just noticed this.
Cheers Bob

1 Like

Ok thanks, I am not a programmer, just trying to learn and decided to make this work. I will try to read up on this more. Thanks again

1 Like

Hi Larry
Yes I have not looked at your sketch, only to check on that “PULL UP” entry. I picked up on your error when reading the text.
If you use the pull down resistors and switch to 3.3V to activate delete the PULL UP and just declare an INPUT.
If you use the PULL UP declaration you will have to switch the input LOW (or Ground) to activate.
You cannot do both.
As you have it you probably have the input sitting about 1V depending on the value of the internal pull up resistor. This would make the “LOW” state of the input a bit iffy and confuse the system no end.
I am not saying this will fix your problem but you will have to change it whatever you do.
Cheers Bob

1 Like