csharp-串口操作

NuGet 添加 System.IO.Ports 包

private SerialPort port;

port = new SerialPort("com6",9600,Parity.None, 8, StopBits.One);
port.ReadTimeout = 500;
port.WriteTimeout = 500;

port.Open();

if (false == port.IsOpen)
{
Console.WriteLine("open failed.");
}else
{

port.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

// taskSerialRead = new Task(() => { Read(); });
// taskSerialRead.Start();

port.Write("ST");
}

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
Char[] buf = new Char[5];
buf[2] = '\0';
int iRet = port.Read(buf,0,2);

string str = new string(buf);
Console.WriteLine($"read: {str}");
if (str == "AB")
{
port.Write("CD");
}
// Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.
// ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.
// this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}

遍历串口

string[] ports = SerialPort.GetPortNames();   
Array.Sort(ports);

//将其显示到comboPorName控件中去
comboPortName.Items.AddRange(ports);
comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;