Pages

Wednesday 4 March 2015

Integrating C#.NET with Embedded System:Chapter-5

USB RFID INTERFACE WITH C#
 
 Radio-frequency identification (RFID) is the wireless use of electromagnetic fields to transfer data, for the purposes of automatically identifying and tracking tags attached to objects. The tags contain electronically stored information. Some tags are powered byelectromagnetic induction from magnetic fields produced near the reader. Some types collect energy from the interrogating radio waves and act as a passive transponder. Other types have a local power source such as a battery and may operate at hundreds of meters from the reader. Unlike a barcode, the tag does not necessarily need to be within line of sight of the reader, and may be embedded in the tracked object. Radio frequency identification (RFID) is one method for Automatic Identification and Data Capture (AIDC).

ReadingUSB RFID data from serial port
We can use Serial port for Reading the Tag values from the RF-ID Reader. For this we need to connect the RF-ID Reader using the Serial cable to the port and use the relevant COM Port No# to the Serial port Object of C# to Connect.  

Normally the System.Net Contains the Serial Port Class and also available in the Toolbox as Serial port component for your Win Forms App 

The following code is for reading RFID data from serial port. 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;
using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.IO;



namespace com

{

publicpartialclassForm1 : Form



    {

CommManager com = newCommManager();

string RxString;

public Form1()

        {

            InitializeComponent();



        }





           }



privatevoid Form1_Load_1(object sender, EventArgs e)//when form loads setting a values.

        {

        com .SetPortNameValues(comboBox2 );

            com.Parity="None";

            com.BaudRate = "9600";

            com.StopBits="One";

            com.DataBits = "8";

            com.DisplayWindow=richTextBox1;







        }



privatevoid button1_Click(object sender, EventArgs e)

        {

            com.PortName = comboBox2.Items[comboBox2.SelectedIndex].ToString();

            com.OpenPort();

This snippet of code reads all the comport values into combobox.and opens the port for reading.



        }



    }



}


