Arduino Control Using a WPF Application

This article will guide you through the process of robot or embedded system control using a WPF application. There are mainly two types of Robotics but sometimes a hybrid model becomes a necessity. Robotics control can be done using a controller but then again, the cost factor is also relevant. You won't feel like spending hundreds of bucks for your control of various robots. It's always beneficial when you have a software model for this purpose.

The following hardware is required:

  1. An Arduino developer board (I have used an Arduino Leonardo).
  2. Light Emitting Diode (LED).

The following software is required:

  1. Arduino IDE
  2. Visual Studio

Arduino

An Arduino is a developer board built around the Atmel AVR microcontrllers. They are used in embedded systems and robotics applications, this open-source hardware is one of the best developer boards to design your embedded systems.

Arduino Leonardo developer board
Figure 1: A layout of an Arduino Leonardo developer board. Picture credit: Arduino.

Let's begin with the Arduino part first. We will be turning on and off an LED and using a WPF app. First let us see the circuit diagram. We will connect the LED to pin number 13. The LED's longer pin will be in the pin number 13 whereas the shorter in the GND pin.

Circuit diagram
Figure 2: Circuit diagram.

In the preceding figure, the resistance may or may not be used. However it's safe to use it. In that case you need 220 ohm to 1K ohm resistance.
The LED is connected to the pin 13 and GND. Our next course of action is to program the Arduino. First connect the Arduino to the USB. For drivers and the IDE, visit arduino. Now after connecting the Arduino board to your PC, go to Tools, then port to select the port where your Arduino is connected. Also select your developer board by clicking Tools and selecting Board. The following Figure 3 shows the screenshot of the IDE where you need to select.

IDE where you need to select the port
Figure 3: Screenshot of the IDE where you need to select the port and the board.

After selecting the board and the port, we will go to the programming.
  1. void setup()   
  2. {  
  3.     pinMode(13, OUTPUT);  
  4.     Serial.begin(9600);  
  5. }  
  6.   
  7. void loop()   
  8. {  
  9.     if (Serial.available() > 0)   
  10.     {  
  11.         char c = Serial.read();  
  12.         if (c == '1')   
  13.         {  
  14.             digitalWrite(13, HIGH);  
  15.         } else if (c == '0')   
  16.         {  
  17.             digitalWrite(13, LOW);  
  18.         }  
  19.     }  
  20. }  
Let me explain the code first. In the setup() function, we initialize the pins to be configured as input or output. The pinMode() command will allow us to do that.
  1. pinMode(13,OUTPUT);   
Here 13 is the pin number whereas the output is used to configure it. You can also use other pins but since we have connected the LED to pin number 13, we have used 13.

The next part is where you need to define the Baud Rate. The Baud Rate in this case will be 9600. You can use other values as well but in that case the value that you use here must match the one you use in your WPF app. Serial.Begin(9600) is used to start the Serial port communication. These are the parts under the setup function.

In void loop(), the code that needs to be executed repeatedly is inserted out there. Since we are using Serial port communication, our first course of action is to accept a value through the communication channel. In order to do that, we will first check whether the link is available with the following line of code.
  1. if(Serial.available()>0)   
Once this condition is checked, we will accept the value over the Serial port.
  1. char c = Serial.read();   
Here we store the value of the character received in a character variable c. We will use this c to switch on and off the LED. Our intent is to switch on and off a LED. The LED will be switched on when we receive 1. When we receive 0, it will be switched off. To switch an LED on and off, we need to change the state of the pin 13 on the Arduino board. When the state is HIGH, the LED is on and vice versa. The line of code used to attain this functionality is:
  1. digitalWrite(13,HIGH); //for high   
  2. digitalWrite(13,LOW);//for low   
Now the following is the finalized code for void loop:
  1. void loop()     
  2. {    
  3.   if(Serial.available()>0)    
  4.   {    
  5.     char c = Serial.read();    
  6.     if (c == '1')    
  7.     {       
  8.       digitalWrite(13,HIGH);    
  9.     }    
  10.     else if (c == '0')    
  11.     {    
  12.       digitalWrite(13,LOW);    
  13.     }      
  14.   }    
  15. }  
