Home > Arduino > C# App: Code For App

C# App: Code For App


I see there have been alot of visits to the C# app post, and as I am not able to upload the application to the site, I have now dumped all the code below.

You need to create a SerialPort object which will let you connect to your Arduino. You initialize it using the COM port the Arduino is using as well as setting the baud rate (The speed at which the Arduino will communicate). These are selectable via drop down’s on the form to make it easier to switch. You also attach an event handler to listen for serial data coming from the Arduino and to respond accordingly. The code was done in Visual Studio 2010, and is a fit for purpose quick code project. It does it’s job to just send and receive serial data. 
The form has the following objects attached to it.

private System.Windows.Forms.ComboBox cmbComPorts;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox cmbBaudRate;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.TextBox txtInput;
        public System.Windows.Forms.TextBox txtReceive;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Button btnOpenPort;
        private System.Windows.Forms.Button btnClosePort;

The Code for the app is below

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;
using System.IO.Ports;

namespace SerialTestApp
{
    public partial class frmSerialMain : Form
    {
        SerialPort serialPort = new SerialPort();

        public frmSerialMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadComPorts();
        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            if (OpenPortConnection())
            {
                btnSend.Enabled = Boolean.Parse("True");
                txtInput.Enabled = Boolean.Parse("True");
                btnOpenPort.Enabled = Boolean.Parse("False");
                btnClosePort.Enabled = Boolean.Parse("True");
                cmbBaudRate.Enabled = Boolean.Parse("False");
                cmbComPorts.Enabled = Boolean.Parse("False");
                txtReceive.Text += "\r\nPort Activated";
                ScollToBottom();
            }
        }

        private void btnClosePort_Click(object sender, EventArgs e)
        {
            if (ClosePortConnection())
            {
                btnSend.Enabled = Boolean.Parse("False");
                txtInput.Enabled = Boolean.Parse("False");
                btnOpenPort.Enabled = Boolean.Parse("True");
                btnClosePort.Enabled = Boolean.Parse("False");
                cmbBaudRate.Enabled = Boolean.Parse("True");
                cmbComPorts.Enabled = Boolean.Parse("True");
                txtReceive.Text += "\r\nPort Closed";
                ScollToBottom();
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtInput.Text.Length > 0)
                {
                    serialPort.Write(txtInput.Text);
                    txtReceive.Text += String.Format("\r\n >>>>:{0}", txtInput.Text);
                    ScollToBottom();
                    txtInput.Text = "";
                    txtInput.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK);
            }
        }

        private void DataReceviedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string strIndata = sp.ReadLine();
                txtReceive.Text += String.Format("\r\n<<:{0}", strIndata.ToString());
                ScollToBottom();
            }
            catch
            {
                MessageBox.Show("Error with Serial Event Handler, cannot listen for data", "Error", MessageBoxButtons.OK);
            }
        }

        void LoadComPorts()
        {
            //Load the available Com Ports
            string[] portarray = new string[10]; //create an array of strings
            portarray = SerialPort.GetPortNames(); //Get all port names
            for (int i = 0; i < portarray.Length; i++) //foreach com port
            {
                cmbComPorts.Items.Add(portarray[i].ToString());
                //Console.WriteLine("Com Port: {0}", portarray[i].ToString()); //output the com port
            }
            cmbComPorts.Sorted = Boolean.Parse("True");
        }

        bool OpenPortConnection()
        {
            bool successFlag = true;

            //set baud rate
            try
            {
                if (serialPort.IsOpen) serialPort.Close(); //if the port is already open, close it
                serialPort.BaudRate = Convert.ToInt16(cmbBaudRate.SelectedItem.ToString()); // set baud rate
            }
            catch
            {
                MessageBox.Show("Error setting Baud Rate. Please check rate", "ERROR", MessageBoxButtons.OK);
                successFlag = false;
            }

            //Try to open the port.
            try
            {
                if (serialPort.IsOpen) serialPort.Close(); //if the port is already open, close it
                serialPort.PortName = cmbComPorts.SelectedItem.ToString(); //Get Port Name and set it.
                serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceviedHandler);
                serialPort.Open(); //Open Port.
            }
            catch
            {
                MessageBox.Show("Error opening Port. Please check if a Port was selected.", "ERROR", MessageBoxButtons.OK);
                successFlag = false;
            }

            return successFlag;
        }

        bool ClosePortConnection()
        {
            bool successFlag = true;

            //Try to close the port.
            try
            {
                if (serialPort.IsOpen)
                    serialPort.Close(); //Close Port.
            }
            catch
            {
                MessageBox.Show("Error Closing Port. Please restart Application.", "ERROR", MessageBoxButtons.OK);
                successFlag = false;
            }

            return successFlag;
        }

        private void ScollToBottom()
        {
            txtReceive.SelectionStart = txtReceive.Text.Length;
            txtReceive.ScrollToCaret();
        }
    }
}
Advertisements
Categories: Arduino
  1. August 11, 2011 at 19:53

    Where did you buy your Arduino?

  2. August 11, 2011 at 19:53

    I should have added in Cape Town.

  3. fahad
    July 9, 2015 at 00:19

    it is not sending and receiving data 😦

    • July 16, 2015 at 14:32

      Hi Fahad,

      Is it connected on the right port?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: