C#窗体程序,创建串口的接收和发送,先检查串口的连接状态,如果已经连接好则向com1发送A0 EC B6 E3数据,等待5秒后再向com2发送play数据,再等待5后再向com3发送1234数据并且所有端口只发送一次的完整代码
时间: 2024-09-14 20:10:21 浏览: 26
在C#中创建一个简单的Windows Form应用程序,用于控制串口通信,你可以使用`System.IO.Ports.SerialPort`类。首先需要添加对`System.IO.Ports命名空间`的引用。以下是完整的代码示例:
```csharp
using System;
using System.IO.Ports;
public partial class MainForm : Form
{
SerialPort serialPort1, serialPort2, serialPort3;
public MainForm()
{
InitializeComponent();
InitializeSerialPorts();
}
private void InitializeSerialPorts()
{
// 检查并设置串口连接
serialPort1 = new SerialPort("COM1");
serialPort1.DataReceived += SerialPort_DataReceived;
if (serialPort1.IsOpen)
SendDataToCom1();
serialPort2 = new SerialPort("COM2");
serialPort2.DataReceived += SerialPort_DataReceived;
serialPort3 = new SerialPort("COM3");
serialPort3.DataReceived += SerialPort_DataReceived;
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine("Data received on " + ((SerialPort)sender).Name);
}
private void SendDataToCom1()
{
byte[] data = { 0x41, 0x30, 0xEC, 0xB6, 0xE3 };
try
{
serialPort1.Write(data, 0, data.Length);
Console.WriteLine("Sent data to COM1: A0 EC B6 E3");
Thread.Sleep(5000); // 等待5秒
}
catch (Exception ex)
{
Console.WriteLine("Error sending to COM1: " + ex.Message);
}
finally
{
if (!serialPort1.IsDisposed)
serialPort1.Close(); // 关闭连接后不再发送
}
}
private void SendPlayDataToCom2()
{
string playData = "play";
try
{
serialPort2.Write(playData, 0, playData.Length);
Console.WriteLine($"Sent '{playData}' to COM2");
Thread.Sleep(5000); // 再次等待5秒
}
catch (Exception ex)
{
Console.WriteLine($"Error sending to COM2: {ex.Message}");
}
}
private void SendDataToCom3()
{
int num = 1234;
try
{
serialPort3.Write(BitConverter.GetBytes(num), 0, sizeof(int));
Console.WriteLine($"Sent number {num} to COM3");
Thread.Sleep(5000); // 最后一次等待5秒
}
catch (Exception ex)
{
Console.WriteLine($"Error sending to COM3: {ex.Message}");
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
SendDataToCom1();
SendPlayDataToCom2();
SendDataToCom3();
}
}
```
在这个代码中,我们初始化了三个串口,并在单击按钮时依次发送数据。注意这只是一个基本示例,实际应用可能需要处理异常、超时和其他更复杂的场景。
阅读全文