// 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)); } }
标签:片段,Console,代码,receivedData,serialPort,length,串口,var,new From: https://www.cnblogs.com/lu1770/p/18373354