Tuesday, February 13, 2007

Serial Port Usage

I had a project assigned to me reading information from a scanner and taking the information retrieved and converting the bytes to base64 and passing the base64 to a decoder which could take a USPS barcode in PDF-417 or DataMatrix and parse out its information into human readable information of all information contained within the barcode using an IBI Dictionary. I cannot demonstrate all parts of the project but I would like to demonstrate gathering information from a port and converting it to base64. This is rather simple and probably elementary for most developers.

First of all, you must create a serial port like so:

SerialPort port = null;

On Load of Form, or constructor do the following:

port = new SerialPort(Port, 9600, Parity.None, 8, StopBits.One);
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

string Base64Scan = string.Empty;
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
byte[] buffer = new byte[port.BytesToRead];
port.Read(buffer, 0, port.BytesToRead);

// Convert to Base64
Base64Scan = Convert.ToBase64String(buffer);

This is it, now some would say why even bother with such a simple blog. The reason, I ran into a problem in the first phase of reading the information into a string using
port.ReadExisting(); which caused a problem because the .NET encodation caused the results to be wrong. When char 255 or FF was recieved, it was converted to char 63 or 3F. By reading the bytes directly, the correct results were returned. Hopefully this will help others that fall into this problem.

1 comment:

Raisa said...

Good words.

Creative Commons License
Blogged Information and Code is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.