Arnoldo B. Canales

C# Program interacting with Arduino Mega 2560 Microcontroller.

Figure 1: Arduino Mega 2560 plugged to a buzzer using a breadboard.

The idea of this simple project is to create a "Communications Routine" that will allow me to interact with not only the Mega 2560 but also the Arduino UNO and the ESP32 boards so bear with me and let see how far I can get with this project.

These are pretty simple routines, on both ends, C# and Arduino, but that is what I want, start simple and grow as I keep building more and more complex iterations. So as you can see in the code below, the Mega 2560 expects four (4) bytes as initial communications parameters, so the idea is to send, using a C# program, an encoded message (see Table 1 below) using these four bytes. The controller routine is expecting these four bytes and it is designed to act upon these commands with an specific set of tasks.

Table 1: Commands table

Byte 0 Byte 1 Byte 2 Byte 3 Comments
0 0 0 0 Do Nothing
1 1 1 1 Tell me your ID
1 2 0 0 Do Nothing
1 3 0 0 Do Nothing
1 4 7 0 Sound Buzzer 1
1 4 8 0 Sound Buzzer 2
1 4 9 0 Sound Buzzer 3

When I want to query the controller for its ID, I will be sending the command "1,1,1,1" (four 1's), when I want to sound buzzer #1, I will be sending command "1,4,7,0", and so on and so forth. After the command is sent, I wait for a few milliseconds waiting for the answer.

The code below shows the Arduino Mega 2560 Simple Communications Routine.


//------------------------------------------------------------------------
//  Basic Communication Framework
//  Routine to communicate with the Arduino Mega 2560 Controller.
//  June 18, 2018
//------------------------------------------------------------------------
#include <stdio.h>
//
//Memory variables
//
//Assigning Name to Controller Board
String xCntrlrName = "A1";
//
//Buzzer plugged at Controller's pin 13.
const int xBuzzerPin = 13;
//
//Variables to talk to the Master Computer via USB port
byte cmdByte0;
byte cmdByte1;
byte cmdByte2;
byte cmdByte3;
//
//------------------------------------------------------------------------
// Routine: setup() - Main Setup.
// 
//------------------------------------------------------------------------
void setup() 
{
  //
  pinMode(xBuzzerPin,OUTPUT);   //initialize the buzzer pin as an output
  //
  // Activate serial monitor to send/receive communications using 9600 bauds
  Serial.begin(9600);
}
//
//------------------------------------------------------------------------
// Routine: loop() - Main Loop.
// 
//------------------------------------------------------------------------
void loop() 
{
  if (Serial.available() > 2) //Read data to bytes
  {
    cmdByte0 = Serial.read();    delay(10); 
    cmdByte1 = Serial.read();    delay(10); 
    cmdByte2 = Serial.read();    delay(10); 
    cmdByte3 = Serial.read();    delay(10); 
  }
  // 
  if(cmdByte0 == 1)          // First byte is equal to "1", then someone maybe talking to Arduino,
  { 
    if(cmdByte1 == 1)        // Second byte is equal to "1".
    { 
      if(cmdByte2 == 1)      // Third byte is equal to "1".
      {
        if(cmdByte3 == 1)    // Forth byte is equal to "1", tell me your ID!
        {
          Serial.print(xCntrlrName);
        }
      }   
    }
    //
    //..
    if(cmdByte1 == 2) {    }
    if(cmdByte1 == 3) {    }
    //..
    //
    if(cmdByte1 == 4)       // Second byte is equal to "4".
    {    
      if(cmdByte2 == 7)     // Third byte is equal to "7".
      {
          buzzerX(10);
          Serial.print("1st command");
      }
      if(cmdByte2 == 8)     // Third byte is equal to "8".
      {
          buzzerX(10);
          Serial.print("2nd. command");
      }
      if(cmdByte2 == 9)     // Third byte is equal to "9".
      {
          buzzerX(10);
          Serial.print("3rd. command.");
      }      
    }
  }
  //Reset bytes to zero.
  cmdByte0 = 0;
  cmdByte1 = 0;
  cmdByte2 = 0;
  cmdByte3 = 0;    
}
//
//-------------------------------------------------------------------------------
// buzzerX Routine
//-------------------------------------------------------------------------------
void buzzerX(int xDuration)
{
  for(int i=0; i < xDuration; i++)
  {
     digitalWrite(xBuzzerPin,HIGH);
     delay(5);//wait for 5ms
     digitalWrite(xBuzzerPin,LOW);
     delay(5);//wait for 5ms
  }
}

  					

Below you can see the C# Program - Simple Communications Routine.


using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace CS_Comm
{
    public partial class Form1 : Form
    {
        public string xCntrllerName1 = "A1";
        public string PCPort1;
        static SerialPort ControllerPort;
        DataTable xDataStream;
        //
        public Form1(){InitializeComponent();}
        //
        //----------------------------------------------------------------------
        //
        //Load Form - Form1_Load
        //
        //----------------------------------------------------------------------
        private void Form1_Load(object sender, EventArgs e)
        {
            if (HandShake(9600, xCntrllerName1, 1, 1, 1, 1))
            {
                lblControllerName1.Text = xCntrllerName1 + " @ " + PCPort1;
                lblMessages.Text = "Connection Successful - Connected via " + PCPort1 + " to board " + xCntrllerName1 + ".";
                btnCommand1.Enabled = true;
                btnCommand2.Enabled = true;
                btnCommand3.Enabled = true;
            }
            else
            {
                lblMessages.Text = "Error with connection....";
            }
            //
            xDataStream = CreateTable0();
            dataGridView0.DataSource = xDataStream;
            Format_dgv0(dataGridView0);
        }
        //
        //----------------------------------------------------------------------
        //
        // DataGrid connected to a DataTable - Create Table0 for Data Stream DataGridView
        //
        //----------------------------------------------------------------------
        //
        public DataTable CreateTable0()
        {
            DataTable xTable = new DataTable();
            xTable.Columns.Add("ReturnInfo", typeof(byte));
            return xTable;
        }
        //
        //----------------------------------------------------------------------
        //
        //Format DatagridView0 - This DataGridView stores the Data Stream
        //
        //----------------------------------------------------------------------
        //
        public void Format_dgv0(DataGridView pdgv)
        {
            //dataGridView Formatting
            dataGridView0.Columns[0].Width = 90;
            dataGridView0.Columns[0].HeaderText = "Data returned";
            //
            dataGridView0.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
            foreach (DataGridViewColumn col in dataGridView0.Columns)
            {
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
                col.DefaultCellStyle.Font = new Font("Calibri", 8, FontStyle.Regular);
                col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
            }
        }
        //
        //----------------------------------------------------------------------
        //
        //Handshake with Controller - Identify Com Port and Establish connection.
        //
        //----------------------------------------------------------------------
        public Boolean HandShake(int bauds, string passCode, byte parameter1, byte parameter2, byte parameter3, byte parameter4)
        {
            try
            {
                byte[] parameters_buffer = new byte[4];
                parameters_buffer[0] = Convert.ToByte(parameter1);
                parameters_buffer[1] = Convert.ToByte(parameter2);
                parameters_buffer[2] = Convert.ToByte(parameter3);
                parameters_buffer[3] = Convert.ToByte(parameter4);
                //
                int intReturnValue = 0;
                byte byteReturnValue = 0;
                string returned_passCode = "";
                int parameters_Read = 0;
                //
                string[] ports = SerialPort.GetPortNames();
                foreach (string nextPort in ports)
                {
                    ControllerPort = new SerialPort(nextPort, bauds);
                    ControllerPort.Open();
                    ControllerPort.Write(parameters_buffer, 0, 4);
                    Thread.Sleep(200);
                    //
                    returned_passCode = "";
                    //
                    parameters_Read = ControllerPort.BytesToRead;
                    while (parameters_Read > 0)
                    {
                        byteReturnValue = (byte)ControllerPort.ReadByte();
                        intReturnValue = (int)byteReturnValue;
                        //
                        returned_passCode = returned_passCode + Convert.ToChar(intReturnValue);
                        parameters_Read--;
                    }
                    ControllerPort.Close();
                    //
                    PCPort1 = nextPort;
                    //
                    if (returned_passCode.Contains(passCode)) return true;
                }
                return false;
            }
            catch (Exception e){ MessageBox.Show("Error Message at HandShake: " + e); return false; }
        }
        //
        //----------------------------------------------------------------------
        //
        //Given an order to Controller and get an answer back 
        //
        //----------------------------------------------------------------------
        //
        public string comm_message(byte par_1, byte par_2, byte par_3, byte par_4)
        {
            try
            {
                byte[] parameters_buffer = new byte[4];
                parameters_buffer[0] = Convert.ToByte(par_1);
                parameters_buffer[1] = Convert.ToByte(par_2);
                parameters_buffer[2] = Convert.ToByte(par_3);
                parameters_buffer[3] = Convert.ToByte(par_4);
                //
                ControllerPort.Open();
                ControllerPort.Write(parameters_buffer, 0, 4);
                Thread.Sleep(200);
                //
                xDataStream.Clear();
                //
                int intReturnValue = 0;
                byte byteReturnValue = 0;
                char charReturnValue = (Char)intReturnValue;
                string returned_MessageAsIs = "";
                //
                int parameters_Read = ControllerPort.BytesToRead;
                txtNumOfChars.Text = parameters_Read.ToString();
                while (parameters_Read > 0)
                {
                    //Read data from Comm Port
                    byteReturnValue = (byte)ControllerPort.ReadByte();  //Read data from Comm Port
                    //Read data from Comm Port
                    //
                    intReturnValue = (int)byteReturnValue;
                    xDataStream.Rows.Add(byteReturnValue);
                    //
                    //if ((intReturnValue >= 48 && intReturnValue <= 57)  || 
                    //    (intReturnValue >= 65 && intReturnValue <= 90)  || 
                    //    (intReturnValue >= 97 && intReturnValue <= 122) || 
                    //    (intReturnValue == 32) || (intReturnValue == 46)) 
                    //{
                        //Save incoming message "as it comes in"
                        returned_MessageAsIs = returned_MessageAsIs + Convert.ToChar(intReturnValue);
                    //}
                    parameters_Read--;
                }
                ControllerPort.Close();
                //
                return returned_MessageAsIs;
            }
            catch (Exception e){ MessageBox.Show("Error Message at comm_message : " + e); return "Invalid Exception!"; }
        }
        //
        //----------------------------------------------------------------------
        //
        //Buttons
        //
        //----------------------------------------------------------------------
        //
        private void btnCommand1_Click(object sender, EventArgs e)
        {
            String Msg = comm_message(1, 4, 7, 0);
            txtCommand1.Text = Msg;
            txtCommand2.Text = "";
            txtCommand3.Text = "";
        }
        //
        private void btnCommand2_Click(object sender, EventArgs e)
        {
            String Msg = comm_message(1, 4, 8, 0);
            txtCommand1.Text = "";
            txtCommand2.Text = Msg;
            txtCommand3.Text = "";           
        }
        //
        private void btnCommand3_Click(object sender, EventArgs e)
        {
            String Msg = comm_message(1, 4, 9, 0);
            txtCommand1.Text = "";
            txtCommand2.Text = "";
            txtCommand3.Text = Msg;
        }
    }
}

  					

VIDEOS

 

Video: C# --- Mega 2560 interface.

 

Video: Controller Mega 2560 playing the buzzer