vb.net Serialport readbyte 没有得到正确的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28230709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:44:40  来源:igfitidea点击:

Serialport readbyte not getting the right data

c#vb.netvisual-studio-2010serial-port

提问by dxtr

I'm writing a software in VB.net to communicate with an external device with modbus I have a problem while reading data received from the device , to put it in example , using sp1.ReadByte()the data sent from the device is this :

我正在 VB.net 中编写一个软件来与带有 modbus 的外部设备通信我在读取从设备接收到的数据时遇到问题,举个例子,使用sp1.ReadByte()从设备发送的数据是这样的:

05-03-04-00-00-01-9F-FE-0B

Update : to read data i used this code

更新:为了读取数据,我使用了这段代码

Dim reponse As Byte() = New Byte(5 + (2 * nombre_registrre - 1)) {}

        For i As Integer = 0 To response.Length - 1

         response(i) = CByte(genvision.sp1.ReadByte())

        Next

but receive this

但收到这个

05-03-04-01-9F-FE-0B

I want to read it byte by byte even those 00 00 ,

我想逐字节读取它,即使是那些 00 00 ,

Thank you so much for your help

非常感谢你的帮助

采纳答案by dxtr

Problem solved , The problem was : sp1.DiscardNull = true ,

问题解决了,问题是: sp1.DiscardNull = true ,

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.discardnull(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.discardnull(v=vs.110).aspx

thank you so much for your help

非常感谢你的帮助

回答by chouaib

Try :

尝试 :

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
  byte[] array = new byte[256];
  int i = 0;
  while (serialPort1.BytesToRead > 0)
  {
    array[i]=serialPort1.ReadByte();
    i++;
  }
}

EDITSorry I was driven here by the C#tag! you have to be more exact next times, P.S I'm not sure how to make it in VB but it shouldn't be much different

编辑对不起,我是被C#标签驱赶到这里的!下次你必须更准确,PS 我不知道如何在 VB 中制作它,但它不应该有太大不同