Now you need to compile and upload the code. Just press the right arrow-type button on the top-left corner and your sketch will first be saved and will then compile and ultimately uploaded. The following Figure 4 shows us the screenshot.

Arduino IDE with the final sketch
Figure 4: Screenshot of the Arduino IDE with the final sketch.

Once you upload the code, your hardware part is done. Now we will do the controlling part using the WPF app. So open Microsoft Visual Studio and open a WPF project. Figure 5 shows the screenshot of the start page of Visual Studio. Let us name the project controller_Arduino.

start page of Microsoft Visual Studio
Figure 5: Screenshot of the start page of Microsoft Visual Studio.

Now before going to the main code, let me explain how it will work. Serial port communication in WPF will be carried out by the SerialPort class. We will send characters serially using this class. The buttons to be used in the UI will contain a TextBox for entering the com port number where the device will be connected. Once the device is connected a textBlock named StatusBox will display connected. Once the device (Arduino) is connected with the app, then the app will be able to communicate with the Arduino. This project uses serial communication by the USB that definitely is wired. For wireless, you need to have two more hardware and some changes will be done in the circuitry. Everything else will be the same. Let us now design the UI. The UI will consist of the following components. 
  1. A button named "on" with the content on to switch on a LED.

  2. A button named "off" with the content to switch off a LED.

  3. A button named connect with the content as connect to connect the Arduino board.

  4. A button named disconnect with the content as disconnect to disconnect the Arduino board.

  5. A TextBox with the named com port which will be taken as an input for the com port number.

  6. A TextBlock with the name status to display the current connection status.

Add the preceding components in the MainWindows.xaml page. Create a click event for each button. Alternatively you can use the code pasted.

  1. <Window x:Class="controller_Arduino.MainWindow"    
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
  4.         Title="Controller for Arduino v1" Height="750" Width="1020">    
  5.     <Grid>    
  6.         <Button x:Name="on" Content="On" HorizontalAlignment="Left" Margin="136,164,0,0" VerticalAlignment="Top" Width="87" Height="52" Click="on_Click"/>    
  7.         <Button x:Name="Of" Content="Off" HorizontalAlignment="Left" Margin="246,164,0,0" VerticalAlignment="Top" Width="87" Height="52" Click="Of_Click"/>    
  8.         <TextBlock x:Name="status" HorizontalAlignment="Left" Margin="506,253,0,0" TextWrapping="Wrap" Text="Disconnected" VerticalAlignment="Top" Height="29" Width="94"/>    
  9.         <TextBox x:Name="comportno" HorizontalAlignment="Left" Height="23" Margin="506,164,0,0" TextWrapping="Wrap" Text="COM13" VerticalAlignment="Top" Width="120"/>    
  10.         <Button x:Name="Connect" Content="Connect" HorizontalAlignment="Left" Margin="506,199,0,0" VerticalAlignment="Top" Width="55" Height="24" Click="Connect_Click"/>    
  11.         <Button x:Name="Disconnect" Content="Disconnect" HorizontalAlignment="Left" Margin="571,199,0,0" VerticalAlignment="Top" Width="55" Height="24" Click="Disconnect_Click"/>    
  12.     
  13.     </Grid>    
  14. </Window>   
Now let us browse to MainWindow.xaml.cs and begin the real code. As already mentioned before, we will use the SerialPort class so we need to add this first.
  1. using System.IO.Ports;  
Now create an object of the SerialPort class.
  1. SerialPort sp = new SerialPort();  
Now navigate to the connect button's event handler method and here we will add the code required to connect our app to the Arduino. A try catch block is added to prevent crashes while connecting. The most common reason is the incorrect port number.
  1. private void Connect_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     try    
  4.     {    
  5.         String portName = comportno.Text;    
  6.         sp.PortName = portName;    
  7.         sp.BaudRate = 9600;    
  8.         sp.Open();    
  9.         status.Text = "Connected";    
  10.     }    
  11.     catch (Exception)    
  12.     {    
  13.   
  14.         MessageBox.Show("Please give a valid port number or check your connection");    
  15.     }    
  16. }    
In the preceding code, we are storing the portname that's the comport number. The PortName is assigned tosp.PortName. Next the baud rate is assigned in sp.BaudRate=9600. The next step is to open the communication channel. Ultimately the status TextBlock is updated with the Connected string. Similarly for the disconnect button, we have code to disconnect the Arduino.
  1. private void Disconnect_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     try    
  4.     {    
  5.         sp.Close();    
  6.         status.Text = "Disconnected";    
  7.     }    
  8.     catch (Exception)    
  9.     {    
  10.   
  11.         MessageBox.Show("First Connect and then disconnect");    
  12.     }    
  13. }   
The preceding code is also included in a try catch block so as to prevent the application from crashing in case some error occurs.

Our next course of action is to code for the on and off buttons.
  1. private void on_Click(object sender, RoutedEventArgs e)    
  2. {    
  3.     sp.Write("1");    
  4. }    
  5.   
  6. private void Of_Click(object sender, RoutedEventArgs e)    
  7. {    
  8.     sp.Write("0");    
  9. }  
The preceding code is quite simple. Using only sp.Writr(“1”); and sp.Write(“0”); we are able to send characters serially to the Arduino.

The entire code for MainWindow.xaml.cs is pasted below for your convenience. However it is advised to try this yourself.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Text;    
  5. using System.Threading.Tasks;    
  6. using System.Windows;    
  7. using System.Windows.Controls;    
  8. using System.Windows.Data;    
  9. using System.Windows.Documents;    
  10. using System.Windows.Input;    
  11. using System.Windows.Media;    
  12. using System.Windows.Media.Imaging;    
  13. using System.Windows.Navigation;    
  14. using System.Windows.Shapes;    
  15. using System.IO.Ports;    
  16.     
  17. namespace controller_Arduino    
  18. {    
  19.     /// <summary>    
  20.     /// Interaction logic for MainWindow.xaml    
  21.     /// </summary>    
  22.     public partial class MainWindow : Window    
  23.     {    
  24.         SerialPort sp = new SerialPort();    
  25.         public MainWindow()    
  26.         {    
  27.             InitializeComponent();    
  28.         }    
  29.     
  30.         private void on_Click(object sender, RoutedEventArgs e)    
  31.         {    
  32.             sp.Write("1");    
  33.         }    
  34.     
  35.         private void Of_Click(object sender, RoutedEventArgs e)    
  36.         {    
  37.             sp.Write("0");    
  38.         }    
  39.     
  40.         private void Connect_Click(object sender, RoutedEventArgs e)    
  41.         {    
  42.             try    
  43.             {    
  44.                 String portName = comportno.Text;    
  45.                 sp.PortName = portName;    
  46.                 sp.BaudRate = 9600;    
  47.                 sp.Open();    
  48.                 status.Text = "Connected";    
  49.             }    
  50.             catch (Exception)    
  51.             {    
  52.     
  53.                 MessageBox.Show("Please give a valid port number or check your connection");    
  54.             }    
  55.         }    
  56.     
  57.         private void Disconnect_Click(object sender, RoutedEventArgs e)    
  58.         {    
  59.             try    
  60.             {    
  61.                 sp.Close();    
  62.                 status.Text = "Disconnected";    
  63.             }    
  64.             catch (Exception)    
  65.             {    
  66.     
  67.                 MessageBox.Show("First Connect and then disconnect");    
  68.             }    
  69.         }    
  70.     }    
  71. }   
Congratulations, your project is complete. You made your first Arduino Controller. It's simple but with a creative mind, you will be able to attain more complicated tasks. In my future article, I will introduce you to controlling an Arduino but with a Windows Phone using HC06. In the end, I will include a screenshot of my latest robot controller named Universal Robot Controller.

Your first Arduino Controller
Figure 6: Your first Arduino Controller

This article showed you how to control the Arduino using a wired connection. However if you want to shift to a wireless connection, then you need to have a Serial and USB link. In my projects I used a link of 2.4 GHz frequency. In that case some changes will occur in the circuit since you need to use the Rx and Tx pins. It's not a big deal though. The WPF app part remains the same. In case of any problem, please share it in the comments section below.

Up Next
    Ebook Download
    View all
    Learn
    View all