I use this code to read the RFID chip SN through ftdi usb reader. I want to use the RFID SN (0DBFFC21) later in SQL queries.
My problem is that I get the SN many times splited in two rows... How should I put there a delay or something, so I can get full string everytime?
#region Namespace Inclusions
using System;
using System.IO.Ports;
using System.Windows.Forms;
#endregion
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
The correct approach may vary, but here is one simple to read data of known size:
string _buffer;
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
_buffer += port.ReadExisting(); // read into buffer
if (_buffer.Length > 7) // wait until at least 8 characters are received
{
Console.WriteLine(_buffer.Substring(0, 8)); // display
_buffer = _buffer.Substring(8, _buffer.Length - 8); // remove from buffer
}
}
if delay between packets is big enough following code may be sufficient:
_buffer += port.ReadExisting();
if (_buffer.Length >= 8)
{
Console.WriteLine(_buffer);
_buffer = null;
}