串口代码片段

// See https://aka.ms/new-console-template for more information

using System.IO.Ports;
using System.Runtime.InteropServices;

Console.WriteLine("Hello, World!");

try
{
    var ports = SerialPort.GetPortNames();
    foreach (var port in ports)
    {
        Console.WriteLine(port);
    }

    TestCommand0();
}
catch (Exception e)
{
    Console.WriteLine(e);
}

string GetPortName()
{
    /*
    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    {
        return "COM3";
    }
    */
    return "/dev/ttyUSB0";
}



void TestCommand0()
{
    var requestFrame = new List<byte>
    {
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, 0x80, 0x00, 0x00, 0x82
    };

    var parity = Parity.Odd;
    var stopBits = StopBits.One;
    var dataBits = 8;
    // var baudRate = 9600;
    var baudRate = 1200;

    var portName = GetPortName();
    Console.WriteLine(portName);

    var serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

    serialPort.ReadTimeout = 3500;
    //serialPort.Handshake = Handshake.RequestToSend;

    //serialPort.DtrEnable = true;
    serialPort.RtsEnable = true;

    // serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);


    serialPort.Open();

    serialPort.Write(requestFrame.ToArray(), 0, requestFrame.Count);

    Thread.Sleep(1000);
    //serialPort.RtsEnable = false;

    var response = new byte[512];
    var length = serialPort.Read(response, 0, 512);

    var receivedData = new byte[length];
    Array.Copy(response, 0, receivedData, 0, length);

    Console.WriteLine(BitConverter.ToString(receivedData));
}

static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    if (sender is SerialPort serialPort)
    {
        var response = new byte[512];
        var length = serialPort.Read(response, 0, 512);

        var receivedData = new byte[length];
        Array.Copy(response, 0, receivedData, 0, length);

        Console.WriteLine(BitConverter.ToString(receivedData));

    }
}

  

posted on 2024-08-22 10:45  ZhengyaoLu  阅读(7)  评论(0编辑  收藏  举报

导航