Language: EN

comunicar-arduino-con-c

Control Arduino with C# and the serial port

When we saw the use of the serial port in Arduino in this post, we already mentioned that it was the main means we had for communication between Arduino and other devices.

This communication has the advantage that

  • It can be performed with a wide variety of devices (such as a computer, tablet, mobile)
  • It is independent of the operating system (including Windows, Linux, Mac, and Android)
  • It can be done in a multitude of programming languages.

In this post, we will learn how to connect Arduino with C#, the popular programming language from Microsoft, which natively provides objects to easily use serial ports.

For this, it is necessary to have Visual Studio installed, Microsoft’s IDE. The “Community” version is free for personal use and can be downloaded from this link.

To see how to connect Arduino with C#, we will look at two simple examples, the same ones we saw in the post Arduino communication with serial port. But this time, we will perform the communication from a program developed in C#, instead of using the Serial Monitor of the Arduino IDE.

The C# code we are going to show is very simple (I’m almost embarrassed to publish it) because they are examples to illustrate how easy it is to use the serial port to connect Arduino with C#. But keep in mind that in a real project we should include some improvements.

For example, the use of the serial port would be integrated into our objects, and we would have independence between the visual layer and the model. Also, we would normally transmit bytes instead of text, and we would include checks to ensure that the transmission has been completed successfully.

We will see this in future posts, but for now, we are satisfied with learning to use the basics of serial ports to communicate Arduino with C#.

Turn on and off an LED

In this example, we will create a simple form with two ON and OFF buttons, which will allow us to turn on the integrated LED on the Arduino board, connected to Pin 13.

First, we start Visual Studio and create a new C# project. To do this, we click on File/New/Project.

We choose the “Windows Form Application” template, the location where we want to save it on our hard drive and name the project “BasicSerialPort”.

arduino-chsarp-1

An empty form will open, which will be the main window of our example. We drag two buttons from the Toolbox to our form, and place them one on top of the other.

arduino-chsarp-2

Now we use the properties bar to change the text and name of both the buttons and the form.

arduino-chsarp-3

We leave the values as shown in the following table.

ElementNameText
FormfrmMainBasic C#
ON ButtonbtOnON
OFF ButtonbtOffOFF

Now, we press F7 on the form to access the code (or right-click and choose “View code”).

arduino-chsarp-4

We replace all the code with the following.

using System;
using System.Windows.Forms;

namespace BasicSerialPort
{
    public partial class frmMain : Form
    {
        System.IO.Ports.SerialPort ArduinoPort;

        public frmMain()
        {
            InitializeComponent();

            //create Serial Port
            ArduinoPort = new System.IO.Ports.SerialPort();
            ArduinoPort.PortName = "COM4";  //replace with your 
            ArduinoPort.BaudRate = 9600;
            ArduinoPort.Open();

            //bind events
            this.FormClosing += FrmMain_FormClosing;
            this.btOFF.Click += BtOFF_Click;
            this.btON.Click += BtON_Click;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //close port
            if (ArduinoPort.IsOpen) ArduinoPort.Close();
        }

        private void BtOFF_Click(object sender, EventArgs e)
        {
            ArduinoPort.Write("a");
        }

        private void BtON_Click(object sender, EventArgs e)
        {
            ArduinoPort.Write("b");
        }
    }
}

Remember to replace the serial port in the code, in the example “COM4”, with the serial port where you have connected Arduino.

Now we load this program into Arduino.

const int pinLED = 13;

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

void loop() {
  if (Serial.available() > 0)
  {
    int option = Serial.read();
    if (option == 'a')
    {
      digitalWrite(pinLED, LOW);    
    }
    if (option == 'b')
    {
      digitalWrite(pinLED, HIGH);
    }
  }
}

We run the program by pressing F5. We press the buttons, and we will see that the integrated LED of Arduino turns on and off.

We are going to modify the previous program to send a number from 0 to 9 to Arduino. Arduino will receive that number and blink the integrated LED the number of times received.

To do this, we start by modifying the form from the previous example. We remove one of the two buttons and drag a new Textbox from the Toolbox.

arduino-chsarp-5

We use the properties palette to modify the properties of the Textbox and the remaining button. We leave the values according to the following table.

ElementNameText
FormfrmMainBasic C#
Send ButtonbtSendSend
TextboxtxNumber

Now we edit the form code, and replace it with the following.

using System;
using System.Windows.Forms;

namespace BasicSerialPort
{
    public partial class frmMain : Form
    {
        System.IO.Ports.SerialPort ArduinoPort;

        public frmMain()
        {
            InitializeComponent();

            //create Serial Port
            ArduinoPort = new System.IO.Ports.SerialPort();
            ArduinoPort.PortName = "COM4"; //replace with your 
            ArduinoPort.BaudRate = 9600;
            ArduinoPort.Open();

            //bind events
            this.FormClosing += FrmMain_FormClosing;
            this.btSend.Click += BtSend_Click;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //close port
            if(ArduinoPort.IsOpen) ArduinoPort.Close();
        }

        private void BtSend_Click(object sender, EventArgs e)
        {
            //convert Textbox text to integer
            int value;
            bool rst = Int32.TryParse(txNumber.Text, out value);

            //if the conversion is valid, and the number is between 0 and 9, send the number as text
            if (rst == true && value > 0 && value < 9 )
            {
                ArduinoPort.Write(value.ToString());
            }
        }
    }
}

We load this program into Arduino.

const int pinLED = 13;

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

void loop()
{
  if (Serial.available()>0) 
  {
    char option = Serial.read();
    if (option >= '1' && option <= '9')
    {
      option -= '0';
      for (int i = 0;i<option;i++) 
      {
        digitalWrite(pinLED, HIGH);
        delay(100);
        digitalWrite(pinLED, LOW);
        delay(200);
      }
    }
  }
}

We run the program in Visual Studio by pressing F5. When entering a number between 0 and 9, we will see the LED on the board blink the indicated number of times.

So far, this is a first introduction to communication between Arduino and C#. In the future, we will use more advanced methods to handle servos and robots.

Download the code

All the code from this post is available for download on Github. github-full