The DESIGN of FORM is shown.

 Here we made use of combobox,richtextbox for displaying RFID DATA after reading and OPEN button to open the selected comport.for above project you have to create a class for comport management, the code for this class as given below and it is common for all the serial communication interface.

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
publicclassCommManager
{

publicbool retriewResonse;
publicint signalStrength;
publicbool readRfid;
// Public rxModeBin As Boolean
//Public messag2 As String

    #region "Manager Enums"
///<summary>
/// enumeration to hold our transmission types
///</summary>
publicenumTransmissionType
    {
        Text,
        Hex
    }

publicenumRxMode
    {
        ASCII,
        Dec,

Hex,

        Bin

    }





///<summary>

/// enumeration to hold our message types

///</summary>

publicenumMessageType

    {

        Incoming,

        Outgoing,

        Normal,

        Warning,

        Error

    }

    #endregion



    #region "Manager Variables"

//property variables

privatestring _baudRate = string.Empty;

privatestring _parity = string.Empty;

privatestring _stopBits = string.Empty;

privatestring _dataBits = string.Empty;

privatestring _portName = string.Empty;

privateTransmissionType _transType;

privateRxMode rx_Mode;

privateRichTextBox _displayWindow;

privateProgressBar strngthbar;



privateTextBox rfidText;

privateLabel sgnStrLbl;

privatestring _msg = string.Empty;

privateMessageType _type;

//global manager variables

privateColor[] MessageColor = {

              Color.Blue,

              Color.Green,

              Color.Black,

              Color.Orange,

              Color.Red

       };

privateSerialPort comPort = newSerialPort();

    #endregion

privatebool write = true;



    #region "Manager Properties"

///<summary>

/// Property to hold the BaudRate

/// of our manager class

///</summary>

publicstring BaudRate

    {
         
get { return _baudRate; }

set { _baudRate = value; }

    }



///<summary>

/// property to hold the Parity

/// of our manager class

///</summary>

publicstring Parity

    {

get { return _parity; }

set { _parity = value; }

    }



///<summary>

/// property to hold the StopBits

/// of our manager class

///</summary>

publicstring StopBits

    {

get { return _stopBits; }

set { _stopBits = value; }

    }



///<summary>

/// property to hold the DataBits

/// of our manager class

///</summary>

publicstring DataBits

    {

get { return _dataBits; }

set { _dataBits = value; }

    }



///<summary>

/// property to hold the PortName

/// of our manager class

///</summary>

publicstring PortName

    {

get { return _portName; }

set { _portName = value; }

    }



///<summary>

/// property to hold our TransmissionType

/// of our manager class

///</summary>

publicTransmissionType CurrentTransmissionType

    {

get { return _transType; }

set { _transType = value; }

    }

///<summary>
/// property to hold our display window
/// value
///</summary>
publicRichTextBox DisplayWindow
    {
get { return _displayWindow; }
set { _displayWindow = value; }
    }


publicRxMode Current_rxMode
    {
get { return rx_Mode; }
set { rx_Mode = value; }
    }

publicTextBox rfidDisplay
    {

get { return rfidText; }
set { rfidText = value; }
    }

/// Property to hold the message being sent
/// through the serial port
> 
publicstring Message
    {
get { return _msg; }
set { _msg = value; }
    }

publicMessageType Type
    {
get { return _type; }
set { _type = value; }
    }

publicProgressBar SignalStrengthBar
    {

get { return strngthbar; }
set { strngthbar = value; }
    }
    #endregion
publicLabel SignalStrengthLbl
    {
  
     get { return sgnStrLbl; }
     set { sgnStrLbl = value; }

}



    #region "Manager Constructors"

///<summary>

/// Constructor to set the properties of our Manager Class

///</summary>

///<param name="baud">Desired BaudRate</param>

///<param name="par">Desired Parity</param>

///<param name="sBits">Desired StopBits</param>

///<param name="dBits">Desired DataBits</param>

///<param name="name">Desired PortName</param>

public CommManager(string baud, string par, string sBits, string dBits, string name, RichTextBox rtb)

    {

        _baudRate = baud;

        _parity = par;

        _stopBits = sBits;

        _dataBits = dBits;

        _portName = name;

        _displayWindow = rtb;

//now add an event handler

        comPort.DataReceived += comPort_DataReceived;

    }



///<summary>

/// Comstructor to set the properties of our

/// serial port communicator to nothing

///</summary>

public CommManager()

    {

        _baudRate = string.Empty;

       _parity = string.Empty;

       _stopBits = string.Empty;

       _dataBits = string.Empty;

       _portName = "COM1";

       _displayWindow = null;

//add event handler

        comPort.DataReceived += comPort_DataReceived;

    }

public CommManager(refProgressBar strngthBar)

    {

        _baudRate = string.Empty;

        _parity = string.Empty;

        _stopBits = string.Empty;

        _dataBits = string.Empty;

        _portName = "COM1";

        _displayWindow = null;

//add event handler

        comPort.DataReceived += comPort_DataReceived;

    }

    #endregion



    #region "WriteData"

publicvoid WriteData(string msg)

    {



try

        {

switch (CurrentTransmissionType)

            {

caseTransmissionType.Text:

//first make sure the port is open

//if its not open then open it

if (!(comPort.IsOpen == true))

                    {

                        comPort.Open();

                    }

//send the message to the port

                    comPort.Write(msg);



//display the message

                    _type = MessageType.Outgoing;

//+ "" + Environment.NewLine + ""

                    _msg = msg;

                    DisplayData(_type, _msg);

break; // TODO: might not be correct. Was : Exit Select



break;

caseTransmissionType.Hex:

try

                    {

//convert the message to byte array

byte[] newMsg = HexToByte(msg);

if (!write)

                        {

                            DisplayData(_type, _msg);

return;

                        }

//send the message to the port

                        comPort.Write(newMsg, 0, newMsg.Length);

//convert back to hex and display

                        _type = MessageType.Outgoing;

//  + "" + Environment.NewLine + ""

                        _msg = ByteToHex(newMsg);

                        DisplayData(_type, _msg);

                    }

catch (FormatException ex)

                    {

//display error message

                        _type = MessageType.Error;

                        _msg = ex.Message + "" + Environment.NewLine + "";

                        DisplayData(_type, _msg);

                    }

finally

                    {

_displayWindow.SelectAll();

                    }



break; // TODO: might not be correct. Was : Exit Select



break;

default:

//first make sure the port is open

//if its not open then open it

if (!(comPort.IsOpen == true))

                    {

                        comPort.Open();

                    }

//send the message to the port

                    comPort.Write(msg);



//display the message

                    _type = MessageType.Outgoing;

//+ "" + Environment.NewLine + ""

                    _msg = msg;

                    DisplayData(MessageType.Outgoing, _msg);

break; // TODO: might not be correct. Was : Exit Select



break;

            }



        }

catch (Exception ex)

        {

        }



    }

    #endregion



    #region "HexToByte"

///<summary>

/// method to convert hex string into a byte array

///</summary>

///<param name="msg">string to convert</param>

///<returns>a byte array</returns>

privatebyte[] HexToByte(string msg)

    {

if (msg.Length % 2 == 0)

        {

//remove any spaces from the string

            _msg = msg;

            _msg = msg.Replace(" ", "");

//create a byte array the length of the

//divided by 2 (Hex is 2 characters in length)

byte[] comBuffer = newbyte[_msg.Length / 2];

for (int i = 0; i <= _msg.Length - 1; i += 2)

            {

_displayWindow.SelectAll();

                    }



break; // TODO: might not be correct. Was : Exit Select



break;

default:

//first make sure the port is open

//if its not open then open it

if (!(comPort.IsOpen == true))

                    {

                        comPort.Open();

                    }

//send the message to the port

                    comPort.Write(msg);



//display the message

                    _type = MessageType.Outgoing;

//+ "" + Environment.NewLine + ""

                    _msg = msg;

                    DisplayData(MessageType.Outgoing, _msg);

break; // TODO: might not be correct. Was : Exit Select



break;

            }



        }

catch (Exception ex)

        {

        }



    }

    #endregion



    #region "HexToByte"

