0

I'm writing a C# application that will receive serial data from 3 different COM ports configure with 8-bit UART with no parity. The other devices will be sending and receiving binary encoded HEX ex. AF01h = 10101010 00000001 two characters for each byte. I have set up virtual COM ports and a simple application for testing purposes and am sending data back and forth before I hook the devices up. I found that data is ASCII encoded by default on transmission and reception but I need both to be binary encoded HEX. I do not see that option in the encoding class and would rather not have the application using a complete different encoding than the 3 other devices. Right now I am using this code to convert the string when it is sent

string binarystring = String.Join(String.Empty, hexstring.Select(c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')));
sport.Write(binarystring);
txtReceive.AppendText("[" + dtn + "] " + "Sent: " + binarystring + "\n");

This works for testing transmission for now but i will eventually change the code to place the two digit hex number directly into a byte array.

This code will allow me to enter AF01h = 1010101000000001, but on the receiving end of the application I get 16 bytes of ASCII encoded characters. Is there a way I can get the app on the same page as the other devices?

R Mason
  • 1
  • 2
  • Don't use the Write(string) overload. Use byte[] to ensure you are encoding binary data correctly. – Hans Passant Sep 23 '17 at 07:44
  • Wont i have to encode the ASCII characters from the textbox before i move them into the Byte[]? Also won't the ASCII encoding/ decoding still apply once i send the bytes? – R Mason Sep 23 '17 at 08:13

1 Answers1

0

Figured out a way to do it. Just needed to convert the long string of hex to two hex character byte integers

string hex = txtDatatoSend.Text; //"F1AAAF1234BA01"
int numOfBytes = HEX.Length;
byte[] outbuffer = new byte[numOfBytes / 2];
for (int i = 0; i < numOfBytes; i += 2)
{
outbuffer[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
sport.Write(outbuffer, 0, outbuffer.Length);
sport.DiscardOutBuffer()

The only caveat is you have to enter in the an even number of characters

On the other end the data gets placed right back in the Byte[] and i can decode it like this.

byte[] inbuffer = new byte[sport.BytesToRead];
sport.Read(inbuffer, 0, inbuffer.Length);
txtReceive.AppendText("[" + dtn + "] " + "Received: " + inbuffer.Length + " bytes ");
for (int i = 0; i < inbuffer.Length; i++)
{
string hexValue = inbuffer[i].ToString("X2");
txtReceive.AppendText(inbuffer[i] + " is " + hexValue + "HEX ");
}
txtReceive.AppendText("\n");
sport.DiscardInBuffer();
R Mason
  • 1
  • 2