简体   繁体   English

C# 读取 HEX 串口数据并发送到 Streamwriter

[英]C# Read HEX Serial Port Data and send to Streamwriter

I am trying to read serial data from a device which is sending its data in HEX and then write it to an azure relay streamwriter to a receiver application.我正在尝试从以十六进制发送数据的设备读取串行数据,然后将其写入 azure 中继流写入器到接收器应用程序。 The device is sending these HEX Values: 16 51 1D 65 D4 A6 However my program seems to be reading:设备正在发送这些十六进制值:16 51 1D 65 D4 A6 但是我的程序似乎正在读取:

: 在此处输入图像描述

How do I get the serial port to read the HEX data and send it over a streamwriter?如何让串口读取 HEX 数据并通过流写入器发送? I have attached my code below.我在下面附上了我的代码。 Thank you for your help!谢谢您的帮助!

// 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);
            });

You could read it as a byte array instead of text:您可以将其读取为字节数组而不是文本:

int length = sp.BytesToRead;
byte[] buf = new byte[length];

sp.Read(buf, 0, length);
System.Diagnostics.Debug.WriteLine("Received Data:" + buf);

I solved my query with this code:我用这段代码解决了我的查询:

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());
    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM