今天主要写一个串口数据发送的应用程序,只专门用来发送数据,具体效果图如下
1.功能要求
发送数据,数据由下拉框进行选择,然后点击按钮进行发送
2.功能实现
(1)上位机界面实现
界面看起来很简单,可以自己怎么喜欢怎么放置,主要有3个组件:
label显示“数据”二字
下拉框用于选择要发送的数据(主要为了体现使用下拉框)
按钮点击发送数据操作
重点是串口加入,设置串口的属性,如图需要在组件中拖串口组件到窗体中,还需要设置串口的属性,串口名称,波特率等等。。。
(2)后端代码实现
主要是分为2点
下拉框中元素的添加和串口发送
using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace SerialPort{public partial class Form1 : Form{public Form1(){InitializeComponent();}//窗口创建初始化函数private void Form1_Load(object sender, EventArgs e){String str;//用来临时存储I大写的十六进制格式字符串for (int i = 0; i < 256; i++)//256个{str = i.ToString("x").ToUpper();//ToString("x")是将数字转换为16进制字符串,ToUpper()是将字符串所有字母转换为大写if (str.Length == 1)str = "0" + str;//如果是一位的比如0xA,此时为了对齐,在数据前加一个字符“0”(0x0A)comboBox1.Items.Add("0x" + str);//统一添加0x}comboBox1.Text = "0x00";//初试值}private void button1_Click(object sender, EventArgs e){String data = comboBox1.Text;//存储当前下拉框的内容String convertdata = data.Substring(2, 2);//获取要发送的数据后两位byte[] buffer = new byte[1];//用来存储数据buffer[0] = Convert.ToByte(convertdata, 16);//将字符串转化为byte型变量try//防止出错{serialPort1.Open();//打开串口serialPort1.Write(buffer, 0, 1);//发送数据serialPort1.Close();//关闭串口}catch//如果出错执行以下代码{if (serialPort1.IsOpen)//如果事先端口就已经打开了就关闭端口serialPort1.Close();MessageBox.Show("端口错误", "错误");}}}}
附一下代码下载链接
serialport