01_SerialPort类串口通信

 

文档:SerialPort 类 (System.IO.Ports) | Microsoft Learn

 

 

页面展示:

 代码:

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;
using System.Threading.Tasks;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;

namespace MyModbusTool
{
    public partial class FormModnus2 : Form
    {
        //串口类对象
        private SerialPort serial;
        //计时器
        private Timer timer;
        private Thread reavThread;
        public FormModnus2()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;//跨线程检测关闭
            InitUI();
            //初始化
            serial = new SerialPort();
            timer = new Timer();
            timer.Tick += Timer_Tick;

        }

        /// <summary>
        /// 通过线程方式去接收数据
        /// </summary>
        public void StarreavThread()
        {
            reavThread = new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        //阻塞线程,先读一个字节
                        //没有数据就会阻塞,直到有数据才会执行
                        int first = serial.ReadByte();
                        int len = serial.BytesToRead;//获取剩下缓冲区中数据的字节数。
                        byte[] left = new byte[len];
                        int nRead = serial.Read(left, 0, len);

                        //合并数据到 data
                        byte[] data= new byte[1+len];
                        data[0] = (byte)first;
                        for(int i=0;i<len;i++)
                        {
                            data[1 + i] = left[i];
                        }

                        //获取原有的内容
                        String strText = tbxJS.Text;
                        String content = Encoding.GetEncoding("GB2312").GetString(data);
                        String time = DateTime.Now.ToString("HH:mm:ss.fff:");

                        tbxJS.Text = strText + "\r\n" + time + content;

                    }
                    catch (Exception e)
                    {
                        break;
                    }
                }
            });
            reavThread.Start();
        }



        #region 初始化UI
        /// <summary>
        /// 初始化UI
        /// </summary>
        public void InitUI()
        {
            //获取本机的所有的串口名称
            string[] _porNames = SerialPort.GetPortNames();
            foreach (string _porName in _porNames)
            {
                this.cbxCKMC.Items.Add(_porName);
            }
            this.cbxCKMC.SelectedIndex = 0;//默认选中第一个

            //设置波特率
            string[] baudRates = { "9600", "14400", "19200", "38400", "57600", "115200" };
            foreach (string baudRate in baudRates)
            {
                this.cbxBTL.Items.Add(baudRate);
            }
            this.cbxBTL.SelectedIndex = 0;


            //数据位
            string[] dataBits = { "8", "7", "6", "5", };
            foreach (string s in dataBits)
            {
                this.cbxSJW.Items.Add(s);
            }
            this.cbxSJW.SelectedIndex = 0;

            //奇偶校验
            Parity[] parities = { Parity.None, Parity.Odd, Parity.Even, Parity.Mark, Parity.Space };
            foreach (Parity s in parities)
            {
                this.cbxJOJY.Items.Add(s);
            }
            this.cbxJOJY.SelectedIndex = 0;


            //停止位
            StopBits[] stopBits = { /*StopBits.None, */StopBits.One, StopBits.Two, StopBits.OnePointFive };
            foreach (StopBits s in stopBits)
            {
                this.cbxTZW.Items.Add(s);
            }
            this.cbxTZW.SelectedIndex = 0;

        }
        #endregion

        #region 打开串口
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDKCK_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnDKCK.Text == "打开串口")
                {
                    string _cbxCKMC = this.cbxCKMC.SelectedItem.ToString();//窗口名称
                    string _cbxBTL = this.cbxBTL.SelectedItem.ToString();//波特率
                    string _cbxSJW = this.cbxSJW.SelectedItem.ToString();//数据位
                    string _cbxJOJY = this.cbxJOJY.SelectedItem.ToString();//奇偶校验
                    string _cbxTZW = cbxTZW.SelectedItem.ToString();//停止位

                    serial.PortName = _cbxCKMC;
                    serial.BaudRate = Convert.ToInt32(_cbxBTL);
                    serial.DataBits = Convert.ToInt32(_cbxSJW);
                    serial.Parity = (Parity)Enum.Parse(typeof(Parity), _cbxJOJY);
                    serial.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _cbxTZW);

                    serial.Open();
                    StarreavThread();

                    groupBox1.Enabled = false;
                    btnDKCK.Text = "关闭串口";
                }
                else
                {
                    serial.Close();
                    groupBox1.Enabled = true;
                    btnDKCK.Text = "打开串口";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        #endregion

        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butFS_Click(object sender, EventArgs e)
        {
            if (serial.IsOpen)
            {
                String StrMsg = tbxFS.Text;
                byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(StrMsg);
                serial.Write(bytes, 0, bytes.Length);
            }
        }

        /// <summary>
        /// 自动发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            try
            {
                //如果勾选
                if (checkBox1.Checked)
                {
                    int intervaar = Convert.ToInt32(tbxFSJG.Text);//获取间隔时间
                    timer.Interval = intervaar;
                    timer.Start();//开始执行
                }
                else
                {
                    timer.Stop();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 定时器响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            butFS_Click(null, null);
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormModnus_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serial.IsOpen)
            {
                serial.Close();
            }
        }
    }
}

 

posted @ 2024-05-06 17:05  野码  阅读(34)  评论(0编辑  收藏  举报