///<summary>

/// method to convert hex string into a byte array

///</summary>

///<param name="msg">string to convert</param>

///<returns>a byte array</returns>

privatebyte[] HexToByte(string msg)

    {

if (msg.Length % 2 == 0)

        {

//remove any spaces from the string

            _msg = msg;

            _msg = msg.Replace(" ", "");

//create a byte array the length of the

//divided by 2 (Hex is 2 characters in length)

byte[] comBuffer = newbyte[_msg.Length / 2];

for (int i = 0; i <= _msg.Length - 1; i += 2)

            {
                comBuffer[i / 2] = Convert.ToByte(Convert.ToByte(_msg.Substring(i, 2), 16));

            }

            write = true;

//loop through the length of the provided string

//convert each set of 2 characters to a byte

//and add to the array

//return the array

return comBuffer;

        }

else

        {

            _msg = "Invalid format";

            _type = MessageType.Error;

// DisplayData(_Type, _msg)

            write = false;

returnnull;

        }

    }

    #endregion



    #region "ByteToHex"

///<summary>

/// method to convert a byte array into a hex string

///</summary>

///<param name="comByte">byte array to convert</param>

///<returns>a hex string</returns>

privatestring ByteToHex(byte[] comByte)

    {

//create a new StringBuilder object

StringBuilder builder = newStringBuilder(comByte.Length * 3);

//loop through each byte in the array

foreach (byte data in comByte)
{
            builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));

//convert the byte to a string and add to the stringbuilder

        }

//return the converted value

return builder.ToString().ToUpper();

    }

    #endregion



    #region "DisplayData"

///<summary>

/// Method to display the data to and

/// from the port on the screen

///</summary>

///<remarks></remarks>

    [STAThread()]

privatevoid DisplayData(MessageType type, string msg)

    {

        _displayWindow.Invoke(newEventHandler(DoDisplay));

    }

      
#endregion

    #region "OpenPort"
