I have tried using Readline() and data gets dropped, I tried using Read() but I am not sure how to have an error proof method of doing it, since I may get several packets one after another and I have no way of knowing that there is going to be another packet coming in. In between packets BytesToRead is 0, so I can't use it. When reading data to the buffer to you have a timer or put the thread to sleep to allow for all the packets to arrive?
I am lost. Don't know what to try next.
I should mention that I get no guarantee that the string coming off the serial port will be ended with \n or \r or \r\n. I simply need a fool proof way to read ALL the packets that will come from the scale when the user presses PRINT on it.
Someone answered here with the idea I liked - waiting for a certain amount of time for all the packets, but they erased their answer. ANy chance you could re-post it?
Have you tried listening to the DataRecieved
event of the SerialPort
class?
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
serialPort.Dispose();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With