Categories
Arduino C#

Arduino + C# Serialport ReadLine and Display on Textbox

Today we are going to read analog input in Arduino and send that read value to Serial port via serial.println() function. After that we are going to create C# based winform application and read data coming from Arduino and display into a Textbox using delegate methods in C#. SerialPort Object in C# will help us for reading incoming serial data but it runs on different thread then the GUI thread. So we have to handle cross thread communication. We are going to do this using delegates which are similar to pointer to function but it also keep track of the input arguments with their types and return types.

Arduino ADC Read Example

To read the analog input in Arduino we have built in function called analogRead(). This function takes one argument which is the name Analog Pin Number. In Arduino UNO we have pins ranging from A0 to A5. In this example we placed a potentiometer to A0 pin of Arduino UNO and thus we need to read that pin in our code. Here is the final Sketch for the Arduino AnalogRead example.

  const int analog_pin = A0;
  
void setup() {
  Serial.begin(9600);
  delay(10);
}

void loop() {
  //10-bit, (0->1023)
  unsigned int analog_val = 0;
  analog_val = analogRead(analog_pin);
  Serial.println(analog_val);
  delay(1000);
}Code language: JavaScript (javascript)

C# code for handling incoming Serial Data

There are few core tasks which we need to handle before we start reading incoming data. First one is to initialize serialport with the correct port number and baudrate. After that we need to properly open the input serial port. Once port is opened, We have to attach a Event of DataReceived to the serialport before it is opened. Once attached, We are good to open the serial port and the Event will be fired if any incoming data will be at the serial buffer. Although we can set the buffer related properties as well but for the sake of simplisty let’s stick to the defaults.

Once everything is properly set up you can simple call the serialPort1.readLine() method to read the full line string present at the serial buffer. One thing to remember here is that, we are using Serial.readLine() funciton because at the arduino side we used Serial.println() function. So if you are not sending proper line break from your sender(which is the Arduino in our case), You will get readTimeOut exception.

Here is the full code for the Serial Communication in C#

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 ArduinoADCTest
{
    public partial class Form1 : Form
    {
        delegate void serialCalback(string val);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.PortName = textBox1.Text.ToString();
                    serialPort1.Open();
                    button1.Enabled = false;
                    button2.Enabled = true;
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();

                }               
               
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
            button1.Enabled = true;
            button2.Enabled = false;
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string incomSting = serialPort1.ReadLine();
            setText(incomSting);
        }

        private void setText(string val)
        {
            if (this.textBox2.InvokeRequired)
            {
                serialCalback scb = new serialCalback(setText);
                this.Invoke(scb,new object[]{val});

            }
            else
            {
                textBox2.Text = val;
            
            }                    
        }
    }
}
Code language: PHP (php)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

2 replies on “Arduino + C# Serialport ReadLine and Display on Textbox”

Hello. This doesnt work for me. textbox2.text does nothing.
Connection seems to be established.
you have a SLN file for VS 2022 please?
Thanl you

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.