The method's parameters are port.Read(byte[], int, int), so the first parameter is a byte array (byte[]). Try: byte[] buf = new byte[5];
But I don't recommend reading a fixed # of bytes if possible since it is very easy to get one or two bytes off in the incoming buffer and hence not receive the data when expected or get unexpected results.
This is much preferred since it handles any amount of incoming data. Just process what ends up in the PortBuffer and remember to clean it out from time to time to prevent memory creep.
private List<byte> PortBuffer = new List<byte>();
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] data = new byte[port.BytesToRead];
port.Read(data, 0, data.Length);
PortBuffer.AddRange(data);
ProcessIncomingData(PortBuffer);
}
private void ProcessIncomingData(List<byte> PortBuffer)
{
// Search through the bytes to find the data you want
// then remove the data from the list. It is good to
// clean up unused bytes (usually everything before
// what you're looking for)
}
=================================================
Hi Charlie!
int intBytes;
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
intBytes = serialPort.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort.Read(bytes, 0, intBytes);
this.Invoke(new EventHandler(SetText));
}
void SetText()
{
tbReceive.Text += intBytes.ToString() + ";";
}
You are right. I install ActiveSyn 4.0 which uses COM1. After I delete it, the program works very well. I have another question. I modify you program in DataReceive event handler:
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int intBytes = serialPort.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort.Read(bytes, 0, intBytes);
tbReceive.Text += intBytes.ToString() + ";";
}
The tbReceive is a TextBox control. When the program excutes at the last line,
tbReceive.Text += intBytes.ToString() + ";";
there is an exception, System.InvalidOperationException was unhandled. The error message is "Cross-thread operation not valid: Control 'tbReceive' accessed from a thread other than the thread it was created on." Please tell me what's reason and how to solve it. Thanks!