Control Arduino from ASP.NET C# Web Application Interface

Hi Folks! Today I will be showing you how to create a web application capable of communicating with Arduino. Excited yet? No? Well, you should be.

All you need for this project is Microsoft Visual Studio, an Arduino board (my perticular model is the Uno Rev3, but I’m sure most models will work just fine), and some basic wire and LED components. I picked up an ARDX Starter Kit from SeeedStudio, which contained all the LEDs and wires I needed.

interface assembly
a screen of the app the final assembly

This was my first real venture into Arduino (not counting the mundane “make a blinking LED!” crap) and I have to admit it was a struggle at times. However, after a few hours on the Google Machine and some good ol’ fashioned brain power, I was able to overcome. After taking some time to enjoy the fruits of my labor, I have decided to share my project with you, my fellow citizen of the internet.

Because I feel pretty comfortable with .NET and C#, I chose to put those coding all of that on the back burner and start off configuring my Arduino. First you will need to install the Arduino software and its drivers for your PC. I’d show you how to do it, but there are probably 10000 posts existing on this topic already.

Using my breadboard, I configured the hardware portion of my project like so (excuse the terrible art):
wiring

And that does it for the hardware portion! Moving on to the programming…

Using the code below, we are going to tell the Arduino the pin locations of each of our LED’s including a power indicator LED that I added for shits and giggles. The next thing we do is set the baudrate for our serial connection as well as a delay value (optional).

After that, we begin our setup, in which we set set our pinModes, start our serial connection and turn on our power indicator LED.

Next is our loop, or in other words, what we want the Arduino to do. We start by putting an if statement to look  for a serial connection. This is important because we want to constantly be ready to receive an input. By putting that if clause, we don’t waste any time computing if there is nothing to process. Then, we read the input (if there is one) and complete actions based on its values. Perfect!

///set pin numbers for leds

//power indicator led
int pwr = 6;

//controlled leds
int blue = 12;
int green = 11;
int orange = 10;
int red = 9;

///set baudrate for serial connection
int baud = 9600;

///set delay time: 1 second
int time = 1000;

void setup()
{
  //set pinmode and turn on power led
  pinMode(pwr, OUTPUT);
  digitalWrite(pwr, HIGH);

  //start serial
  Serial.begin(baud);

  //set pinmode for controlled leds
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(orange, OUTPUT);
  pinMode(red, OUTPUT);
}

// the loop routine runs over and over and over and over
void loop()
//loop constantly scans for serial input
{
  //when connection is more than 1 begin if statements
  if (Serial.available() > 0)
  {
    //read serial input value
    int val = Serial.read();
    //begin if statement
    if (val == '1')
    {
      digitalWrite(blue, HIGH);
      delay(time);
      digitalWrite(blue, LOW);
    }
    if (val == '2')
    {
      digitalWrite(green, HIGH);
      delay(time);
      digitalWrite(green, LOW);
    }
    if (val == '3')
    {
      digitalWrite(orange, HIGH);
      delay(time);
      digitalWrite(orange, LOW);
    }
    if (val == '4')
    {
      digitalWrite(red, HIGH);
      delay(time);
      digitalWrite(red, LOW);
    }
    //flush the serial value
    Serial.flush();
  }
}

Ok, so that does it for our hardware. Our Arduino is configured and ready to receive inputs. Now, we move on to Visual Studio to create our web application. Lets start with our code behind. First, we need to make sure we load the proper assemblies. The serial port is our main mode of communication to our Arduino, so loading the System.IO.Ports assembly is critical.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO.Ports;
using System.Text;
using System.ComponentModel;
using System.Windows;

Next, we need to make sure that we define our COM port number and set our baudrate. Our web application is going to have 4 buttons to control the 4 LED colors on our Arduino, so we need to create event handlers to respond to each of those button clicks. It is important that we close the connection after each button click or else there will be communication errors.

namespace ArduinoTest
{
    public partial class LEDTest : System.Web.UI.Page
    {
        SerialPort ardo;

        protected void Page_Load(object sender, EventArgs e)
        {
            ardo = new SerialPort();
            ardo.PortName = "COM4";
            ardo.BaudRate = 9600;
        }

        protected void BlueOn(object sender, EventArgs e)
        {
            string blue = "1";
            ardo.Open();
            ardo.Write(blue);
            ardo.Close();
        }
        protected void GreenOn(object sender, EventArgs e)
        {
            string green = "2";
            ardo.Open();
            ardo.Write(green);
            ardo.Close();
        }

