Reading Serial data from an Arduino using C#

In this example we will use analog pin 0 to obtain a value and send it via the com port (USB) , we will read this with a C# app and display the value in a progress bar and label.

Here is a screenshot of this in action, Arduino code and app running

arduino serial out
arduino serial out

Arduino Code

void setup()
{
Serial.begin(9600);
}

void loop()
{
int sensorValue = analogRead(A0);
Serial.println(sensorValue, DEC);
delay(200);
}

 

C# Code

The C# Windows form application requires a SerialPort component, a ProgressBar and a label to be added to the form.

We set the ProgressBars minimum to 0 and maximum to 1024

using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ArduinoSerialIn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.PortName = “COM5”;
serialPort1.Open();
serialPort1.DataReceived += serialPort1_DataReceived;
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string line = serialPort1.ReadLine();
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
}

private delegate void LineReceivedEvent(string line);
private void LineReceived(string line)
{

label1.Text = line;
progressBar1.Value = int.Parse(line);
}
}
}

 

Download

Serial out example on GITHUB

Previous articleRGB LED and Netduino example
Next articleArduino to C# temperature example