我有一个设备,我通过串行接口与之通信。
通信以十六进制完成,所以我发送十六进制,我确实收到十六进制。
示例:如果我发送" AA 00 03 89 18 0A 98 BB"设备报告" AA 00 02 00 80 82 BB"。
我的目标是以人类可读的方式处理返回值,特别是作为字符串。
发送工作正常,但接收是我努力奋斗的部分,也是我需要帮助的地方。
发送部分:
这是我定义要发送的命令的部分:
private void Print_Bipmap()
{
int x;
int y;
int i;
int RowBytes;
byte n;
Color Pixels;
byte[,] ImageArray = new byte[bitmap.Width, bitmap.Height];
// Calculate output size
RowBytes = (bitmap.Width + 7) / 8;
// Generate body of array
for (y = 0; y < bitmap.Height; y++)
{ // Each row...
for (x = 0; x < (bitmap.Width / 8); x++)
{ // Each 8-pixel block within row...
ImageArray[x, y] = 0;
for (n = 0; n < 8; n++)
{ // Each pixel within block...
Pixels = bitmap.GetPixel(x * 8 + n, y);
if (Pixels.GetBrightness() < 0.5)
{
ImageArray[x, y] += (byte)(1 << (7 - n));
}
}
}
}
comport_writeByte(18); //DC2
comport_writeByte(42); //*
comport_writeByte((byte)bitmap.Height); //r
comport_writeByte((byte)RowBytes); //n
for (y = 0; y < bitmap.Height; y++)
{
for (x = 0; x < RowBytes; x++)
{
comport_writeByte(ImageArray[x, y]); //[d1 ..... dn]
}
}
}
这是我将十六进制消息发送到设备的部分:
Public Sub MySendSerialData(ByVal data As Byte())
Public Class ClassRfidWrapper
Public Function Command(ByVal theCommand As String) As Byte()
'Versuche.
Try
If theCommand = "SetBuzzer" Then
Dim bytes() As Byte = {&HAA, &H0, &H3, &H89, &H18, &HA, &H98, &HBB}
Return bytes
End If
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Class -> ClassRfidWrapper, Method -> SendCommand, Error -> " & ex.Message)
End Try
Return Nothing
End Function
End Class
End Sub
发送:
'Versuche.
Try
If MyCheckIfSerialIsConnected() = True Then
'Mitteilung.
Main.MessageObject.MyMessage("message sent to device: ", Bytes_To_String2(data), 3)
'Log [LogWrapperToDevice]
Main.LogObject.MyLog(Bytes_To_String2(data), "LogWrapperToDevice")
SerialInterface.Write(data, 0, data.Length)
End If
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Class -> ClassSerialInterface, Method -> MySendSerialData, Error -> " & ex.Message)
End Try
将Hex转换为字符串的函数:
SerialInterfaceObject.MySendSerialData(RfidWrapperObject.Command("SetBuzzer"))
接收部分:
这就是我遇到问题的地方
Public Function Bytes_To_String2(ByVal bytes_Input As Byte()) As String
Dim strTemp As New StringBuilder(bytes_Input.Length * 2)
For Each b As Byte In bytes_Input
strTemp.Append(Conversion.Hex(b))
Next
Return strTemp.ToString()
End Function
问题是,我得到垃圾......
我明白,.ReadExisting是错误的方式,因为它将接收的数据解释为字符串,所以我需要一个示例代码,如何接收数据并将数据转换为包含十六进制代码的字节数组,我随后可以使用我的函数Bytes_To_String2
转换为字符串感谢您的帮助
答案 0 :(得分:1)
将响应缓冲区作为字节数组读取。
Public Shared Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim respSize As Integer = sp.BytesToRead
Dim respBuffer As Byte() = New Byte(respSize - 1)
comport.Read(respBuffer, 0, respSize)
' Convert to string and additional processing ...
End Sub