        protected void OrangeOn(object sender, EventArgs e)
        {
            string orange = "3";
            ardo.Open();
            ardo.Write(orange);
            ardo.Close();
        }
        protected void RedOn(object sender, EventArgs e)
        {
            string red = "4";
            ardo.Open();
            ardo.Write(red);
            ardo.Close();
        }
    }
}

Last but not least, all thats left is to create the HTML. We need to add 4 buttons and make sure we add the matching ‘OnClick’ event to each button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LEDTest.aspx.cs" Inherits="ArduinoTest.LEDTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>LED Web Control</title>
    <style type="text/css">
        .Panel
        {
            margin-left: 2%;
            margin-top: 2%;
            border-color: white;
            border-width: 20px;
        }
        .Header
        {
            font-family: "Segoe UI";
            font-size: xx-large;
            font-weight: normal;
            font-style: normal;
            font-variant: normal;
            text-transform: none;
            color: #000000;
        }
        .Sub
        {
            font-family: "Segoe UI";
            font-size: x-large;
            font-weight: normal;
            font-style: normal;
            font-variant: normal;
            text-transform: none;
            color: #666666;
        }
    </style>
</head>
<body bgcolor="#CCCCCC">
    <form id="form1" runat="server">
      <asp:Panel ID="Panel1" runat="server" BackColor="White" BorderStyle="Solid"
            Width="317px" CssClass="Panel">
        <div>
        <span class="Header">LED Web Control<br /> </span>
        <span class="Sub">A web control to blink your Arduino LEDs.<br /> </span>
        <table>
            <tr>
                <td>
                    <asp:Button ID="BLUE" runat="server" Text="BLUE" OnClick="BlueOn"
                        BackColor="Blue" BorderStyle="None" Font-Names="Segoe UI" Font-Size="XX-Large"
                        ForeColor="White" Width="310px" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Green" runat="server" Text="GREEN" OnClick="GreenOn" BackColor="#33CC33"
                        BorderStyle="None" Font-Names="Segoe UI" Font-Size="XX-Large"
                        ForeColor="White" Width="310px" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="ORANGE" runat="server" Text="ORANGE" OnClick="OrangeOn"
                        BackColor="#FF6600" BorderStyle="None" Font-Names="Segoe UI" Font-Size="XX-Large"
                        ForeColor="White" Width="310px" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="RED" runat="server" Text="RED" OnClick="RedOn"
                        BackColor="#CC0000" BorderStyle="None" Font-Names="Segoe UI" Font-Size="XX-Large"
                        ForeColor="White" Width="310px" />
                </td>
            </tr>
        </table>
        </div>
      </asp:Panel>
    </form>
</body>
</html>

Fire that puppy up and you’re done! Congratulations, I knew you had it in you. If you have any issues, feel free to leave a comment and I will do my best to help.

UPDATE: I have posted a follow up on how to acomplish the opposite. Send Data from Arduino to ASP.NET C# Web Application

Advertisements

10 responses to “Control Arduino from ASP.NET C# Web Application Interface

  1. Neat, I’m going to try something similar with my smartfusion. Never used asp.net before, that’s the scary part. The hardware.. meh

  2. Hello #Ben, Good Day I would like to ask if what type of document on VS are this code running on? i normally encounter HTTP Error 403.14 – Forbidden. Thank you

  3. hello, excellent project.
    I’m working on something, just let me know how you make the asp.net application
    you create an empty asp.net project? or where you write the statements of the libraries and serial port code
    hopefully this could answer very interesting. thanks

  4. could you some help me please i wrote this code on visiual studio and arduoino but i cant run it my visual studio can’t remember using System.Web.UI.WebControls;;

  5. Hi Ben! Your tutorial is great. I love it. I have a question to ask. Is it possible to replace the LEDs with Relay board. Which means that instead of the program to turn LED on and off, it will turn the relays on and off. Is it possible to do that? Hoping for your reply real soon. Thank you.

  6. Hi Ben, thank you very much for this wonderful article. I have tried this and it works amazingly. But, as because arduino supports only 1 serial communication at a time, I would like to know about how can I send data from asp.net c# web application to arduino using WiFi/Ethernet shield and vice-versa?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s