1
votes

I am trying to write GUI in C# for interfacing FPGA to PC via UART. At FPGA side i use 32bit unsigned data type:

data_to_uart            :   out unsigned(31 downto 0);
data_to_uart            <= to_unsigned(1000, 32);

Then data_to_uart in my FPGA design goes to block that splits this 32bit unsigned to 4 bytes and sends them one by one via UART. So at the terminal I receive folowing (value should be: 1000):

00000000 00000000 00000011 11101000

My problem is: how to read those four bytes properly in c# by using using System.IO.Ports; and convert it to int (to do some math) and then to string - to display value on label.

Curently I am using:

inputData = serialPort1.ReadExisting();

The folowing: Binary to decimal conversion example does not work for me because .ReadExisting is returning String :(

I took a look at this:

Microsoft Docs - SerialPort Method

Do I have to use SerialPort.ReadByte Method? There's stated that it reads only one byte, how to read all four and then convert to int?

I am using: baud rate - 115200, 8 bits and one stopbit.

Thanks for looking and maybe some advice. :)

1
If you are dealing with binary data, you shouldn't be using string encoding to read those bytes anyway. While C# will happily convert byte[] -> string -> byte[], there are no guarantees that what you end up with is the same as what you started with.Llama
As long as you are communicating via the serial port, you should not treat 32-bit integers as raw. Because it is not possible to distinguish where multiple 32-bit = 4-byte data starts and ends. It is recommended to design a protocol by converting the numerical value into a character string and adding a start code, an end code, and a checksum if necessary. Or, you may adopt any of the existing protocols.kunif
As @kunif said, a protocol is essential. If you don't want to reinvent the wheel, take a look at modbus or other protocol.Louis Go

1 Answers

1
votes

As others said, you should use a protocol. But to answer the question:

    if (serialPort1.ReadBufferSize >= 4)
    {
        var buffer = new byte[4];
        for (int i = 3; i >= 0; --i)
            buffer[i] = (byte)serialPort1.ReadByte();
        int myNumber = BitConverter.ToInt32(buffer, 0);
    }

This would read the four bytes from the serial port and turn them into an integer variable. Note that the buffer is filled backwards, since you are sending the binary out big-endian.