miércoles, 27 de julio de 2011

Serial Port Communication using C#


Today we'll see a very simple example of how to open a serial port , using C# and Visual Studio 2010. The example is a console program, so you won't be seeing nice user interface. It's very easy to open a serial communication, first of all, we must define which serial device we want to interact with, by example let's say we want to talk via a serial port with an Arduino board. Now, we need to define communication settings such as:
·         Baud Rate
·         Parity
·         Bit Format
·         Stop Bits
·         Port Name
Let's say we want our Baud Rate to be 9600 bps, none parity, 8-bit format, 1 stop bit. Port name is always assigned by the host computer, the name has always this format : "COMn", where "n" is the port number, automatically assigned by our computer. Because of this, it's possibly to find several serial ports assigned by our computer. So, our program will first check out all available serial ports, and let us choose which to open.  After opening the port we will be able to send text to it, just by writing our message in the console, while doing this our program can asynchronously receive data from or serial device.
The code is as follows:
//Made by Henry Serrano 27/7/2011
//You can use/modify the code in any way you like,
//just remember to share it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports; //required for SerialPort class

namespace SerialPortCommunicationExample
{
    class Program
    {
        static SerialPort port1;
        static Boolean portstate = false;

        static void Main(string[] args)
        {
            Console.WriteLine("SerialPort Communication Example\n");
            Console.WriteLine("Open a port communication,");
            Console.WriteLine("then, start sending or receiving messages\n");

            chooseSerialPort();
            while (portstate == true)
            {
                port1.WriteLine(Console.ReadLine());
            }
            Console.ReadLine();
        }

        static void chooseSerialPort()
        {
            //store all available port names
            string[] ports = SerialPort.GetPortNames();
            int i = 1;

            Console.WriteLine("Choose Serial Port");
            foreach (string portname in ports)
            {
                //write all available port names
                Console.WriteLine(i.ToString() + " " + portname);
                i++;
            }

            Console.WriteLine("\nWrite number corresponding to SerialPort");

            i = Convert.ToInt16(Console.ReadLine());

            try
            {
                //create serial port as configured below
                //BaudRate = 9600 bps, Parity:None, 8-bit data, 1 Stop-bit
                port1 = new SerialPort(ports[i - 1], 9600, Parity.None, 8, StopBits.One);

                //create asynchronous event(it's a secondary threat of the main program)
                //will activate every time our serial device sends data to computer
                port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);
                //finally open port
                port1.Open();
                portstate = true;
                Console.WriteLine(ports[i-1] + " is now open");
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to open Port");
            }
           
        }

        static void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine("Received: " + port1.ReadLine());
        }
    }

This is a functional Arduino code for using with this program:
//Made by Henry Serrano 27/7/2011
//You can use/modify the code in any way you like,
//just remember to share it

const int buffersize = 64;
unsigned char buffer[buffersize]; //64 character buffer

void setup(){
  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    int i = 0;
    unsigned char data = 0;
     while(Serial.available() > 0){
       data = Serial.read();
       if(i < buffersize){
        buffer[i] = data; //put all data into buffer until if fills
        i++;
       }
     }
     for(int j = 0; j < i; j++){
       Serial.print(buffer[j]); //print buffer characters
     }
  }
  //delay(10);
}
Code is considerably commented, I'll add here the full project for download. I'll also add the Arduino sketch for quickly use with this program. It's considerably easy and recommended to optimize this code for your personal goals.

2 comentarios:

  1. Jajaja excelente!! Estaba buscando un ejemplo que pudiera entender!!

    ResponderEliminar
  2. This blog awesome and i learn a lot about programming from here.The best thing about this blog is that you doing from beginning to experts level.

    Love from Pprogramming

    ResponderEliminar