Sunday, September 18, 2011

Open & Close Garage Door with your Netduino plus

There are many ways to control your garage door with your Netduino. I decided to hack a spare garage door opener (since I wasn't using it) with an Optoisolator. My total cost $1.25. If I didn't have a spare garage door opener I would have run two wires off the Optoisolator pin 3 & 4 to the control panel in the garage. To send commands to the Netduino I am going to use HTTP commands.

Supplies

  • Garage door opener
  • Optoisolator with Darlington Driver - 1 Channel. I purchased mine from Sparkfun.
  • 100 ohm resistor
  • 33 ohm resistor
  • Netduino plus
1. Build it

Here is the schematic for interfacing with the garage door opener. Excuse my unsophisticated schematic as I don't own any electrical CAD software.

  • Connect the Optoisolator pin 1 (Anode) to the Netduino plus digital pin 13
  • Connect the Optoisolator pin 2 (Cathode) to a ground pin on the Netduino plus with a 33 ohm resistor in-line.
  • Connect the Optoisolator pin 3 (Emitter) to one side of the garage door opener push-button with a 100 ohm resistor in-line.
  • Connect the Optoisolator pin 4 (Collector) to the other side of the garge door opener push-button.
Here is mine all built. You may notice mine has is wired for two garages although I only have one hooked up to the Netduino for this tutorial.

2. Code it

For the code, I am going to start with a stubbed out web server code from my previous blog post. To get more information on the basic code for a web server see my previous blog post.
If you have not installed all the necessary software see my previous blog post on how to setup your Netduino Plus development environment here (How to Setup Netduino Plus Development Environment).

After you download the code, open the project. Let's modify the code so we can send an HTTP request to the Netduino to activate the garage door opener. We are going to send a command to push the button on the garage door opener. We don't know if we are opening it or closing it since we are not yet monitoring the garage door status. We will combine this project to activate the garage door with the monitor code in a later post. Then we will be able to send the specific command "Open" or "Close".

Make the following changes to code
  • Line 6: Initialize digital port 13 to talk to the garage door opener
  • Lines 38-48: Parse the http request and confirm the user requested to door be activated with the command "HTTP:/192.XXX.X.XXX/activatedoor"
  • Line 49: Call our method to activate the garage door opener.
  • Lines 51-55: Send HTTP response.
  • Lines 56-62: send a HTTP response - command not recognized.
  • Lines 68-75: activate garage door method
    • Line 70: light the on-board LED for visual confirmation command is being sent to garage door opener
    • Line 71: Send voltage to the digital pin 13 to close the push-button on the garage door opener
    • Line 72: Wait for 1 second
    • Line 73: Turn off on-board LED
    • Line 74: Stop voltage to pin 13


public class WebServer : IDisposable
    {
        private Socket socket = null;
        //open connection to onbaord led so we can blink it with every request
        private OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
        private OutputPort Garage2CarOpener = new OutputPort(Pins.GPIO_PIN_D13, false);

        public WebServer()
        {
            //Initialize Socket class
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Request and bind to an IP from DHCP server
            socket.Bind(new IPEndPoint(IPAddress.Any, 80));
            //Debug print our IP address
            Debug.Print(Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);
            //Start listen for web requests
            socket.Listen(10);
            ListenForRequest();
        }

        public void ListenForRequest()
        {
            while (true)
            {
                using (Socket clientSocket = socket.Accept())
                {
                    //Get clients IP
                    IPEndPoint clientIP = clientSocket.RemoteEndPoint as IPEndPoint;
                    EndPoint clientEndPoint = clientSocket.RemoteEndPoint;
                    //int byteCount = cSocket.Available;
                    int bytesReceived = clientSocket.Available;
                    if (bytesReceived > 0)
                    {
                        //Get request
                        byte[] buffer = new byte[bytesReceived];
                        int byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
                        string request = new string(Encoding.UTF8.GetChars(buffer));
                        string firstLine = request.Substring(0, request.IndexOf('\n')); //Example "GET /activatedoor HTTP/1.1"
                        string[] words = firstLine.Split(' ');  //Split line into words
                        string command = string.Empty;
                        if( words.Length > 2)
                        {
                            string method = words[0]; //First word should be GET
                            command = words[1].TrimStart('/'); //Second word is our command - remove the forward slash
                        }
                        switch (command.ToLower())
                        {
                            case "activatedoor":
                                ActivateGarageDoor();
                                //Compose a response
                                string response = "I just opened or closed the garage!";
                                string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                                clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                                clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
                                break;
                            default:
                                //Did not recognize command
                                response = "Bad command";
                                header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                                clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                                clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
                                break;
                        }
                    }
                }
            }
        }
        private void ActivateGarageDoor()
        {
            led.Write(true);                //Light on-board LED for visual cue
            Garage2CarOpener.Write(true);   //"Push" garage door button
            Thread.Sleep(1000);             //For 1 second
            led.Write(false);               //Turn off on-board LED
            Garage2CarOpener.Write(false);  //Turn off garage door button
        }
        #region IDisposable Members
        ~WebServer()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (socket != null)
                socket.Close();
        }
        #endregion
    }
