问题
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