我的代码有问题,我想读取串行端口感谢DataReceivedHandler,但我只工作一次。此串行端口是一个EnOcean USB密钥,当我按下按钮时,它会从电子卡接收数据。数据发送是24个字节。第一次按按钮时,它的工作状态非常好,我收到了数据,但如果我再次按下,没有任何事情发生,DataReceivedHandler看不到任何东西,也不会向我发送数据。多次读取SerialDataPort
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
//init serialport comport
SerialPort comport = (SerialPort)sender;
// Shortened and error checking removed for brevity...
int bytes = comport.BytesToRead;
string indata = comport.ReadExisting();
byte[] buffer = new byte[bytes];
comport.Read(buffer, 0, bytes);
HandleSerialData(buffer, comport);
}
HandleSerialData的作品,它在我的问题我没有问题,我认为,我让代码以防万一。
public void HandleSerialData(byte[] respBuffer, SerialPort comport)
{
/*StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
foreach (byte b in respBuffer)
hex.AppendFormat("{0:x2}", b);*/
string hex = "";
int n = 0;
byte[] ID_TIC;
ID_TIC = new byte[8];
for (int i = 12 ; i < 15; i++)
{
ID_TIC[n] = respBuffer[i];
n = n++;
}
hex = hex + BitConverter.ToString(ID_TIC).Replace("-",string.Empty);
string hex2 = hex.ToString();
Dispatcher.BeginInvoke((Action)(() => { EnOcean_Label.Content = ID_TIC; }));
Dispatcher.BeginInvoke((Action)(() => { EnOcean2_Label.Content = ID_TIC; }));
List<User> users = new List<User>();
users.Add(new User() { NumeroTIC = hex2, NumeroCNT1 = hex2, Date = DateTime.Now });
Dispatcher.BeginInvoke((Action)(() => { dgSimple.ItemsSource = users; }));
WriteTest(ID_TIC);
}
我们已经告诉过你如何在你的上一个问题中正确地做到这一点,你仍然在大幅度错误。调用ReadExisting()*和* Read()根本没有意义,因为ReadExisting已经清空了接收缓冲区,所以你永远不会从Read()中获得任何东西。而且你还没有计算字节数,这是一个很难的要求,你不能忽略Read()的返回值。请一个团队成员来帮助你。 –