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


Tuesday, March 8, 2011

How to Erase & Reset the Netduino Plus

This post is a step by step guide to resetting your Netduino plus in case it becomes unresponsive. Is your Netduino plus not responding? Can't deploy a project to the Netduino plus? Can't Debug your project on the Netduino plus? Tonight I tried to run someone's sample project and it caused mine to hang. The White LED and the Blue LED stayed lit and it became completely unresponsive.  Rebooting it did not help, nor could I deploy another project to it to try and fix it. This is how to reset the Netduino plus.
  1. Unplug the Netduino plus from the computer (and an external power supply).
  2. Start MFDeploy.exe Start > Programs > .Net Micro Framework 4.1 > Tools
  3. Change "Device" to "USB". The actual device (pull down will be blank)
  4. Hold down the pushbutton on theNetduino plus (don't let go)
  5. Without letting go of the push button, plug the Netduino plus into the computer
  6. Within 5 seconds... press "Ping" and you should see "Pinging.... TinyBooter". If it says TinyCLR you did not complete everything quick enough so you need to start over.
  7. Quickly press "Erase". Press "OK" to continue. This will erase the Netduino application ONLY. The Netduino plus firmware will not be affected by this procedure.
  8. You should see a dialog box (picture above) "Erasing Deployment Status"
  9. When the dialog box disappears and it has completed the erasing procedure, you can disconnect and reconnect the Netduino plus
  10. You should now be able to deploy another application to the Netduino plus.
If this procedure fails to recover your Netduino plus, you may have to take the drastic measure of erasing and reflashing the firmware.






Saturday, March 5, 2011

Netduino Plus Web Server Hello World


This tutorial will show you how to create a simple Netduino plus web server. The Netduino plus will respond with "Hello World" when we make a HTTP request over it's Ethernet port. This is a step by step how to with all of the code for the project available for download at the end of this post.
  • Let's start by creating a new project. Name it "WebserverHelloWorld"
  • Right click on project name and choose to "Add" > "Add new item"
  • Add new "Class" and name is "WebServer.cs"
  • Here is a very simple version of a web server. It will listen for requests and respond with "Hello World". It will also blink the on-board LED when a web request comes into the Netduino plus.
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);
        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));
                        Debug.Print(request);
                        //Compose a response
                        string response = "Hello World";
                        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);
                        //Blink the onboard LED
                        led.Write(true);
                        Thread.Sleep(150);
                        led.Write(false);
                    }
                }
            }
        }
        #region IDisposable Members
        ~WebServer()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (socket != null)
                socket.Close();
        }
        #endregion
    }
  • Now add the following code to Program.cs.
public static void Main()
        {
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
            WebServer webServer = new WebServer();
            webServer.ListenForRequest();
        }

  • Make your program run on the Netduino and not the emulator by right clicking on your project > "Properties"
  • Select the ".Net Micro Framework" tab and change the following settings.
    • Transport: USB
    • Device: NetduinoPlus_NetduinoPlus
  • Now run the program by pressing F5 or "Debug" > "Start Debugging".
  • In the "Output" the program will write the Netduino plus IP address. If you don't have the "Output" window open, select "View" > "Output" to open it.
  • Now open a web browser and type the Netduino plus IP in the address bar.
  • You should receive back "Hello World" from the Netduino plus.
Here is a video demo of the web server running on the Netduino plus.
Here is the complete source code.

Thursday, March 3, 2011

Simple Netduino plus example

Time for your first Netduino plus project. Let's build a very basic example to make sure everything is working correctly. If you have not installed all the software yet, see my previous blog post on how to setup your development environment.
  • Launch Visual Studio
  • Choose to create a new project
    • Select "Netduino Plus Application" and name the project "NetduinoPlusSimpleExample".
    • Enter the following code in the Main method
      • On line #3 we declare the on-board LED as an output port. The second parameter we set the default value to "false" (low or off).
      • Then we create an infinite loop.
      • Inside the loop on line #6 we write to the on-board LED true (high or on).
      • Line #7 we pause the application for one second
      • Then we turn off the LED for one second.
      • This loop will continue until you reset the Netduino plus or upload another program.
    public static void Main()
            {
                OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
                while (true)
                {
                    led.Write(true);
                    Thread.Sleep(1000);
                    led.Write(false);
                    Thread.Sleep(1000);
                }
            }
    


    • Now that we have the program written we are going to upload it to the Netduino. Attach a mini-USB cable to the Netduino plus and plug into a USB port. If you receive a driver error you must confirm or re-install the Netduino drivers.
    • Now we need to tell Visual Studio to run the program on the Netduino plus board and not the emulator. I have not found the emulator to be very useful as it does not display any outputs.
    • Right click on your project "NetduinoPlusSimpleExample" > "Properties"
    • Select the ".Net Micro Framework" tab and change the following settings.
      • Transport: USB
      • Device: NetduinoPlus_NetduinoPlus
    • Save your changes
    • Let's run the program. Select "Debug" > "Run" or F5
    • Here is a video of the program running on my Netduino plus

    • Download the complete project

    Tuesday, February 22, 2011

    How to Setup Netduino Plus Development Environment


    To get started with Netduino plus development install the following software. I would recommend you install everything in this order.
    1.  Microsoft Visual C# Express 2010 (get it FREE here)
    2. .NET Micro Framework  (get it FREE here)
    3. Netduino SDK (Free download)
      Download 32-bit Netduino SDK v4.1.0
      Download 64-bit Netduino SDK v4.1.0
    Now that you have all the software installed, let's test that everything is working. The drivers for your Netduino plus should have already been installed with the Netduino SDK. If they don't seem to be working you can download the drivers from the Netduino website

    You are ready for your first Netduino plus project.