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 communicating with Arduino with other devices.

This communication has the advantage that it can be carried out with a wide variety of devices (such as a computer, a tablet, a mobile phone), is independent of the operating system (including Windows, Linux, Mac, and Android) and can be done in a multitude of programming languages.

In this post we are going to learn how to connect Arduino with C#, the popular Microsoft programming language, which natively has objects to use the serial ports in a very simple way.

To do 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.

Communication can be done both by cable and wirelessly via Bluetooth, as we saw in the post Connect Arduino by Bluetooth with HC-05 or HC-06 modules

To see how to connect Arduino with C# we are going to see two simple examples, the same ones we saw in the post Communication of Arduino with serial port. But this time we will carry out 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 almost feel 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. In addition, we would normally transmit bytes instead of text, and include checks to ensure that the transmission has been carried out correctly.

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

You can also use Visual Studio to program Arduino directly, as we saw in the post The best IDE for Arduino, Visual Studio with Visual Micro

Turn on and off an LED

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

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

We choose the template “Windows Form Application”, the location where we want to save it on our hard drive and as the name of 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.

ElementoNameText
FormulariofrmMainBasic C#
Boton ONbtOnON
Boton OFFbtOffOFF

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 yours
            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 in which you have Arduino connected.

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.

Blinking an LED

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

To do this, we start modifying the form of 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 as shown in the following table.

ElementoNameText
FormulariofrmMainBasic C#
Boton SendbtSendSend
TextboxtxNumber

Now we edit the code of the form, 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 yours
            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 )
            {
     /te(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, a first presentation of communication of Arduino with C#. In the future, we will use more advanced methods to handle servos and robots.

If you liked this post and want to read more about Arduino, you can check the section Arduino Tutorials

Download the code

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