Arduino LED Controller With WPF

619

7

Posted in TechnologyArduino

Introduction: Arduino LED Controller With WPF

The purpose of this project is to control an LED connected on an Arduino with a WPF application using serial communication.

For this project I will be using an Arduino Nano but feel free to use whatever kind of Arduino (Uno, Mega, etc...)

All the files required for this project are included in this tutorial.

This is a basic tutorial that gives you the opportunity to easily implement more functions and hardware to this project. For the sake of this tutorial, I kept it simple so that it is easier to understand.

If you want to know more about certain function or syntax used in this code, I would recommend you to go check out https://www.arduino.cc/reference/en/ for more detail information.

Enjoy!

Step 1: Connect Your LED

Step 2: WPF Form

Create a WPF application

  • File > New > Project...
  • Name it Application1
  • Save it wherever you want (Desktop, Documents, etc)

Open the MainWindow.xaml tab

  • shortcut (SHIFT+F7)

Open the toolbox and add the following elements to your form

  • shortcut (CTRL+ALT+X) will open the toolbox

Add (2x Buttons, 2x Textboxes and 2x Labels)

Button (1)

Namebtn1(name of this button instance)
ContentLED 1 OFF(text on the button)
Background#FFFF0000(Color red)

 

Button (2)

Namebtn2(name of this button instance)
ContentBlink(text on the button)
Background#FFDDDDDD(Color light grey)

 

Textbox (1)

Nametb1(name of this textbox instance)
Text (erase the text content, leave blank)

 

Textbox (2)

Nametb2(name of this textbox instance)
Text (erase the text content, leave blank)

 

Label (1)

Namelb1(name of this label instance)
ContentLoop for ... times(text on the label)

 

Label (2)

Namelb2(name of this label instance)
ContentSpeed (Milliseconds)(text on the label)

Step 3: WPF Code Behind

Open the MainWindow.xaml.cs

  • shortcut (F7)

At the top of the code, add the following line of code

using System.IO.Ports;

This allows you to access and use the serial ports

Add the following lines of code

namespace Application1
{
    public partial class MainWindow : Window
    {
        SerialPort  mySerialPort = new SerialPort("COM6", 9600);
        private byte btnstate = 0;

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}   

The first line creates an instance of the SerialPort class named mySerialPort

It sets the serial port on COM6 (that might and will probably be different for you). Check the Device Manager to get your proper COM port number.

It also sets the baud rate (9600bauds)

The second line that we haded creates a variable that will store the state of the button (btn1)

When btnstate is equal to 0, it means that the button is in the OFF mode

When btnstate is equal to 1, it means that the button (btn1) is in the ON mode

Open the MainWindow.xaml tab

  • shortcut (F7)
  • Double-Click on LED 1 OFF (btn1)

When you double-click an object that is in your form, Visual Studio will create a "_Click" event for you in the MainWindow.xaml.cs tab

Add the following lines of code in the btn1_Click event

private void btn1_Click(object sender, RoutedEventArgs e)
        {
            if(btnstate == 0)
            {
                mySerialPort.Open();
                mySerialPort.Write("1");
                mySerialPort.Close();
                btnstate = 1;
                btn1.Background = Brushes.Green;
                btn1.Content = "LED 1 ON";
            }
            else
            {
                mySerialPort.Open();
                mySerialPort.Write("2");
                mySerialPort.Close();
                btnstate = 0;
                btn1.Background = Brushes.Red;
                btn1.Content = "LED 1 OFF";
            }
        }

if / else statement, checks the value of our variable btnstate

If btnstate is equal to 1, the program will execute the code in the "if" statement.

If btnstate is equal to 0, the program will execute the code in the "else" statement

mySerialPort.Open/Write/Close

First we Open the serial port to establish communication with the arduino (on COM6 @ 9600bauds).

Then we write on the serial port the character "1".

Once done writing on the serial port, we close it.

Changing the value of btnstate

By changing the value of btnstate from 0 to 1 or 1 to 0 allows use to use the button (btn1) as a toggle switch.

Each time that we click the button (btn1), the program checks the current state of the button (defined by our variable btnstate) and then executes either the "if" or "else" statement.

btn1.Background and btn1.Content

Depending on the state of the button (ON or OFF mode) change the background color of the button (Red for OFF, Green for ON)

Alos, change what is written on the button by changing the Content proprety of the button (LED 1 OFF, LED 1 ON)

In the MainWindow.xaml tab

