Reputation: 844
I am building a C# application that reads data from the serial port. The data I sent is like a byte. 0x0, 0x1, 0x5, 0x100. It is like sending integers. I want to read the data, and print it in my debug console. The only problem is how.
After some research, I found out that I was able to print it like: 01, 6A, 52. But this isn't what I want. I only want the digits after the x. 0x0 has to be 0, 0x50 has to be 50, 0x145 has to be 145, etc.
The code I have now is:
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
readingbuffer = Encoding.UTF8.GetBytes(serialPort.ReadExisting());
Debug.WriteLine(BitConverter.ToString(readingbuffer));
this.Invoke(new EventHandler(procesReading));
}
Every time the serial port received some data, the code above is triggered.
I don't know if it is possible to read the digits after the x, so, could anybody assist me a little bit?
Upvotes: 0
Views: 1953
Reputation: 1382
byte[] buf = new byte[4]; // creates a byte array the size of the data you want to recieve
int bufCount = 0;
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
bufCount += serialPort.Read(buf, bufCount, buf.Length - bufCount);
if(bufCount == buf.Length)
serialPort.Close();
}
EDIT:
You can then convert it to Hex string like that
string hex = BitConverter.ToString(buf).Replace("-", string.Empty);
Upvotes: 2