Reputation: 53
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. :)
Upvotes: 1
Views: 355
Reputation: 975
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.
Upvotes: 1