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码形式逐个发出,

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

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

相关推荐
ClutchoQ5 分钟前
【你指的API是哪个API?软件工程师跨服聊天实录】
笔记·其他
二哈赛车手2 小时前
新人笔记---Spring AI的Advisor以及其底层机制讲解(涉及源码),包含一些遇见的Spring AI的Advisor缺陷问题的解决方案
java·人工智能·spring boot·笔记·spring
red_redemption3 小时前
自由学习记录(181)
学习
wuxinyan1233 小时前
大模型学习之路007:RAG 零基础入门教程(第四篇):生成侧核心技术与大模型集成
人工智能·学习·rag
阿豪只会阿巴4 小时前
【没事学点啥】TurboBlog轻量级个人博客项目——Turbo Blog 项目学习与上线指南
开发语言·python·学习·状态模式
Slow菜鸟4 小时前
Docker 学习篇(三)| Docker安装指南(Linux版)
linux·学习·docker
Tutankaaa4 小时前
知识竞赛软件SaaS版 vs 本地部署
人工智能·经验分享·笔记·学习
小仙女的小稀罕4 小时前
培训要点写不完不会整理?规范培训转待办可这样操作
大数据·人工智能·学习·自然语言处理·语音识别
许长安4 小时前
RPC 异步调用基本使用方法:基于官方helloworld-async 示例
c++·经验分享·笔记·rpc
Wallace Zhang5 小时前
SimpleFOC源码学习10(v2.3.2) - 电流传感器CurrentSense.cpp与CurrentSense.h
驱动开发·stm32·学习·电流环·simplefoc·foc电机控制