【问题标题】:C# Read HEX Serial Port Data and send to StreamwriterC# 读取 HEX 串口数据并发送到 Streamwriter
【发布时间】:2020-10-25 20:27:30
【问题描述】:

我正在尝试从以 HEX 格式发送数据的设备读取串行数据,然后将其写入 azure 中继流写入器到接收器应用程序。 设备正在发送这些十六进制值:16 51 1D 65 D4 A6 但是我的程序似乎正在阅读:

:

如何让串口读取 HEX 数据并通过流写入器发送?我在下面附上了我的代码。感谢您的帮助!

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

【问题讨论】:

    标签: c# azure serial-port hex streamwriter


    【解决方案1】:

    您可以将其读取为字节数组而不是文本:

    int length = sp.BytesToRead;
    byte[] buf = new byte[length];
    
    sp.Read(buf, 0, length);
    System.Diagnostics.Debug.WriteLine("Received Data:" + buf);
    

    【讨论】:

    • 谢谢您,使用您的代码我能够实现我想要的!我把我的代码放在下面
    【解决方案2】:

    我用这段代码解决了我的查询:

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

    【讨论】:

      猜你喜欢
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多