  • shortcut (F7)
  • Double-Click on Blink (btn2)

When you double-click an object that is in your form, Visual Studio will create a "_Click" event for you in the MainWindow.xaml.cs tab

This part of the code requieres the user to input 2 parameters to make it work properly. We will prompt an error message to the user if an error occurs.

The first parameter will be in the textbox1 (tb1) and this will be the for loop ... times.

The second parameter will be in the textbox2 (tb2) and this will be our Blinking speed (in Milliseconds)

Add the following lines of code in the btn2_Click event

private void btn2_Click(object sender, RoutedEventArgs e)
        {
            if(tb1.Text!= "" && tb2.Text!="")
            {
                mySerialPort.Open();
                mySerialPort.Write("t" + tb2.Text + "s" + tb1.Text);
                mySerialPort.Close();
            }
            else
            {
                MessageBox.Show("You must set (Loop For ... times) and (Speed) before executing the Blink command!");
            }
            
        }

if statement

If the content of textbox1 (tb1) AND the content of textbox2 (tb2) IS NOT EQUAL to "" (which is empty/no text in the box) do what is inside the curly brackets

else statement

If the content of textbox1 (tb1) OR the content of textbox2 (tb2) IS EQUAL to "" (which is empty/no text in the box) prompt the user an error message.

mySerialPort.Write();

Here is one way to send multiple variables by a serial communication.

  • First we send the character "t".
  • Then we send how many times we want the LED on our arduino to blink
  • Then we send the character "s".
  • Finally we send the speed in milliseconds at which we want the LED on our arduino to blink

Example : "t10s1000" means Blink the LED 10 times with an On/Off time of 1 second (1000ms)

The arduino will receive this message on the serial port and will interpret the "t" as "oh! the following characters are for my ForLoop" and the "s" as "oh! the following characters are for the blinking speed"

The "t" and "s" can be change by any characters, I used "t" for "times" and "s" for "spped". As long as you use the same characters in your Arduino sketch it will be fine.

I will explain this with more detail when we get in the arduino sketch.

That's it for the WPF application! Save it then launch the Arduino IDE.

Step 4: Arduino Sketch

Open Arduino IDE

  • File > New
  • Save As Application1.ino

Write the following code in your sketch

int led1 = 2;
char mychar;
long blinkSpeed;
int loopFor;


void setup()
{
    pinMode(led1, OUTPUT);
    Serial.begin(9600);
}


void loop()
{
  
	while (Serial.available()>0)
	{
        mychar = Serial.read();
   
        if(mychar == '1')
        {
            digitalWrite(led1, HIGH);
        }
        else if(mychar == 't')
        {
            loopFor = Serial.parseInt();
        }

        else if(mychar == 's')
        {
            blinkSpeed = Serial.parseInt();
            BlinkMyLED(led1, blinkSpeed, loopFor);
        }
        else
        {   
            digitalWrite(led1,LOW);
        }
    }
}
  
void BlinkMyLED(int pinNumber, long _blinkSpeed, int _loopFor)
{
  for(int x = 0; x < _loopFor; x++)
  {
    digitalWrite(pinNumber, HIGH);
    delay(_blinkSpeed);
    digitalWrite(pinNumber, LOW);
    delay(_blinkSpeed);
  }
}
    

How does it work?

Let's say that the user clicks the Blink button in the WPF application. He puts 10 in textbox1 (tb1) and 100 in textbox2 (tb2).

The serial data on the serial port is going to be "t10s100"

This data gets to the arduino, therfore Serial.available() is greater than 0 (0 means that there is no data available on the serial buffer)

As long as there is data available on the serial port, read the first byte and store it in the variable mychar.

As soon as you store the first byte check what it is.

If mychar is equal to the character '1' (notice single quote) turn the LED on using digitalWrite();

If mychar is equal to the character 't' (this is for our ForLoop) store the next available byte that can be converted to integers (int) in the variable loopFor. We use the function Serial.parseInt() to do that.

If mychar is equal to the character 's' (this is for our blink speed) store the next available byte that can be converted to integers (int) in the variable blinkSpeed. We use the function Serial.parseInt() to do that. The character 's' will always be after the charater 't' (in the data sequence) therfore, after we store the speed data in the blinkSpeed variable we execute our custom BlinkMyLED function.

If mychar is not equal to '1' OR 't' OR 's', turn the LED off using digitalWrite();

BlinkMyLED function, has 3 parameters

1 - LED pin number

2 - Blink Speed

3 - How many times you want to blink

Example : "t10s100" / led1 = 2

loopFor = 10

blinkSpeed = 100

BlinkMyLED(led1, blinkSpeed, loopFor); would be equal to BlinkMyLED(2,100,10); with this example.

The function would turn on/off every 100ms pin#2 for 10 times. Using a simple ForLoop. The following portion of the code has been changed just to demonstrate how it works if we manually input the parameters.

 void BlinkMyLED(2, 100, 10)
{
  for(int x = 0; x < 10; x++)
  {
    digitalWrite(2, HIGH);
    delay(100);
    digitalWrite(2, LOW);
    delay(100);
  }
}

Step 5: Test It!

That's it!!! Compile & Upload on your Arduino and launch the WPF application.

Enjoy and don't be afraid to ask for more Instructables!

Share

    Recommendations

    • Spotless Contest

      Spotless Contest
    • Microcontroller Contest

      Microcontroller Contest
    • Space Challenge

      Space Challenge
    user

    We have a be nice policy.
    Please be positive and constructive.

    Tips

    Questions

    Comments