0

I am working on Visual Studio & I am designing a GUI for my sensor. My sensor is transmitting 8 bytes on press of button and I am having trouble while reading those 8 bytes available serially and store them in array, so I can further use those bytes here is my code below for serially reading available bytes.

For storing serial available bytes in an array I have created and assigned new array as follows:

byte incoming = new byte[9];

Serially writing to sensor is achieved successfully now I am facing trouble in reading the bytes available on serial port transmitted by my sensor. Kindly assist me in achieving best possible solution.

private void timer1_Tick(object sender, EventArgs e)
{
    if (!serialPort1.IsOpen)
    {
        MessageBox.Show("Command cannot be sent, Serial Port Not opened");
    }
    else
    {
        serialPort1.Write(TandH, 0, TandH.Length);
        serialPort1.Read(incoming[], 0, 8);
    }
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52
  • 1
    Instead of trying to read directly after writing, use the [DataReceived](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.datareceived?view=netframework-4.7.2) event. – Idle_Mind Jan 12 '19 at 19:35
  • 3
    Please read the documentation for the `SerialPort.Read` method carefully. The method does not wait for all 8 bytes to be received. It will only read as many bytes as are in the input/receive buffer when the method is being called. Check the return value (again, read the documentation about what the meaning of SerialPort.Read's return value is) and if necessary repeat calling SerialPort.Read until you got all 8 bytes. (Alternatively, use SerialPort.ReadByte 8 times to read the 8 bytes.) –  Jan 12 '19 at 19:59
  • can you please help me by writing lines so i can easily understand – Hamza Abbasi Jan 13 '19 at 07:59
  • For example see [my answer](https://stackoverflow.com/a/53633030/2594597) to the "C# await event and timeout in serial port communication" question. Just use `SerialPort.Read()` instead of a `Stream.ReadAsync()`. – Leonid Vasilev Jan 14 '19 at 12:05

0 Answers0