C# SerialPort: ReadLine not working

无人久伴 提交于 2020-01-17 05:40:08

问题


i'm having issues reading input from a serial port in C#. The device, that is connected via usb, is a ELM327-Chip for reading the OBD-port of the car.

My Code consist of two threads: A Write- and a Read-Thread. It looks like the following:

static volatile SerialPort moPort;

...

moPort = new SerialPort("COM3");

moPort.BaudRate = 38400;
moPort.Parity = Parity.None;
moPort.DataBits = 8;
moPort.StopBits = StopBits.One;
moPort.NewLine = "\r";
moPort.ReadTimeout = 5000;

moPort.Open();

Write-Thread:

for (; ; )
{
    foreach (string sPID in Car.getAvailablePIDs())
    {
        moPort.WriteLine("01 " + sPID);
        Thread.Sleep(50);
    }
}

Read-Thread:

for (; ; )
{
    string sResult;
    try
    {
    sResult = moPort.ReadLine();
    }
    catch (TimeoutException)
    {
    return;
    }
}

This way my program is working properly. The Input I get from the Device looks like the following:

41 0C 00 1C\r
41 1E 00\r
>NO DATA 

The problem just occurs when I dont use the sleep function in the main-thread. The response I receive from the device then looks like the following:

41 0C
00 1C
\r41 1E
00\r
>NO
DATA

It doesn't seperate the strings anymore by '\r' but just sends ... chaos.

I have no idea what I should do or if there is anything wrong with my code. Has anyone suggestions?

MfG Kyle


回答1:


First of all: SerialPort implementation in C# sucks. There are many, many problems, i.e. works on some emulated ports but not on physical (none of the devices we tested). I recommend using http://serialportstream.codeplex.com/ I wanted to tell you this first because I wasted many tears, blood and hair fighting with many alogic behaviours of standard SerialPort class.

Now, regarding your code - the most important thing is to seperate the read-write logic completely. You can write as you like but please consider reading data as in my example below

port.DataReceived += port_DataReceived;

and the handler

private void port_DataReceived(object sender, RJCP.IO.Ports.SerialDataReceivedEventArgs e)
{
    try
    {       
        SerialPortStream sp = (SerialPortStream)sender;

        if (sp.BytesToRead > 0)
        {
            int bytes_rx = sp.Read(buffer, 0, BYTES_MAX);           

            if (datacollector != null)
                datacollector.InsertData(buffer, bytes_rx);
        }
    }
    catch (Exception ex)
    {
        ///project specific code here...
    }
}


来源:https://stackoverflow.com/questions/33310396/c-sharp-serialport-readline-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!