.NET SerialPort DataReceived event thread interference with main thread

Posted by Kiran on Stack Overflow See other posts from Stack Overflow or by Kiran
Published on 2010-12-22T00:56:49Z Indexed on 2010/12/22 1:54 UTC
Read the original article Hit count: 485

Filed under:
|
|

I am writing a serial communication program using the SerialPort class in C# to interact with a strip machine connected via a RS232 cable. When i send the command to the machine it responds with some bytes depending on the command. Like when i send a "\D" command, i am expecting to download the machine program data of 180 bytes as a continous string. As per the machine's manual, it suggests as a best practice to send an unreognized characters like comma (,) character to make sure the machine is initialized before sending the first command in the cycle. My serial communication code is as follows:

public class SerialHelper
{
    SerialPort commPort = null;
    string currentReceived = string.Empty;
    string receivedStr = string.Empty;
    private bool CommInitialized()
    {
        try
        {
            commPort = new SerialPort();
            commPort.PortName = "COM1";
            if (!commPort.IsOpen)
                commPort.Open();
            commPort.BaudRate = 9600;
            commPort.Parity = System.IO.Ports.Parity.None;
            commPort.StopBits = StopBits.One;
            commPort.DataBits = 8;
            commPort.RtsEnable = true;
            commPort.DtrEnable = true;

            commPort.DataReceived += new SerialDataReceivedEventHandler(commPort_DataReceived);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    void commPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort currentPort = (SerialPort)sender;
        currentReceived = currentPort.ReadExisting();
        receivedStr += currentReceived;
    }

    internal int CommIO(string outString, int outLen, ref string inBuffer, int inLen)
    {
        receivedStr = string.Empty;
        inBuffer = string.Empty;
        if (CommInitialized())
        {
            commPort.Write(outString);
        }

        System.Threading.Thread.Sleep(1500);

        int i = 0;
        while ((receivedStr.Length < inLen) && i < 10)
        {
            System.Threading.Thread.Sleep(500);
            i += 1;
        }

        if (!string.IsNullOrEmpty(receivedStr))
        {
            inBuffer = receivedStr;
        }
        commPort.Close();

        return inBuffer.Length;

    }
}

I am calling this code from a windows form as follows:

len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4)
len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4)
If(inBuffer == "!?*O")
{
   len = SerialHelperObj.CommIO("\D",2,ref inBuffer, 180)
}

A valid return value from the serial port looks like this: \D00000010000000000010 550 3250 0000256000 and so on ...

I am getting some thing like this: \D00000010D,, 000 550 D,, and so on...

I feel that my comm calls are getting interferred with the one when i send commands. But i am trying to make sure the result of the comma command then initiating the actual command. but the received thread is inserting the bytes from the previous communication cycle.

Can any one please shed some light into this...? I lost quite some hair just trying to get this work. I am not sure where i am doing wrong

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET