C# 扫描和打开串口

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)//线程循环
           {
              //......
           }
       }
   }
}


public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort port1 = new SerialPort(); string InputData = String.Empty; delegate void SetTextCallback(string text); private void Port_Select() {//获取机器中的串口地址 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } } private void Form1_Load_1(object sender, EventArgs e) { Port_Select(); this.comboBox1.SelectedIndex = 0; this.comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "关闭串口") //当要关闭串口的时候 { port1.DiscardOutBuffer(); port1.DiscardInBuffer(); port1.Close(); button1.Text = "打开串口"; label3.Text = "串口当前状况:未打开"; comboBox1.Enabled = true; comboBox2.Enabled = true; } else if (button1.Text == "打开串口") //当要打开串口的时候 { try { port1.PortName = comboBox1.SelectedItem.ToString(); port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem); port1.DataBits = 8; port1.RtsEnable = true; port1.Open(); port1.DiscardOutBuffer(); port1.DiscardInBuffer(); button1.Text = "关闭串口"; comboBox1.Enabled = false; comboBox2.Enabled = false; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + " 波特率:" + comboBox2.SelectedItem.ToString() + " 数据位:8 "; } catch { button1.Text = "打开串口"; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + "打开失败"; MessageBox.Show("该串口无法打开"); } } } 资源中部分代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星papa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值