Windows C# app Arduino control over serial port

Windows app C# Arduino control over serial port
Share:

About

In this tutorial, we will be using Visual Studio to make a C# Windows Forms Application. The app will communicate with the Arduino over a serial port. The Arduino will be programmed to turn on or off an LED based on what it receives from the App. 

Hardware Used

Windows App

Open up visual studio and create a new wfa(windows frorms application) project.

Add two buttons, set the text of one to ON and the other to OFF.

Add two buttons, set the text of one to ON and the other to OFF. In the properties window find the name property and rename the on button to onButton. Do the same thing for the off button(writing off instead of on of course).
Next, double click on the on button to make an event handler for it. Do the same for the off button. Whenever the button gets clicked the code inside the event handler will get executed.
Insert this code into the event handlers(for the off button change the Write() parameter from “1” to “0”):
//Setup port by providing the port name and baud rate.
SerialPort sp = new SerialPort("COM6", 9600);
//Open port.
sp.Open();
//Write to port.
sp.Write("1");
//Close port.
sp.Close();
As of right now just replace the “COM6” with the name of whatever port your Arduino is currently connected to. Later on, we’ll implement a dropdown to choose a port from.
There will be an error saying that SerialPort couldn’t be found. To fix it include the serial port namespace. Just press Ctrl + . and select using System.IO.Ports. This using System.IO.Ports; line will be added  to the top of your file and all the errors should be gone.
This should all work but it’s a really good idea to implement exception handling when dealing with serial ports. For example, if the port isn’t available or doesn’t exist our application will throw an exception. If left unhandled the exception will crash the app, to prevent this we need to handle the exception and give the user a message saying we couldn’t connect to the port.
Here’s the full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ArduinoControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void onButton_Click(object sender, EventArgs e)
        {
            try
            {
                SerialPort sp = new SerialPort("COM6", 9600);
                sp.Open();
                sp.Write("1");
                sp.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void offButton_Click(object sender, EventArgs e)
        {
            try
            {
                SerialPort sp = new SerialPort("COM6", 9600);
                sp.Open();
                sp.Write("0");
                sp.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

The Arduino Part

Hardware

Connect the LED from PIN 13 to GND.

Software

The Arduino code is very simple. First, we declare pin 13 as an output and begin serial communication at a baud rate of 9600. In the loop, we read the serial data and check whether a 1 or a 0 was received. If one is received the output gets turned on else it gets turned off.
int ledPin = 13;

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

void loop()
{
  char ch;
  while(Serial.available() > 0) 
  {
    ch = Serial.read();

  	if (ch == '1')
  	{
  		digitalWrite(ledPin, HIGH);
  	}
  	else if (ch == '0')
  	{
  		digitalWrite(ledPin, LOW);
  	}
  }
}

Result

Improvements

Right now the COM port is hardcoded so it has to be changed in the code every time. I did this for demonstration purposes as it’s the simplest way(and not the best way) to make a connection. Instead, we should be able to get all the available ports in a dropdown menu and select the one we want to connect to.
Update the GUI by adding a connect/disconnect button and adding a dropdown menu/combo box.
And update the code like so.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ArduinoControl
{
    public partial class Form1 : Form
    {
        bool connected = false;
        SerialPort sp;
        public Form1()
        {
            InitializeComponent();
            var ports = SerialPort.GetPortNames();
            portComboBox.DataSource = ports;
        }

        private void onButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (connected)
                {
                    sp.Write("1");
                }
                else
                {
                    MessageBox.Show("Connect to a port before sending");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void offButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (connected)
                {
                    sp.Write("0");
                }
                else
                {
                    MessageBox.Show("Connect to a port before sending");
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void connectButton_Click(object sender, EventArgs e)
        {
            try
            {
               
                sp = new SerialPort(portComboBox.SelectedItem.ToString(), 9600);

                if (!connected)
                {
                    sp.Open();
                    connected = true;

                    MessageBox.Show("Serial port connected.");
                }
                else
                {
                    sp.Close();
                    sp.Dispose();

                    connected = false;

                    MessageBox.Show("Serial port disconnected.");
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger