用C#写一份串口收发代码
以下是一个基本的串口收发代码示例,使用C#语言编写:
using System;
using System.IO.Ports;
class Program
{
static SerialPort serialPort;
static void Main(string[] args)
{
// 创建一个新的串口实例
serialPort = new SerialPort("COM1", 9600);
// 配置串口参数
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Handshake = Handshake.None;
// 注册数据接收事件处理程序
serialPort.DataReceived += SerialPort_DataReceived;
try
{
// 打开串口
serialPort.Open();
Console.WriteLine("串口已打开");
// 发送数据
string dataToSend = "Hello, World!";
serialPort.WriteLine(dataToSend);
Console.WriteLine("已发送数据:{0}", dataToSend);
// 延迟 1 秒,等待接收数据
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
Console.WriteLine("串口打开失败:{0}", ex.Message);
}
finally
{
// 关闭串口
serialPort.Close();
Console.WriteLine("串口已关闭");
}
Console.ReadLine();
}
static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 读取接收到的数据
string dataReceived = serialPort.ReadExisting();
Console.WriteLine("已接收数据:{0}", dataReceived);
}
}
在上述代码中,我们首先创建了一个SerialPort对象,并根据需要配置了串口参数,如串口号、波特率、校验位、数据位和停止位等。
然后,我们注册了一个数据接收事件处理程序SerialPort_DataReceived,该事件会在有数据接收到时触发。在事件处理程序中,我们使用ReadExisting方法读取接收到的数据,并进行相应的处理。
接下来,我们使用Open方法打开串口,并使用WriteLine方法发送数据。然后,我们使用Thread.Sleep方法延迟一秒钟,以便有足够的时间接收数据。
最后,我们在必要时关闭串口,并等待用户按下回车键退出程序。
请注意,以上代码仅为示例,实际使用时可能需要根据具体情况进行适当的修改和优化
原文地址: http://www.cveoy.top/t/topic/hHXB 著作权归作者所有。请勿转载和采集!