C# 读取 HEX 串口数据并发送到 Streamwriter
C# Read HEX Serial Port Data and send to Streamwriter
我正在尝试从以 HEX 格式发送数据的设备中读取串行数据,然后将其写入 azure 中继流写入器以接收应用程序。
设备发送这些十六进制值:16 51 1D 65 D4 A6
但是我的程序似乎正在读取:
:
如何让串口读取十六进制数据并通过流式写入器发送?我在下面附上了我的代码。感谢您的帮助!
// Read from the serial and write to the hybrid connection.
var writes = Task.Run(async () => {
// var reader = Console.In;
var writer = new StreamWriter(relayConnection) { AutoFlush = true };
do
{
// Read serial data from the serial port.
string line = sp.ReadExisting();
// Write the line to the hybrid connection (Azure Relay)
if(line.ToString() != "")
{
await writer.WriteLineAsync(line);
}
//cancel connection and break loop
if (Main.disconnect == true)
{
break;
}
}
while (true);
});
您可以将其读取为字节数组而不是文本:
int length = sp.BytesToRead;
byte[] buf = new byte[length];
sp.Read(buf, 0, length);
System.Diagnostics.Debug.WriteLine("Received Data:" + buf);
我用这段代码解决了我的查询:
do
{
// Read serial data from the serial port.
//string line = sp.ReadExisting();
int length = sp.BytesToRead;
byte[] buf = new byte[length];
sp.Read(buf, 0, length);
// Write the line to the hybrid connection (Azure Relay)
if(buf.ToString() != "")
{
for(int i = 0; i < length; i++)
{
await writer.WriteLineAsync(buf[i].ToString("X2"));
}
//await writer.WriteLineAsync(buf.ToString());
}
我正在尝试从以 HEX 格式发送数据的设备中读取串行数据,然后将其写入 azure 中继流写入器以接收应用程序。 设备发送这些十六进制值:16 51 1D 65 D4 A6 但是我的程序似乎正在读取:
:
如何让串口读取十六进制数据并通过流式写入器发送?我在下面附上了我的代码。感谢您的帮助!
// Read from the serial and write to the hybrid connection.
var writes = Task.Run(async () => {
// var reader = Console.In;
var writer = new StreamWriter(relayConnection) { AutoFlush = true };
do
{
// Read serial data from the serial port.
string line = sp.ReadExisting();
// Write the line to the hybrid connection (Azure Relay)
if(line.ToString() != "")
{
await writer.WriteLineAsync(line);
}
//cancel connection and break loop
if (Main.disconnect == true)
{
break;
}
}
while (true);
});
您可以将其读取为字节数组而不是文本:
int length = sp.BytesToRead;
byte[] buf = new byte[length];
sp.Read(buf, 0, length);
System.Diagnostics.Debug.WriteLine("Received Data:" + buf);
我用这段代码解决了我的查询:
do
{
// Read serial data from the serial port.
//string line = sp.ReadExisting();
int length = sp.BytesToRead;
byte[] buf = new byte[length];
sp.Read(buf, 0, length);
// Write the line to the hybrid connection (Azure Relay)
if(buf.ToString() != "")
{
for(int i = 0; i < length; i++)
{
await writer.WriteLineAsync(buf[i].ToString("X2"));
}
//await writer.WriteLineAsync(buf.ToString());
}