Ever wanted to make your own application (*.exe) to work with your arduino (or other serial communicating device)?

This instructable requires:

  - Visual Studio 2008 or later* (I am using 2010 RC, some options may differ between versions)
  - Visual C# Express Edition 2008 or later*

  - An Arduino (Any type) or other kind of serial communicating device
  - A basic knowledge of the C# Language

* An earlier edition of VS may work, but I am not sure if it has the SerialPort library.

Step 1: Create a New Application

Open Visual Studio and create a new Windows Forms Application. Then when form 1 comes up, add as many controls as you would like, starting with the SerialPort class.

If you are adding the Arduino support to your pre-made program, then just add the SerialPort class. If you are more advanced, you may want to make a plain code file with just the SerialPort library, so that you don't keep defining it.

Step 2: Configure Your Serial Port

The only things that ever need to be changed are the
   -BaudRate (Change this to match the Arduino code (Serial.begin(this is your baud rate))
   -Port Name (When compiling and uploading you need to select a port, usually starts with COM)
   -Maybe Read buffer size, and write buffer size, only if you intend on reading/writing more data than 4096Bytes reading or 2048Bytes writing to/from the arduino. Usually this setting can stay the same.

Step 3: Using the Serial Port in Code.

On a button, or any control that has an 'event' when clicked, just double click on the control, and it will come on to the code window. Here are some codes that you can use there. IF STATEMENTS ARE THE SAME!
The majority of the code is similar to the Arduino code, however;

Arduino Code     C# Code
Boolean               bool
unsigned any     uany

random                (new System.Random()).Next()
There is no time options for C#, such as delay() delayMicroseconds().

Other Stuff (at the top?!)

serialPort1.Open();  - Opens the serial port for you to use. There will be a big nasty error if the port is already opened, or if the port is not there.

serialPort1.BytesToRead - use an if statement to compare to 0. If the result is false, then there is serial data available (if(serialPort1.BytesToRead == 0) is the same as for arduino if(Serial.available))

Talking to the Arduino

serialPort1.Write(arg); - Tells the arduino something, where arg is what you want it to say. There will be a big nasty error if the port is not opened.

serialPort1.WriteLine(arg); - same as serialPort1.Write(arg); but always adds "\n".

Reading from the Arduino

string read = serialPort1.ReadTo(arg); - Reads the serial data, until the text in arg is found, then is returned as read. Also will have an error if the port is not opened.

string read = serialPort1.ReadLine(); - Same as serialPort1.ReadTo("\n");

string read  = serialPort1.ReadToEnd(); - Keeps reading until there is no more data to read, then is returned as string read.

Step 4: Example Part 1 - C# Part

On both of the Example pages, I have attatched the source code files. To open, extract the files on to where-ever you want them to be, and open the CS folder, and double click the .csproj file.

I want to have a program that changes an RGB LED's color, each time I click a button, so I am going to need a button on my control, and a serialPort.

I added the button and serial port to my form, and then resized the button to fit.
I then added a serialport, and changed the PortName to COM4. This may be different for your computer.

I then double-clicked the button, and it changed to the code view. In button1_Click(object sender, EventArgs e) I added code (There is some error handling code in this.) :

if (!serialPort1.IsOpen)
MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");

Step 5: Example Part 2 - Arduino Part

On both of the Example pages, I have attatched the source code files. To open, extract the files on to where-ever you want them to be, and open your Arduino programming environment, and then open the file found under the Arduino folder, and subfolders.

An RGB LED was connected to

R  Co  G   B  LED Pin
13 12  11 10 Ardunino Digital Pin

void setup()
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(11, LOW);
digitalWrite(13, HIGH);

int led = 1;

void loop()
case 1:
led = 2;
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
case 2:
led = 3;
digitalWrite(12, LOW);
digitalWrite(10, HIGH);
case 3:
led = 1;
digitalWrite(10, LOW);
digitalWrite(13, HIGH);
I am trying to read a speed value from the arduino, which is serial.println, I only get the initial value each time I open my program, example when I open my program if the speed sensor is 0.00 that's what it says, but when it changes to let's say a number like 20.5 it still says 0.00, but when I reopen the program, it will say 20.5. Also with it cuts off the first digit sometimes, for example I will have a number like 2.65 for my speed, but when I make i open the program I made, it shows only .65. I would really appreciate help. Code is below. <br> <br> <br>using System; <br>using System.Collections.Generic; <br>using System.ComponentModel; <br>using System.Data; <br>using System.Drawing; <br>using System.Linq; <br>using System.Text; <br>using System.Windows.Forms; <br> <br>namespace WindowsFormsApplication1 <br>{ <br> public partial class Form1 : Form <br> { <br> public Form1() <br> { <br> InitializeComponent(); <br> } <br> <br> private void Form1_Load(object sender, EventArgs e) <br> { <br> <br> try <br> { <br> if (arduinoCom.IsOpen == false) <br> { <br> arduinoCom.Open(); <br> } <br> } <br> <br> catch <br> { <br> MessageBox.Show(&quot;Serial Error: Is your serial plugged in?&quot;); <br> } <br> string speedReading = arduinoCom.ReadLine(); <br> speedText.Text = (speedReading); <br> <br> } <br> } <br>} <br>
<p>did you ever get this code working ?&gt; how can i use this code on my VS2013? i just want to learn how to interface Arduino with VS</p>
No I did not get it working. To be honest I got distracted by my other projects and never finished that.
<p>never drop a project men always look for other ways. </p>
<p>Hello, I am trying to build an application that listens and then talks to the arduino, Even though I have managed at other times to get it to work I dont seem to know what it is that works and end up breaking the code while trying to stitch a few changes. So close to finishing the project I dare post here for help. (and stackoverflow)</p><p>Serial port is open and baud rate is set</p><p>Arduino code snippets:</p><p>Serial.println('coin');</p><p>if( Serial.readString() == &quot;1234&quot;); &lt;&lt;&lt;--- how can i relax this condition as i did in the example below. (it does work on the Serial monitor but not on the software, is it an encoding situation?)</p><p>VS code snippets:</p><p> SerialPort sp = (SerialPort)sender;</p><p> string indata = sp.ReadExisting();</p><p> if (indata.Contains(&quot;coin&quot;)) &lt;&lt;&lt;--- it is a relaxed contains condition, better in my case, since I dont really know excaclty what it is receiving.</p><p>SerialPort.Write(&quot;1234&quot;); (how do I make sure it receives the characters i send be it ANSI hex or whatever.</p><p>thanks for your help.</p>
<p>i have project in mikroprosser.</p><p>to create a ohmmeter using arduino uno and interface it in computer using c#<br>can anyone know how?</p><p>email me at jjomar1994@gmail.com</p>
<p>hey pal i just wrote you but something was wrong with your email, can we link up? im really interested in this program your talking about....</p>
<p>This is great workout. thanks. &lt;3</p>
<p>Thx!, It works really good, but i only get the colours red and green. And how can you make a program in c# that simulates a keypress when a button on the arduino is pressed?</p>
<p>I have getting issue in firmware file update to GPS tracer using C#, can you please help me on this.</p><p>file extension is .dat need to send this file to GPS device to update firmware.</p>
<p>Hi <a href="https://www.instructables.com/member/mykiscool/" rel="nofollow">mykiscool</a>,</p><p>I think you must do something like this</p><p>while(true)</p><p>{</p><p>string speedReading = arduinoCom.ReadLine(); <br>speedText.Text = (speedReading); </p><p>System.Threading.Thread.Sleep(1000); //waiting for 5 seconds</p><p>}</p>
Nice work!! =)<br><br>Do you have a link for the source code?
Hi, do you how to interface arduino with a C# program using WiFi?
Thanks so much for this tutorial! I'm a beginner in both Arduino and Microsoft Visual Studio C#. I would like to ask whether is it possible to read multiple data? For my project, i have 2-3 sensors on the Arduino board, and i need to read the data/information from all the 3 sensors in one Arduino program, and display it out separately on Microsoft Visual Studio.
Yes, it's very possible. Use Serial.write(value 1); Serial.write(','); and repeat that a few times on the arduino. Then in C#, use String[] array = Serial.ReadLine().split(','); and then use array[0] to get the first value, [1] to get the second and so on.
wow thank you so much!!!!! i'll give it a try! :D
You're welcome. Some time in the near future I will update this tutorial, covering more on how to read from the Arduino, as well as sending/receiving multiple sets of data. Until then, feel free to contact me with any further questions :D
thank you so much! i'm so glad to hear that! my project is due 3 weeks later and my group is still struggling alot and all of us are quite new to microsoft visual studio and arduino! <br> <br>I do have one question. I'm now able to display the data from the sensor i'm using on the textbox. However, it only display integer value. i can't display double data type (example, values like 25.6, 34.8. It only display 25, 34). The codes below is the program i have typed. <br> <br> if (!serialPort1.IsOpen) <br> { <br> try <br> { <br> serialPort1.Open(); <br> double c = serialPort1.ReadByte(); <br> AirspeedTextBox1.Text = c.ToString(&quot;N2&quot;); <br> serialPort1.Close(); <br> } <br> catch <br> { <br> MessageBox.Show(&quot;There was an error. Please make sure that the correct port was selected, and the device, plugged in.&quot;); <br> } <br> <br>Is there any ways, or other ways to display the decimal values out? Thank you so much again!
ReadByte reads a single 8 bit byte from the Arduino. This can become a problem when reading values over 255, I'll fire up Visual Studio and Arduino, have a poke around and get back to you soon.
Hello! i managed to solve the decimal part! what i did was this: <br> <br>string[] c = serialPort1.ReadExisting().Split(','); <br> AirspeedTextBox.Text = c[0]; <br> SonarTextBox.Text = c[1]; <br> <br>i used string to read the data and i was shocked when it could display the decimal place. <br> <br>And thanks to your help, i manage to read and display multiple data! :D thanks thanks thanks! :D <br> <br>however, i do have another problem that i encounter. I also do need to keep updating the data and display on the textbox. I used the following codes to display the data: <br> <br> <br>using System; <br>using System.Collections.Generic; <br>using System.ComponentModel; <br>using System.Data; <br>using System.Drawing; <br>using System.Linq; <br>using System.Text; <br>using System.Windows.Forms; <br> <br>namespace AirSpeed <br>{ <br> public partial class Form1 : Form <br> { <br> public Form1() <br> { <br> InitializeComponent(); <br> } <br> <br> private void button1_Click(object sender, EventArgs e) <br> { <br> if (!serialPort1.IsOpen) <br> try <br> { <br> serialPort1.Open(); <br> } <br> catch <br> { <br> MessageBox.Show(&quot;There was an error. Please make sure that the correct port was selected, and the device, plugged in.&quot;); <br> } <br> } <br> <br> private void button2_Click(object sender, EventArgs e) <br> { <br> if (serialPort1.IsOpen) <br> serialPort1.Close(); <br> } <br> <br> private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) <br> { <br> this.Invoke(new EventHandler(DoUpdate)); <br> } <br> <br> private void DoUpdate(object s, EventArgs e) <br> { <br> string[] c = serialPort1.ReadExisting().Split(','); <br> AirspeedTextBox.Text = c[0]; <br> SonarTextBox.Text = c[1]; <br> } <br> } <br>} <br> <br>when i run this program, it can display the data and refresh it smoothly, and after a while, the whole form hanged, and informing me that Index was outside the bounds of the array at &quot;this.Invoke(new EventHandler(DoUpdate));&quot; codes (seen in the attached image). <br> <br>Any idea what caused the problem and how do i troubleshoot it? :) meanwhile i'll try to troubleshoot too! :) <br> <br>thanks once again! :D
IndexOutOfBounds is called when not enough data has been sent from the arduino to split it correctly. What you can do, is use ReadLine() instead of ReadExisting(), and use \n in the arduino code.<br><br>My apologies for not responding previously<br>Chris
yay! i managed to solve the problem with your help! thanks so much! :D
okay thank you! and sorry for taking up your time to do that! At the same time i'll try to figure out too! :)
Hello, <br>A forms load event is only ever called once (there are exceptions, but this instance covers none). I recommend you use the timer control to query the Arduino every half a second or so. If you'd like me to explain this further, please let me know :)
Ok thank, I'll try that.
Thank you so much! Works perfectly now. I will favorite your article.
I am c# programmer, I waste a lot of time try the c# in ardunio, at the end, I give up. mainly, many HW library is not equip as ardunio library, even I know how to convert back to c# code. But what is the point for my objective, learn the language or make sth happen in ardunio, and is stupied idea add extra code in the assamble code.
I'm not quite sure what you mean. C# is run on the computer, and the Arduino runs standard Arduino code, which uses the serial library to communicate with the PC.
nice job
Awesome I've been looking for a tut on just this...

About This Instructable




Bio: I love writing computer programs and pulling stuff apart to "see how it works", then putting it back together again.
More by chrisgward:Interfacing your arduino with a C# program Make a Matrix Screen with Pseudo-Random number generator 
Add instructable to: