简体   繁体   中英

Read byte as binary from serial port c#

How to i read the byte as binary instead of ASCII and write back as binary too?

private void ReadPort()
{
    while (_keepReading)
    {
        if (_serialPort.IsOpen)
        {
            byte[] readBuffer = new byte[_serialPort.ReadBufferSize + 1];
            try
            {
                int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
                String SerialIn = System.Text.Encoding.ASCII.GetString(readBuffer,0,count);
                DataReceived(SerialIn);
            }
            catch (TimeoutException) { }
        }
        else
        {
            TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
            Thread.Sleep(waitTime);
        }
    }
}

When _serialPort.ReadBufferSize is specified and _serialPort.Read() is executed, until the received data reaches _serialPort.ReadBufferSize ( At least 4096 bytes ), it means that _serialPort.Read() waits or a timeout exception occurs.

Then does write back mean echoing back in binary to the same serial port that received it?

In the presented source code, the received data is converted to an ASCII string and passed to the DataReceived() function.

The processing and the question text do not match. Which is correct?
Or do you want to output the received data to the console or window text box?

Also, if you want to write back the received data, the function name ReadPort() is not appropriate because it represents only half of the processing.

Please clarify and detail what you want to do and add it to the question article.


For example, if you want to receive data from the serial port and echo back to the same port, the process would be:

byte[] Buffer = new byte[1];
TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
while (_keepReading)
{
   if (_serialPort.IsOpen)
    {
        try
        {
            int count = _serialPort.Read(Buffer, 0, 1);
            if (count > 0)
            {
                _serialPort.Write(Buffer, 0, 1);
            }
        }
        catch (TimeoutException) { }
        catch (Exception) { }
    }
    else
    {
        Thread.Sleep(waitTime);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM