Skip to main content

IoT Home Automation | Garage door proximity sensor

In the last post I added the extra functionality that would allow me to know when was the last time when the device was online and last time when a command was received by the device. Additional to this I added also a state of each device, even if I was not collecting the device state.
Now, it is the moment to add the state functionality to the garage doors (open/close)

Context
The current system is simple, allowing us to trigger the garage door action, without being able to know if we close or open the door. This might create confusion especially when you control the doors from remote controls too.
By adding state functionality to the system, we would be able to know if the doors are open or close. On top of this we could also add actions like open/close the doors and the system could decide if the door is open or not and to close it.

Limitations
The Beninca system that I have on the garage doors is not able to provide to us the doors state. It is just a simple door mechanism that is only able to trigger the doors move. To overcome this limitation, we need to add a physical mechanism that can detect if the doors is open or not.

Physical solution

I decided to buy two proximity sensors that are part of “LJ12A3” family. More exactly LJ12A3 4 ZBX, that are cheap and can detect metal that is as far as 4 mm. In comparison with classical mechanical sensors (push buttons), it is more easily to mount and does not require direct contact.
I also avoided making any holes in the metal frame of the doors. To be able to mount the proximity sensor I used some magnets that I had from an old HDDs. They work grate to fix the sensor to the metal frame. Using this approach, I have the flexibility to move the sensor in any position I want, based on my needs.
I was pretty luck that the cable that is between engine doors and Beninca box had three wires that were free. I used them to connect the proximity sensor to the ESP8266.

Backend Implantation 
There were not too many things to change on the backend system. On the UI, I had to add the Open and Close buttons that would send over Azure Service Bus a message to the gateway.
On the gateway until now, I would return 200 HTTP code for no action and 201 code when the gate needs to move. On top of this, I added two additional codes 202 and 203.

  • 200 – No action is required
  • 201 – Move the door
  • 202 – Close the door
  • 203 – Open the door

For Open and Close actions I also added logic on the ESP8266 to take into account the current state of the door. When the device is checking for new commands, it is also providing us the current door state, that it is used on the UI.


ESP8266 Implementation
Logic become a little more complex, so I decided to extract two functions that would help me to trigger the gate move and another one that based on the HTTP code returned from the backend the right action is executed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void actionOnGate(int httpCode, int gateNumber, int gateState)
{
  // 201 Move
  if (httpCode == 201) {    
  Serial.println("201 - Gate move");  
    triggerGate(gateNumber);   
  }
  // 202 Close
  if ((httpCode == 202) && (gateState == 1) )
  {
    Serial.println("202 && gate Open - Gate move");  
  triggerGate(gateNumber);  
  }
  
  // 203 Open
  if ((httpCode == 203) && (gateState == 2) )
  {
  Serial.println("203 && gate Close - Gate move");  
  triggerGate(gateNumber);  
  } 
}

void triggerGate(int gateNumber){
  Serial.println("Open Relay"); 
  digitalWrite(D(gateNumber), HIGH);    
    delay(2000);
    Serial.println("Close Relay");
  digitalWrite(D(gateNumber), LOW);    
}
You can read data from proximity sensor using the analog or digital input. Initially I tried to use analog input, but the results were not the one that I expected. On the analog sensor, you can read the weight of metal that sensor detects, but in my case, I only need if metal is detected or not.
Using the digital input, there will be only two values that you would receive from the proximity sensor (0 or 1). 0 is returned when the sensor detects something in front of it and 1 when there is nothing in front of it.
On the backend system, I used value 0 when there is no state, 1 when the door is open and 2 when door is close. To match the same values on the device and to avoid confusions I added 1 to the value that was read from the proximity sensor.

1
2
3
4
5
6
7
8
9
Arduino
// Read gate state (1-Open | 2-Close from sensor)
  int gate1State = 1 + digitalRead(D2);
  int gate2State = 1 + digitalRead(D4);

Backend
// Read gate state (1-Open | 2-Close from sensor)
  int gate1State = 1 + digitalRead(D2);
  int gate2State = 1 + digitalRead(D4);
This state is reported directly to the gateway when the device checks for new commands, using the Status parameter. Using the sensor state and the HTTP code that is returned from the gateway, the device can decide to trigger an action or not. For example, it does not make sense to trigger the close action if the door is already close.
The full Arduino code can be found at the end of the post.

Tips and tricks
Wiring
When I made the physical connections, I did not had the same colors on all cables. Because of this when I made the final connection on the ESP8266 I have done some wrong connections and I ended up with close gate all the time. Don't forget to make notes on the paper, otherwise you might lose like mie 2h with it.

Digital vs analog read
Even if the analog read would provide more fidelity, I did not need this kind of level of details. Addition to this the risk for false positives errors would increase. Reading data from the sensor using the digital input it is just what I need.

Backward compatibility
The yard doors are still using the old implementation and are not able to provide their state. To avoid any updates on the device I still expose on the gateway the old API that is only able to push the command to the device.

ESP8266 implementation bug
During the final test, I notified that when I move the door 1, after a few seconds door number two starts to move. Initially I thought that there is some wire that is not connected on the right location. After 30 minutes when I re-weld all the cables on the board, I realized that the issue was not hardware.
It was a copy/paste bug in my code. On the line of code where I call the function that moves the gate 2, I provided the http code returned for gate number 1 not 2. Yes, I know that a lot of refactoring can be done on the code, but the main purpose is to have fun on the automation, not on the code (yet - smile)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
HTTPClient http2;
  String url2 = URLROOT"?Id=2&Status=";
  url2 = url2 + gate2State;
  Serial.println(url2);
  http2.begin(url2);
  http2.setTimeout(3000);
  int httpCode2 = http2.GET();
  Serial.println("HTTP Code for gate 2:");
  Serial.println(httpCode2);
  // old code: actionOnGate(httpCode,2,gate2State);
  actionOnGate(httpCode2,2,gate2State);

What next?
I plan to look on the current system that I have on the yard gates to see if it is possible to get the door state.

 Arduino Code
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#ifdef ESP8266
extern "C" {
#include "user_interface.h"
}
#endif

#define SSID "SSID"
#define PASSWORD "PASSWORD"
#define URLROOT "https://lola"

void setup() {
  pinMode(D3, OUTPUT);
  pinMode(D1, OUTPUT);
    
  //this is required to read ADC values reliably
  wifi_set_sleep_type(NONE_SLEEP_T);
  
  Serial.begin(57600); 
  
  // delay is required only for debugging
  delay(2000);
  Serial.println("Setup complete");
  
  WiFi.mode(WIFI_STA);
}
void loop() {
  int retries = 0;
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Not connected to the WiFi.");
    WiFi.begin(SSID, PASSWORD);
    Serial.println("after wifi begin");
    
    while ( retries < 30 ) {
      Serial.println("loop");
      if (WiFi.status() == WL_CONNECTED) {
        break;
      }
      delay(1000);
      retries++;
    }
    Serial.println("Exiting loop() for another wifi try.");
    return;
  }
  else {
    Serial.println("Connected to WIFI!");
  }    
  
  Serial.println(WiFi.localIP());
  
  // Read gate state (1-Open | 2-Close from sensor)
  int gate1State = 1 + digitalRead(D2);
  int gate2State = 1 + digitalRead(D4);
  Serial.println("Gate state: 1-Open | 2-Close");
  Serial.print("Gate 1 state:");
  Serial.println(gate1State);
  Serial.print("Gate 2 state:");
  Serial.println(gate2State);
  HTTPClient http;
  String url = URLROOT"?DeviceId=1&CurrentStatus=";
  url = url + gate1State;
  Serial.println(url);
  http.begin(url);
  http.setTimeout(3000);
  int httpCode = http.GET();
  Serial.println("HTTP Code for gate 1:");
  Serial.println(httpCode);
  actionOnGate(httpCode,1,gate1State);

  HTTPClient http2;
  String url2 = URLROOT"?DeviceId=2&CurrentStatus=";
  url2 = url2 + gate2State;
  Serial.println(url2);
  http2.begin(url2);
  http2.setTimeout(3000);
  int httpCode2 = http2.GET();
  Serial.println("HTTP Code for gate 2:");
  Serial.println(httpCode2);
  actionOnGate(httpCode2,2,gate2State);
    
  delay(2000);
}

void actionOnGate(int httpCode, int gateNumber, int gateState)
{
  // 201 Move
  if (httpCode == 201) {    
  Serial.println("201 - Gate move");  
    triggerGate(gateNumber);   
  }
  // 202 Close
  if ((httpCode == 202) && (gateState == 1) )
  {
    Serial.println("202 && gate Open - Gate move");  
  triggerGate(gateNumber);  
  }
  
  // 203 Open
  if ((httpCode == 203) && (gateState == 2) )
  {
  Serial.println("203 && gate Close - Gate move");  
  triggerGate(gateNumber);  
  } 
}

void triggerGate(int gateNumber){
  Serial.println("Open Relay"); 
  digitalWrite(D(gateNumber), HIGH);    
    delay(2000);
    Serial.println("Close Relay");
  digitalWrite(D(gateNumber), LOW);    
}

uint8_t D(uint8_t index) {
  switch (index) {
    case 1: return D1;
    case 2: return D3;
  }
}

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP