C# SerialPort programming - Sample code for data transfer through SerialPort


1. Download and open C# project file
  1. Download source code.

    SerialPort.Sample2.zip



2. C# source code for SerialPort.Sample2
  1. Program.cs

      
    
    using System;
    using System.Text;
    
    using Microsoft.SPOT;
    using Microsoft.SPOT.Input;
    using Microsoft.SPOT.Presentation;
    using Microsoft.SPOT.Presentation.Controls;
    using Microsoft.SPOT.Hardware;
    
    using SPL.Script.Engine;
    
    namespace SPLMFConsoleWindow1
    {
        public class Program : Microsoft.SPOT.Application
        {
            public static void Main()
            {
                Program myApplication = new Program();
    
                Window mainWindow = myApplication.CreateWindow();
    
                GPIOButtonInputProvider inputProvider = new GPIOButtonInputProvider(null);
    
                myApplication.Run(mainWindow);
            }
    
            private Window mainWindow;
    
            //##########################  Sample Code  #################################
            private ConsoleWindow _consoleWindow;
    
            private System.IO.Ports.SerialPort _serialPort = null;
            //##########################################################################
    
            public Window CreateWindow()
            {
                mainWindow = new Window();
                mainWindow.Height = SystemMetrics.ScreenHeight;
                mainWindow.Width = SystemMetrics.ScreenWidth;
    
                //##########################  Sample Code  #################################
                Font font = Resources.GetFont(Resources.FontResources.small);
                _consoleWindow = new ConsoleWindow(font);
    
                mainWindow.Child = _consoleWindow;
                //##########################################################################
    
                mainWindow.AddHandler(Buttons.ButtonUpEvent, new ButtonEventHandler(OnButtonUp), false);
    
                mainWindow.Visibility = Visibility.Visible;
    
                Buttons.Focus(mainWindow);
    
                //##########################  Sample Code  #################################
                _consoleWindow.WriteLine("Please push any button!.");
                _consoleWindow.WriteLine("Select button will clear screen.");
                //##########################################################################
    
    
                //##########################  Sample Code  #################################
                _serialPort = new System.IO.Ports.SerialPort("COM2", 9600);
                _serialPort.Open();
    
                System.Threading.Thread serialReaderThread = new System.Threading.Thread(SerialPortReader);
                serialReaderThread.Start();
                //##########################################################################
    
                return mainWindow;
            }
    
            private void OnButtonUp(object sender, ButtonEventArgs e)
            {
                Debug.Print(e.Button.ToString());
    
                //##########################  Sample Code  #################################
                if (e.Button == Microsoft.SPOT.Hardware.Button.VK_SELECT)
                {
                    _consoleWindow.ClearConsole();
                }
                else if (e.Button == Microsoft.SPOT.Hardware.Button.VK_UP)
                {
                    byte[] rBuff = new byte[2];
                    int rCnt = _serialPort.Read(rBuff, 0, 2);
    
                    _consoleWindow.WriteLine("Received data is " + Util.BytesToHex(rBuff));
                }
                else if (e.Button == Microsoft.SPOT.Hardware.Button.VK_DOWN)
                {
                    byte[] wBuff = new byte[4];
                    wBuff[0] = 0x31;
                    wBuff[1] = 0x32;
                    wBuff[2] = 0x33;
                    wBuff[3] = 0x34;
    
                    _serialPort.Write(wBuff, 0, 4);
    
                    _consoleWindow.WriteLine("Serial port write");
                }
                //##########################################################################
            }
    
    
            //##########################  Sample Code  #################################
            private void SerialPortReader()
            {
                byte[] sizeBuff = new byte[4];
                byte[] readBuff = null;
                int rCnt = 0;
                uint readDataSize = 0;
    
                byte[] msgBuff = Encoding.UTF8.GetBytes("SerialPort is ready.");
                _serialPort.Write(msgBuff, 0, msgBuff.Length);
    
                while (true)
                {
                    try
                    {
                        readDataSize = 0;
    
                        rCnt = _serialPort.Read(sizeBuff, 0, 4);
    
                        if (sizeBuff[0] == 0x01 && sizeBuff[1] == 0x00)
                        {
                            readDataSize = Utility.ExtractValueFromArray(sizeBuff, 2, 2);
                        }
    
                        LogInfo("Received size is " + readDataSize.ToString());
    
                        if (readDataSize > 0)
                        {
                            readBuff = ReadSerialData((int)readDataSize);
    
                            LogInfo("Received data is " + Util.BytesToHex(readBuff));
                        }
                    }
                    catch { }
                }
            }
    
            private byte[] ReadSerialData(int buff_length)
            {
                byte[] readBuff = new byte[buff_length];
                int rCnt = _serialPort.Read(readBuff, 0, buff_length);
    
                return readBuff;
            }
    
    
            private void LogInfo(string log)
            {
                this.Dispatcher.BeginInvoke(
                    new DispatcherOperationCallback(
                        delegate(object report)
                        {
                            _consoleWindow.WriteLine(log);
                            return null;
                        }
                        ), null
                    );
            }
            //##########################################################################
        }
    }
    
    
      



3. Execute sample code
  1. Open "Properties" page of C# project.

  2. Choose ".NET Micro Framework" tab.

  3. Select "SPLMFConsoleEmulator" from the emulator list.



  4. Press "F5" key to run sample code.

  5. Click Down-Button to send data through serial port.




4. Send data of variable length from emulator
  1. Select "Emulator" tab on the emulator.

  2. Add below script on the editor.

      
    //data buff
    sendBuff= Util.CreateArrayByte(4)
    sendBuff[0] = 0x11
    sendBuff[1] = 0x22
    sendBuff[2] = 0x33
    sendBuff[3] = 0x44
    
    //size buff
    sizeBuff = Util.CreateArrayByte(4)
    sizeBuff[0] = 0x01
    sizeBuff[1] = 0x00
    sizeBuff[2] = 0x00
    sizeBuff[3] = 0x00
    
    sizeBytes = BitConverter.GetBytes(sendBuff.Length);
    sizeBuff[2] = sizeBytes[0];
    sizeBuff[3] = sizeBytes[1];
    
    COM2.Write(sizeBuff)
    
    wait 100
    
    COM2.Write(sendBuff)
    
      




  3. Press "F5" key or click "Execute Script on the Emulator".

  4. You can see below message on the ConsoleWindow.