Introduction: Interfacing Your Arduino With a C# Program
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)
OR
- 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)
{
try
{
serialPort1.Open();
serialPort1.Write("T");
serialPort1.Close();
}
catch
{
MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");
}
}
Attachments
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()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
digitalWrite(11, LOW);
digitalWrite(13, HIGH);
}
int led = 1;
void loop()
{
if(Serial.available())
{
Serial.read();
switch(led)
{
case 1:
led = 2;
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
break;
case 2:
led = 3;
digitalWrite(12, LOW);
digitalWrite(10, HIGH);
break;
case 3:
led = 1;
digitalWrite(10, LOW);
digitalWrite(13, HIGH);
}
}
}
Attachments

Participated in the
USB Contest
35 Comments
11 years ago on Step 5
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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
if (arduinoCom.IsOpen == false)
{
arduinoCom.Open();
}
}
catch
{
MessageBox.Show("Serial Error: Is your serial plugged in?");
}
string speedReading = arduinoCom.ReadLine();
speedText.Text = (speedReading);
}
}
}
Reply 6 years ago
Hi mykiscool! I think it is because your code where your app reads your arduino serial is in the Load method. try to use a timer class instead.
Reply 8 years ago on Introduction
did you ever get this code working ?> how can i use this code on my VS2013? i just want to learn how to interface Arduino with VS
Reply 8 years ago on Introduction
No I did not get it working. To be honest I got distracted by my other projects and never finished that.
Reply 8 years ago on Introduction
never drop a project men always look for other ways.
3 years ago
Hello,
First of all, I congratulate you.
How can I send any text wirelessly from C #. (For example using esp32 or nodemcu)
Tip 4 years ago
Greetings;
You can use Timer or Threading for time intervals.
Even though in my opinion is not a good practice due to resource consumption, it can be useful for a small application.
I'll write simple pseudo code as I'm not in front of the computer right now.
private Timer tmr;
void InitTimer()
{
tmr = new Timer();
tmr.Interval(1000); // 1 sec in milliseconds
tmr.tick += new EventHandler(tmrTick);
tmr.Start();
}
// Bellow place the code to execute every second. Just like loop method in C++
private void tmrTick()
{
// Your code actions go here
// I.e: getting dht22 temperature every second
}
Reply 4 years ago
that is what I've been looking for although I can't seem to make that code work for me. What is exactly in the formload?
public partial class Form1 : Form
{
string str="";
private Timer tmr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SerialPort currentPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One);
currentPort.Open();
str = currentPort.ReadLine();
label1.Text = str;
}
private void Timer1_Tick(object sender, EventArgs e)
{
Task.Run(() => {
this.BeginInvoke((Action)(() => { label1.Text = str; }));
});
}
private void Button1_Click(object sender, EventArgs e)
{//Start
timer1.Start();
}
private void Button2_Click(object sender, EventArgs e)
{//Stop
timer1.Stop();
}
}
}
11 years ago on Introduction
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.
Reply 11 years ago on Introduction
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.
Reply 11 years ago on Introduction
wow thank you so much!!!!! i'll give it a try! :D
Reply 11 years ago on Introduction
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
Reply 11 years ago on Introduction
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!
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.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
double c = serialPort1.ReadByte();
AirspeedTextBox1.Text = c.ToString("N2");
serialPort1.Close();
}
catch
{
MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");
}
Is there any ways, or other ways to display the decimal values out? Thank you so much again!
Reply 11 years ago on Introduction
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.
Reply 11 years ago on Introduction
Hello! i managed to solve the decimal part! what i did was this:
string[] c = serialPort1.ReadExisting().Split(',');
AirspeedTextBox.Text = c[0];
SonarTextBox.Text = c[1];
i used string to read the data and i was shocked when it could display the decimal place.
And thanks to your help, i manage to read and display multiple data! :D thanks thanks thanks! :D
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:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AirSpeed
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
try
{
serialPort1.Open();
}
catch
{
MessageBox.Show("There was an error. Please make sure that the correct port was selected, and the device, plugged in.");
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
serialPort1.Close();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
string[] c = serialPort1.ReadExisting().Split(',');
AirspeedTextBox.Text = c[0];
SonarTextBox.Text = c[1];
}
}
}
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 "this.Invoke(new EventHandler(DoUpdate));" codes (seen in the attached image).
Any idea what caused the problem and how do i troubleshoot it? :) meanwhile i'll try to troubleshoot too! :)
thanks once again! :D
Reply 11 years ago on Introduction
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.
My apologies for not responding previously
Chris
Reply 5 years ago
sir where can l write \n in the arduino program
Reply 11 years ago on Introduction
yay! i managed to solve the problem with your help! thanks so much! :D
Reply 5 years ago
if its possible can you send me the codes you used for both the arduino and the c#
Reply 11 years ago on Introduction
okay thank you! and sorry for taking up your time to do that! At the same time i'll try to figure out too! :)