Remember to make sure you are deploying to your Netduino board and not the emulator. You do that by right-clicking on the Netduino project in Visual Studio > properties > .Net Framework. Set "Transport" to USB and confirm "Device" is set to "Netduino Plus".

3. Run it


  • Now run the code in debug mode. 
  • Open another a web browser and enter the IP address that the Netdiuno board displayed in the output window. For me its "http://192.168.0.153/activatedoor"
  • You should see the LED on the Netduino plus light and the door should open or close.
Here is the complete code.



To learn how to write the Android app that will control and monitor the garage door read the step by step blog post here. http://androidcodemonkey.blogspot.com/2011/10/android-garage-door-app.html


Wednesday, September 14, 2011

Monitor if Your Garage Door is Open with Netduino Plus

This blog post is going to document how to build an infrared sensor to monitor your garage door. It is part of a series to build an Android garage door app.

Supplies

  • Netduino plus (if you don't already have one). There are many places you can buy one and they seem to charge about the same $59.95.
  • Optical Detector / Phototransistor $1.13. (I bought mine from Sparkfun)
  • 200 ohm resistor (under a buck from any almost anywhere)
  • 5.6K ohm resistor (under a buck from any almost anywhere)
  • (Optional) (2) Screw Terminals 3.5mm Pitch $1.25 ea.
  • (Optional) PC Board $2.19 for two.
1. Build it

Follow this schematic to build your garage door sensor.

 This is what mine looks like (I used the PC board and terminals to make mine a little more tidy).


And here is the sensor installed in the garage. I placed it on the side facing the side plate. When the door is open the sensor detects an object close.


2. Code it

If you have not installed all the necessary software see my previous blog post on how to setup your Netduino Plus development environment here (How to Setup Netduino Plus Development Environment).


Create a new project
Launch Visual Studio 2010 then create a new project (File > New Project > Netduino Plus Application). Let's name it NetduinoInfraredSensor.


Open Program.cs

  • Line 2 we define an AnalogInput and set it for PIN 0

  • Line 4 we set the range for reading the analog signal from 0 to 1024
  • Lines 6-10 are the main infinite loop. 
  • Line 8 we read the voltage through analog input 0 (which will return a value of 0 to 1024 which proportionally to the voltage coming from the infrared sensor we built and hooked up to analog input 0).
  • Line 9 we sleep the program for 1 second (so the program debug output is not flooding through the debug window). Be careful with loops that don't contain any Thread sleep commands. It is possible to for Visual Studio to have difficulty connecting and deploying if the loop is too tight. To be safe always throw in a sleep even if its just for a fraction of second.

//Set the analog pin to monitor Pin 0
AnalogInput garageSensor = new AnalogInput(Pins.GPIO_PIN_A0);
//Set sensor range
garageSensor.SetRange(0, 1024);
//Program loop
while (true)
{
    Debug.Print(garageSensor.Read().ToString());
    Thread.Sleep(1000);
}

3. Run it

First we need to change the project properties to deploy the program to the Netdiuno Plus and not an emulator (default). Right click on the project > properties > .Net Framework. Change the Transport to USB and make sure Netdiuno Plus is the device. (Your Netduino must attached to the computer via USB cable before making this change).
Now we can run the program in debug mode by pressing F5 or Debug > Start Debugging. Now hold an object about 3 inches from the infrared sensor and slowly move it towards the sensor. You will begin to see the reading drop from 1024.


Here is the complete code for the sensor.



To learn how to write the Android app that will control and monitor the garage door read the step by step blog post here. http://androidcodemonkey.blogspot.com/2011/10/android-garage-door-app.html

Android app to monitor & open and close garage door

Have you ever wanted to know if your garage door is open without having to go and check it? There have been many blog posts to light an LED when you leave your garage door open, but I want something more convenient. I decided to write an Android app that would allow me to monitor my garage door and even open or close from anywhere. I am going to provide complete instructions for building the required hardware and the android app code.

Monitor your garage door with an Android app
What is required? We need to build the following:
  • Using a Netduino board (or an Arduino board with an Ethernet shield) build a sensor to detect if the garage door is open or closed. I chose an infrared phototransistor so I would not have to make physical contact with the door and because it's cheap! Like $1.13 cheap! Read this to learn how to build and program it.
  • To open or close the garage door I wired an Optoisolator to a spare garage door opener. Complete step by step tutorial is available here. http://netduinohacking.blogspot.com/2011/09/open-close-garage-door-with-your.html
  • Write a program (or you might hear it referred to as a sketch) to check the sensor and determine if the door is open or close and report it back over HTTP
Open and close garage door with your Netduino



Links