问题
I'm working with VB.NET and I need to send and receive bytes of data over serial. This is all well and good until I need to send something like 173. I'm using a Subroutine to send a byte that takes an input as an integer and just converts it to a character to print it.
Private Sub PrintByte(ByVal input As Integer)
serialPort.Write(Chr(input))
End Sub
If i try
PrintByte(173)
Or really anything above 127 it sends 63. I thought that was a bit odd, so i looked up the ASCII table and it appears 63 corresponds to the ? character. So i think what is happening is VB.NET is trying to encode that number into a character that it does not recognize so it just prints a ?.
What encoding should I use, and how would I implement the encoding change?
回答1:
The issue here is the SerialPort.Encoding property. Which defaults to Encoding.ASCII, an encoding that cannot handle a value over 127. You need to implement a method named PrintByte by actually sending a byte, not a character:
Private Sub PrintByte(ByVal value As Integer)
Dim bytes() As Byte = {CByte(value)}
serialPort.Write(bytes, 0, bytes.Length)
End Sub
来源:https://stackoverflow.com/questions/14668088/vb-net-serial-port-character-encoding