publicbool OpenPort()
    {
try
        {
//first check if the port is already open
//if its open then close it
if (comPort.IsOpen == true)
            {
                comPort.Close();
            }

//set the properties of our SerialPort Object
            comPort.BaudRate = int.Parse(_baudRate);
//BaudRate
            comPort.DataBits = int.Parse(_dataBits);
//DataBits
            comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits);
//StopBits
            comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity);
//Parity
            comPort.PortName = _portName;
//PortName
//now open the port
            comPort.Open();
//display message
            _type = MessageType.Normal;
            _msg = "Port opened at " + DateTime.Now + "" + Environment.NewLine + "";
//MessageBox.Show("opened");
            DisplayData(_type, _msg);
//return true
returntrue;
        }
catch (Exception ex)
        {
MessageBox.Show(ex.Message);
            DisplayData(MessageType.Error, ex.Message);
returnfalse;
        }
    }
    #endregion

    #region " ClosePort "
publicvoid ClosePort()
    {
if (comPort.IsOpen)
        {
            _msg = "Port closed at " + DateTime.Now + "" + Environment.NewLine + "";
            _type = MessageType.Normal;
            DisplayData(_type, _msg);
            comPort.Close();

}

    }   

    #endregion

    #region "SetParityValues"

publicvoid SetParityValues(object obj)

    {

foreach (string str inEnum.GetNames(typeof(Parity)))

        {

            ((ComboBox)obj).Items.Add(str);

        }

    }

    #endregion



    #region "SetStopBitValues"

publicvoid SetStopBitValues(object obj)

    {

foreach (string str inEnum.GetNames(typeof(StopBits)))

        {

            ((ComboBox)obj).Items.Add(str);

        }

    }

    #endregion



    #region "SetPortNameValues"



publicvoid SetPortNameValues(object obj)

    {

foreach (string str inSerialPort.GetPortNames())

        {

            ((ComboBox)obj).Items.Add(str);

        }

    }

    #endregion



    #region "comPort_DataReceived"

///<summary>

/// method that will be called when theres data waiting in the buffer

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

privatevoid comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

    {

//determine the mode the user selected (binary/string)

switch (CurrentTransmissionType)

        {

caseTransmissionType.Text:

//user chose string

//read data waiting in the buffer

string msg = comPort.ReadExisting();





//MessageBox.Show(msg)

try

                {



                }

catch (Exception ex)

                {

                }



//display the data to the user

                _type = MessageType.Incoming;

                _msg = msg;

                DisplayData(MessageType.Incoming, msg + "" + Environment.NewLine + "");

break; // TODO: might not be correct. Was : Exit Select



break;

caseTransmissionType.Hex:

//user chose binary

//retrieve number of bytes in the buffer

int bytes = comPort.BytesToRead;

//create a byte array to hold the awaiting data

byte[] comBuffer = newbyte[bytes];

//read the data and store it

                comPort.Read(comBuffer, 0, bytes);

//display the data to the user

                _type = MessageType.Incoming;

                _msg = ByteToHex(comBuffer) + "" + Environment.NewLine + "";

                DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "" + Environment.NewLine + "");

break; // TODO: might not be correct. Was : Exit Select



break;

default:

//read data waiting in the buffer

string str = comPort.ReadExisting();



try

                {





                }

catch (Exception ex)

                {

                }



//display the data to the user

                _type = MessageType.Incoming;



                _msg = str + "" + Environment.NewLine + "";

                DisplayData(MessageType.Incoming, str + "" + Environment.NewLine + "");

break; // TODO: might not be correct. Was : Exit Select



break;

        }

}

    #endregion



    #region "DoDisplay"

privatevoid DoDisplay(object sender, EventArgs e)

    {

        _displayWindow.SelectedText = string.Empty;

        _displayWindow.SelectionFont = newFont(_displayWindow.SelectionFont, FontStyle.Bold);

        _displayWindow.SelectionColor = MessageColor[Convert.ToInt32(_type)];



        _displayWindow.AppendText(_msg);



        _displayWindow.ScrollToCaret();

    }

    #endregion







publicstring Remove(string value, string rmv)

    {

int pos = value.IndexOf(rmv);



if (pos >= 0)

        {

return value.Remove(pos, rmv.Length);

        }



return value;

    }



}

Output: