C#学习笔记4:PC串口发送数据

今日继续我的C#学习之路,今日学习制作PC串口发送数据的窗口程序

串口是单片机上位机开发的重点,本文围绕做一个通过PC端串口发送数据的程序进行实践学习,

文章提供源码与解释、整体工程文件

目录

1、控件的选择与摆放:

2、程序设计遇到的问题:

3、整体代码贴出:

4、测试效果展示:

5、测试工程下载:

6、设计缺陷解释:


1、控件的选择与摆放:

一共摆放以下几个组件:

其中串口组件需要注意的是设计名称与端口号别搞混了:

杂项中的PortName可以更换PC端口号,杂项的元素波特率等可以在程序中被程序语句更改

Name则是在项目中给其标注的名称

2、程序设计遇到的问题:

1、运行启动时找不到COM端口:

TIP:串口的打开语句必须要有COM端口有测试设备连接的情况下才能正常执行

2、数据十六进制、十进制发送转换问题:

3、对类属性的思想不太了解:

3、整体代码贴出:

cs 复制代码
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.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Serial_port
{
    public partial class Form1 : Form
    {
        int time;
        int count = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int i;
            string str1;

            for (i = 1; i < 100; i++)
            {
                comboBox3.Items.Add(i.ToString() + " 秒");// 初始化下拉框 延时 内容
            }

            for (int j = 0; j < 256; j++)
            {
                str1 = j.ToString("x").ToUpper();//ToString("x")是将数字转转换为l6进制字符串,ToUpper 是将字符串所有字符大写
                if(str1.Length==1)
                { str1 = "0" + str1; }//如果是一位的(0xA),此时为了对齐,在数据前加一个字符"0"(0x0A)
                comboBox1.Items.Add("0x" + str1);//统一添加"0x"
            }

            for (int k = 1; k < 10; k++)//初始化串口号下拉框内容
            {
                comboBox2.Items.Add("COM" + k.ToString()); //添加串口
            }

            for (int H = 0; H < 5; H++)//初始化串口波特率下拉框内容
            {
                switch (H)
                {
                    case 0: comboBox4.Items.Add("2400"); break;
                    case 1: comboBox4.Items.Add("4800"); break;
                    case 2: comboBox4.Items.Add("9600"); break;
                    case 3: comboBox4.Items.Add("115200"); break;
                }
            }

            comboBox1.Text = "0x00";//数据下拉框初始值
            comboBox2.Text = "COM1";//端口下拉框初始值
            comboBox3.Text = "1 秒";//延时下拉框初始值
            comboBox4.Text = "9600";//波特率下拉框初始值

            SerialPort.Close();   //关闭串行端口连接
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (SerialPort.IsOpen)//如果串口已经被打开
            {
                string str = comboBox3.Text;//将下拉框内容添加到一个变里中
                string data = str.Substring(0, 2);
                time = Convert.ToInt16(data);//得到设定定时值(整形)
                progressBar1.Maximum = time;//进度条最大数值
                timer1.Start();//开始计时
            }
            else
            {
                MessageBox.Show("请打开连接设备的串口", "串口发送提示");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //int[] a = new int[5];
            // a[0] = Convert.ToInt16(comboBox1.Text.Substring(2, 2));

            // a[1] = Convert.ToInt16(comboBox1.Text.Substring(3, 1));
            // a[3] = a[0] * 10 + a[1];
            
            count++; //记录过了几秒
            progressBar1.Value = count;//设置进度条进度
            if (count == time)
            {

                timer1.Stop();//时间到,停止计时
                System.Media.SystemSounds.Asterisk.Play();//提示音

                //串口写数据,这么写会让 0x 02中的 0和2都以ascll码形式发出(跳过了字符串中下标0、1的元素)
                SerialPort.Write(comboBox1.Text.Substring(2));
                //SerialPort.Write(a[0].ToString());

                MessageBox.Show("发送延时计时结束!本次串口数据已发送", "串口发送提示");
                count = 0;//使count归0,便于下次计时
            }
        }

        private void button2_Click(object sender, EventArgs e)//尝试打开串口
        {
            try
            {
                SerialPort.PortName = comboBox2.Text;//设置端口号
                SerialPort.BaudRate = Convert.ToInt32(comboBox4.Text);//设置端口波特率
                SerialPort.Open();                   //打开串口
                MessageBox.Show("当前串口有设备连接,串口已成功打开", "串口发送提示");
                //按键状态置位
                button2.Enabled = false;
                button3.Enabled = true;
            }
            catch
            {
                MessageBox.Show("端口无设备连接", "错误警告");
            }
        }

        private void button3_Click(object sender, EventArgs e)//尝试关闭串口
        {
            try
            {
                SerialPort.Close(); //关闭串口        
                //按键状态置位
                button2.Enabled = true;
                button3.Enabled = false;
                MessageBox.Show("已关闭串口", "串口发送提示");
            }
            catch
            {

            }
        }
        private void label1_Click(object sender, EventArgs e) { }
        private void label2_Click(object sender, EventArgs e) { }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { }
        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e) { }
        private void progressBar1_Click(object sender, EventArgs e) { }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { }
        private void comboBox4_SelectedIndexChanged(object sender, EventArgs e) { }

    }
}

4、测试效果展示:

有端口连接情况的检测:

端口、延时、波特率、数据都可以选择:

坚持先打开可用串口再发送数据原则:

发送计时与发送成功提示:

5、测试工程下载:

https://download.csdn.net/download/qq_64257614/89037007?spm=1001.2014.3001.5503

6、设计缺陷解释:

由于没有严谨的进行进制数据的处理

导致0x02在串口发送时会将0和2拆开并以ascll码形式逐个发出,

大家可以对照我的学习版进行针对性优化,

也欢迎大佬将优化方案或者结果私信我一起讨论:

相关推荐
dengqingrui1234 小时前
【树形DP】AT_dp_p Independent Set 题解
c++·学习·算法·深度优先·图论·dp
我的心永远是冰冰哒5 小时前
ad.concat()学习
学习
ZZZ_O^O5 小时前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
slomay6 小时前
关于对比学习(简单整理
经验分享·深度学习·学习·机器学习
hengzhepa7 小时前
ElasticSearch备考 -- Async search
大数据·学习·elasticsearch·搜索引擎·es
小小洋洋8 小时前
BLE MESH学习1-基于沁恒CH582学习
学习
m0_689618289 小时前
水凝胶发生器,不对称设计妙,医电应用前景广
笔记
Ace'9 小时前
每日一题&&学习笔记
笔记·学习
IM_DALLA9 小时前
【Verilog学习日常】—牛客网刷题—Verilog进阶挑战—VL25
学习·fpga开发·verilog学习
挥剑决浮云 -9 小时前
Linux 之 安装软件、GCC编译器、Linux 操作系统基础
linux·服务器·c语言·c++·经验分享·笔记