C# 扫描和打开串口
引言
关于C#Form窗口使用串口通信是非常常用的通讯方式,期中扫描串口、打开串口、关闭串口等操作是其重要的组成部分骤。在这里我通过用一个demo程序,以最简单的方式实现和表达如下。
一、建工程界面
1、新建C# window窗体 (.net Framework)工程;
2、界面添加一个Combox,命名为comport;添加两个按键,分别命名为button_open和button_close。
修改属性中的文字属性等,其它外观功能属性可自由定义。
二、添加代码
代码中,我们需要用到按键的单击事件、初始化扫描串口,以及打开串口,启动线程等几大方面内容。话不多说,上代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
//串口参数结构体
struct COMPORT_ATTRIBUTE
{
public int bandrate;
public int data_bit;
public Parity parity_check_bit;
public StopBits stop_bit;
public string comport_number;
};
namespace app
{
public partial class Form1 : Form
{
// 串口参数
private COMPORT_ATTRIBUTE uart_port;
//实例化串口类
public System.IO.Ports.SerialPort _serialPort = new System.IO.Ports.SerialPort();
//============================== 定义线程 ===========================================
Thread listenThread;
public bool rx_thread_stop_flag = false;//线程停止标志
public bool rx_thread_start_flag = false;//线程停止标志
public Form1()
{
InitializeComponent();
InitializeSerialSet(); // 初始化串口设置
}
private void button_open_Click(object sender, EventArgs e)
{
OpenComport();//打开串口
MessageBox.Show("已经打开串口" + comport.Text +"!", "OK");
}
private void button_close_Click(object sender, EventArgs e)
{
CloseComport();//关闭串口
MessageBox.Show("已经关闭串口" + comport.Text + "!", "OK");
}
//初始化串口
public void InitializeSerialSet()
{
// 初始化扫描串口
InitializePorts();
// 初始化波特率
uart_port.bandrate = 115200;
// 初始化数据位
uart_port.data_bit = 8;
// 初始化停止位
uart_port.stop_bit = (StopBits)1;
// 初始化校验位
uart_port.parity_check_bit = 0;//Parity.None
if (uart_port.parity_check_bit == (Parity)1)// Parity.Odd
{
}
else if (uart_port.parity_check_bit == (Parity)2) //Parity.Even
{
}
else
{
}
}
/// <summary>
/// 扫描串口
/// </summary>
public void InitializePorts()
{
string[] port_names = SerialPort.GetPortNames();
string last_name = "";
comport.Items.Clear();//清除数据
if (port_names == null)
{
MessageBox.Show("本机没有串口!", "Error");
return;
}
foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
{
//获取有多少个COM口就添加进COMBOX项目列表
comport.Items.Add(s);
last_name = s;//保存最新的一个
}
comport.Text = last_name;//显示最新的一个串口
uart_port.comport_number = last_name;//赋值变量
}
/// <summary>
/// 打开串口
/// </summary>
private bool OpenComport()
{
//打开串口
if (_serialPort.IsOpen)
{
//关闭线程
RxThreadOnOff(false);
//关闭后重新打开
CloseComport();
if (_serialPort.IsOpen)//如果关闭失败就退出
{
return false;
}
}
//串口设置
_serialPort.PortName = comport.Text; //串口名称
_serialPort.BaudRate = uart_port.bandrate; //波特率
_serialPort.DataBits = uart_port.data_bit; //数据位
_serialPort.Parity = uart_port.parity_check_bit;//校验位
_serialPort.StopBits = uart_port.stop_bit; //停止位
try
{
_serialPort.Open(); //打开串口
//_serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);//串口接收处理函数
RxThreadOnOff(true);//开启线程
}
catch
{
MessageBox.Show("串口打开失败!");
return false;
}
return true;
}
/// <summary>
/// 关闭串口
/// </summary>
private void CloseComport()
{
try
{
_serialPort.Close(); //关闭串口
}
catch
{
MessageBox.Show("串口关闭失败!");
}
}
/// <summary>
/// 开关接收线程
/// </summary>
private void RxThreadOnOff(bool on_off)
{
if (on_off)
{
listenThread = new Thread(() => ReceiveData());//开启一个线程来不断的接收数据
listenThread.IsBackground = true;
listenThread.Start();
}
else
{
rx_thread_stop_flag = true;
while (listenThread.IsAlive)//等待停止
{ }
rx_thread_stop_flag = false;
}
}
/// <summary>
/// 接收数据
/// </summary>
public void ReceiveData()
{
//接收线程
while (_serialPort.IsOpen && !rx_thread_stop_flag)//线程循环
{
//......
}
}
}
}