vb.net串口字符编码 [英] vb.net serial port character encoding
问题描述
我使用VB.NET,我需要串行发送和接收字节的数据。这是好和好,直到我需要发送像173.我使用子程序发送一个字节,它接受一个输入作为一个整数,只是将它转换为一个字符打印它。
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
如果我尝试
PrintByte(173)
或者真的127以上的任何东西发送63.我以为这有点奇怪,所以我查找了ASCII表,它出现63对应于?字符。所以我认为发生了什么是VB.NET试图将该数字编码为一个字符,它不能识别,所以它只打印一个?。
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?
推荐答案
这里的问题是SerialPort.Encoding属性。默认为Encoding.ASCII,不能处理超过127的值的编码。您需要实际发送一个字节而不是字符来实现一个名为PrintByte的方法:
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
这篇关于vb.net串口字符编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!