当前位置: 首页 > article >正文

C# 串口通信简单示例

C# 简单串口通信示例

  • 串口通信
  • 示例代码

串口通信

C# 串口通信主要操作:

  • 命名空间:using System.IO.Ports;
  • 获取端口:string[] ports = System.IO.Ports.SerialPort.GetPortNames();
  • 设置端口名:serialPort1.PortName = “COM1”; // 字符串
  • 设置波特率:serialPort1.BaudRate = 115200;// int.Parse(“115200”);
  • 设置数据位:serialPort1.DataBits = 1; // int.Parse(“1”);
  • 设置停止位:serialPort1.StopBits = StopBits.One;
    • StopBits.One:停止位1
    • StopBits.OnePointFive:停止位1.5
    • StopBits.Two:停止位2
  • 设置校验位:serialPort1.Parity = Parity.None;
    • Parity.None:无
    • Parity.Even:奇校验
    • Parity.Odd:偶校验
  • 打开串口:serialPort1.Open();
  • 关闭串口:serialPort1.Close();
  • 可读字节:serialPort1.BytesToRead;
  • 读取数据:serialPort1.Read(buffer, 0, len);
  • 写入数据:serialPort1.Write(buffer);
  • 接收事件: XXX_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);

示例代码

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;
using System.IO.Ports;

namespace serial_tools
{
    public partial class Form1 : Form
    {
        String serialPortName;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames(); // 获取本机可用串口端口
            comboBoxPort.Items.AddRange(ports);
            comboBoxPort.SelectedIndex = comboBoxPort.Items.Count > 0 ? 0 : -1; // 有可用端口显示第一个

            comboBoxBaudrate.Text = "115200"; // 默认波特率
            comboBoxDataBits.Text = "8"; // 默认数据位:8
            comboBoxStopbit.Text = "1"; // 默认停止位:1
            comboBoxCheck.Text = "无"; // 默认无校验
        }

        /// <summary>
        /// 重写 系统消息函数
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
           
            base.WndProc(ref m);
        }

        /// <summary>
        /// 串口数据接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int len = serialPort1.BytesToRead; // 获取可读字节数
            byte[] buff = new byte[len]; // 创建缓存数据数组
            serialPort1.Read(buff, 0, len); // 把数据读取到buff数组

            string str = Encoding.Default.GetString(buff); // Byte值转ASCII字符串

            Invoke((new Action(() => {
                if (checkBoxHexShow.Checked)
                {
                    textBoxRecv.AppendText(byteToHexStr(buff));
                }
                else
                { 
                    textBoxRecv.AppendText(str);                 
                }
            
            }))); // 对话框追加显示数据
        }


        public static string byteToHexStr(byte[] bytes)
        {
            string hexStr = "";
            try
            {
                if (bytes != null) {
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        hexStr += bytes[i].ToString("X2");
                        hexStr += " "; // 两个Hex数值以空格隔开
                    }
                }

                return hexStr;
            }
            catch (Exception)
            {
                return hexStr;
            }
        }

        /// <summary>
        /// 打开关闭串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPortOnOff_Click(object sender, EventArgs e)
        {
            if (buttonPortOnOff.Text == "打开串口") {
                try
                {
                    serialPort1.PortName = comboBoxPort.Text; // 获取选择的串口端口
                    serialPortName = comboBoxPort.Text;
                    serialPort1.BaudRate = int.Parse(comboBoxBaudrate.Text); // 获取选择的波特率
                    serialPort1.DataBits = int.Parse(comboBoxDataBits.Text); // 获取选择的数据位

                    // 设置停止位
                    if (comboBoxStopbit.Text == "1") { serialPort1.StopBits = StopBits.One; }
                    else if (comboBoxStopbit.Text == "1.5") { serialPort1.StopBits = StopBits.OnePointFive; }
                    else if (comboBoxStopbit.Text == "2") { serialPort1.StopBits = StopBits.Two; }

                    // 设置奇偶校验
                    if (comboBoxCheck.Text == "无") { serialPort1.Parity = Parity.None; }
                    else if (comboBoxCheck.Text == "奇校验") { serialPort1.Parity = Parity.Even; }
                    else if (comboBoxCheck.Text == "偶校验") { serialPort1.Parity = Parity.Odd; }

                    // 打开串口
                    serialPort1.Open();
                    buttonPortOnOff.Text = "关闭串口";

                }
                catch (Exception ex)
                {
                    MessageBox.Show("串口打开失败"+ ex.ToString(), "警告",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                try
                {
                    serialPort1.Close();
                }
                catch (Exception ex)
                { 
                
                }

                buttonPortOnOff.Text = "打开串口"; 
            }
        }

        /// <summary>
        /// 清空接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClearRecv_Click(object sender, EventArgs e)
        {
            textBoxRecv.Clear();
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSendData_Click(object sender, EventArgs e)
        {
            String Str = textBoxSend.Text.ToString(); // 获取发送文本框里的数据
            try
            {
                if (Str.Length > 0) {
                    serialPort1.Write(Str); // 串口发送数据
                }
            }
            catch (Exception)
            { 
            
            }
        }

        /// <summary>
        /// 清除发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClearSend_Click(object sender, EventArgs e)
        {
            textBoxSend.Clear();
        }

        private void comboBoxPort_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void comboBoxPort_MouseClick(object sender, MouseEventArgs e)
        {

        }
    }
}

窗体界面设计
在这里插入图片描述

运行效果
在这里插入图片描述


http://www.kler.cn/a/103637.html

相关文章:

  • Linux友人帐之日志与备份
  • 《动手学深度学习 Pytorch版》 10.2 注意力汇聚:Nadaraya-Watson 核回归
  • python集合
  • CentOS 系统安装和使用Docker服务
  • 【单元测试】--维护和改进单元测试
  • GIS 数据结构BSP树
  • 如何在 Bash 脚本中添加注释
  • 新成果展示:AlGaN/GaN基紫外光电晶体管的设计与制备
  • SylixOS BSP开发(八)
  • uniapp: 本应用使用HBuilderX x.x.xx 或对应的cli版本编译,而手机端SDK版本是 x.x.xx。不匹配的版本可能造成应用异常。
  • 模拟 Junit 框架
  • Jackson 反序列化失败,出现JSON: Unrecognized field
  • C语言之排序
  • 苹果将于8月31日举行今秋的第二场发布会
  • C语言进阶第九课 --------动态内存管理
  • 经典卷积神经网络 - NIN
  • RISC-V架构——中断委托和中断注入
  • Web开发中会话跟踪的隐藏表单字段(隐藏input)方法
  • 前端领域的插件式设计
  • 做自媒体一定要知道这个配音软件~