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

本文详细描述了如何使用C#在Windows应用中创建一个串口发送数据的程序,包括控件选择、遇到的问题解决、代码实现以及测试过程,特别提到了数据十六进制转换和串口连接管理的注意事项。
摘要由CSDN通过智能技术生成

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

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

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

 

目录

1、控件的选择与摆放:

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

3、整体代码贴出:

4、测试效果展示:

5、测试工程下载:

6、设计缺陷解释:


1、控件的选择与摆放:

 一共摆放以下几个组件:

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

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

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

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

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

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

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

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

3、整体代码贴出:

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

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

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

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

NULL指向我

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

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

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

打赏作者

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

抵扣说明:

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

余额充值