vb.net serial port character encoding

做~自己de王妃 提交于 2020-01-03 03:03:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!