1

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 :

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 ,

Thank you so much for your help

dxtr
  • 685
  • 1
  • 7
  • 16
  • Show us the code you have to ready data from serial port – Adil Jan 30 '15 at 07:14
  • I modified my question with the code I used to read data – dxtr Jan 30 '15 at 07:45
  • Can you try different inputs-outputs and tell us what you get? I personally don't think that the problem is with `00` bytes as you might think – chouaib Jan 30 '15 at 08:54
  • I tried many times with differents Input-output , the same thing the readbyte function seems to ignore 00 : for example now im trying with : 05-03-04-00-3A-00-0E-1E-3A and I'm receiving this : 05-03-04-3A-0E-1E-3A – dxtr Jan 30 '15 at 09:05
  • 1
    How can you be sure that the device is actually sending '00' bytes? Have you tried with any other RS232 terminal to check if it's not a device issue? – Jamby Jan 30 '15 at 10:40
  • @Jamby I'm tried also some Modbus simulator , and I get the same result , I can't read the 00 Byte is it normal , is this how readbyte works ? – dxtr Jan 30 '15 at 15:19
  • @Jamby Using advanced serial port monitor , Im sending Hex string manually , Only NOT &H00 can be read – dxtr Jan 30 '15 at 15:36

2 Answers2

1

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++;
  }
}

EDIT Sorry 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

chouaib
  • 2,763
  • 5
  • 20
  • 35
  • Hey , Its okey , I converted your code to VB.net and tested it , but it gives me the same result , – dxtr Jan 30 '15 at 07:43
  • `array[i]=serialPort1.ReadByte();` will give a compile exception `cannot implicitly convert int to byte` - see https://stackoverflow.com/questions/1318933/c-sharp-int-to-byte for conversion – Jimbo Dec 11 '19 at 05:53
1

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

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

thank you so much for your help

dxtr
  • 685
  • 1
  • 7
  • 16