在C#中进行串口通讯主要涉及到以下几个步骤:
-
引入命名空间
- using System.IO.Ports;
-
创建SerialPort对象
- SerialPort port = new SerialPort();
-
设置串口属性
- //设置串口名 :port.PortName = "COM1";
- //设置波特率:port.BaudRate = 9600;
- //设置校验位:port.Parity = Parity.None;
- //设置数据位:port.DataBits = 8;
- //设置停止位:port.StopBits = StopBits.One;
-
打开串口
port.Open();
-
发送数据
port.Write("Hello World");
-
接收数据
-
// 读取numBytesToRead个字节的数据
byte[] buffer = new byte[10];
int bytesRead = port.Read(buffer, 0, 10);// 将字节数组转换为字符串
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead); -
关闭串口
port.Close();
下列为Demo源码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//先引用
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;
namespace 串口通信
{
public class Class1
{
// 创建SerialPort对象
SerialPort port = new SerialPort();
// 定义事件委托
public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
// 定义事件
public event DataReceivedEventHandler DataReceived;
/// <summary>
/// 是否初始化
/// </summary>
public bool IsOpen { get; set; }
//设置串口属性(可以通过初始化类进行传递参数)
public Class1()
{
port.PortName = "COM3"; //设置串口名
port.BaudRate = 115200; //设置波特率
port.Parity = Parity.None; //设置校验位
port.DataBits = 8; //设置数据位
port.StopBits = StopBits.One; //设置停止位
Thread Mythr = new Thread(ReadMessage);
Mythr.Start();
}
/// <summary>
///打开串口
/// </summary>
public void Openport()
{
try
{
port.Open();
IsOpen = true;
}
catch
{
IsOpen = false;
}
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="Message"></param>
public void SendMessage(string Message)
{
try
{
if (IsOpen)
{
if (port.IsOpen)
{
port.Write(Message);
}
}
}
catch
{
}
}
/// <summary>
/// 关闭串口对象
/// </summary>
public void ClosePort()
{
try
{
IsOpen = false;
if (port.IsOpen)
{
port.Close();
}
}
catch
{
IsOpen = false;
}
}
/// <summary>
/// 读取串口值
/// </summary>
public void ReadMessage()
{
//根据现场情况定义接收数据长度
int numBytesToRead = 1;
while (true)
{
//如果连接打开
if (IsOpen&&port.IsOpen)
{
// 检查是否有足够的数据可读
if (port.BytesToRead >= numBytesToRead)
{
// 读取numBytesToRead个字节的数据
byte[] buffer = new byte[10];
int bytesRead = port.Read(buffer, 0, 10);
// 将字节数组转换为字符串
string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
if (DataReceived != null)
{
DataReceived(this, new DataReceivedEventArgs(data));
}
}
}
}
}
}
// 定义事件参数类
public class DataReceivedEventArgs : EventArgs
{
public string ReceivedData { get; set; }
public DataReceivedEventArgs(string Receiveddata)
{
this.ReceivedData = Receiveddata;
}
}
}
WinForm调用示例 (虚拟串口调试软件)
http://链接:https://pan.baidu.com/s/1Uz9THjTKbryrD1HteXfQhQ 提取码:d01v
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
namespace 串口通信
{
public partial class Form1 : Form
{
Class1 serialPort = new Class1();
public void SerialPort_DataReceived(object sender, DataReceivedEventArgs e)
{
textBox2.Invoke(new Action(() => { textBox2.Text = e.ReceivedData.ToString(); }));
}
public Form1()
{
InitializeComponent();
serialPort.DataReceived += SerialPort_DataReceived;
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort.Openport();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort.SendMessage(textBox1.Text);
}
}
}