当前位置:网站首页>新手入门上位机开发 C#语言:PC串口发送数据
新手入门上位机开发 C#语言:PC串口发送数据
2022-07-30 02:29:00 【最早的早安...】
题目概述:
VS2017开发环境
PC串口发送数据
编程:
namespace _004_7_28
{
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++)//0x00~0xff
{
str = i.ToString("x").ToUpper();//ToString("x")是将数字转换为16进制字符串,ToUpper是将字符串所有字符大写
//comboBox1.Items.Add("0x" + (str.Length == 1 ? "0" + str : str));
if (str.Length == 1)
{
str = "0" + str;//如果是一位的(0xA),此时为了对齐,在数据前加一个字符“0”(0x0A)
}
comboBox1.Items.Add("0x" + str);//统一添加“0x”
}
comboBox1.Text = "0x00";//初始值
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)//按键单击事件
{
string data = comboBox1.Text;//存储当前下拉框内容
string convertdata = data.Substring(2, 2);//把字符分开 将“0x"忽略
byte[] buffer = new byte[1];//数据一个字节就够用了
buffer[0] = Convert.ToByte(convertdata, 16);//将字符串转化为byte型变量(byte相当于unsigned char
try//防止出错
{
serialPort1.Open();//如果串口打开失败
serialPort1.Write(buffer, 0, 1);//如果是写数据出错 发送buffer数组 从0开始 发送1个字节
serialPort1.Close();//如果串口关闭失败
}
catch//如果出错就执行此程序
{
if(serialPort1.IsOpen)//判断串口是否打开成功
{
serialPort1.Close();//如果是写数据出错,此时窗口状态为开,就应该关闭串口,防止下次不能使用,串口是不能重复打开和关闭的
}
MessageBox.Show("端口错误", "错误");
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
}
}
上机实践:
由于没有连接端口,所以发送数据报错。
边栏推荐
- English grammar_indefinite pronouns -some & any
- 1050的显卡,为何在Steam上的显卡使用率排行榜一直都是前五
- 记一次搭建conda虚拟环境
- 解决:npm ERR code ELIFECYCLE npm ERR errno 1(安装脚手架过程中,在npm run dev 时发生错误)
- Mysql中事务是什么?有什么用?
- Not enough information to list load addresses in the image map. (STM32 compilation error)
- [深入研究4G/5G/6G专题-45]: 5G Link Adaption链路自适应-1-总体架构
- 超详细的MySQL基本操作
- The role of interface testing
- 力扣(LeetCode)210. 课程表 II(2022.07.29)
猜你喜欢
随机推荐
go bidirectional streaming mode
[Notes] Stuttering word segmentation to draw word cloud map
Understanding the prototype chain in js, what problem does the prototype chain solve?
机器学习1一回归模型(一)
【服务器存储数据恢复】华为OceanStor某型号存储raid5数据恢复案例
机器学习(十五)异常检测
DAP data processing process
HCIP 第十五天
基于蒙特卡诺的风场景模型出力(Matlab代码实现)
Postgresql daily operation and maintenance skills, suitable for beginners
信息系统项目管理师核心考点(五十四)配置项分类、状态与版本
go jwt使用
Implementation of Portable VR in Unity
Teach you how to achieve a flowing gradient border
ROS 2知识:通信协议 DDS/RTPS
Sublime does background transparency and column editor
Not enough information to list load addresses in the image map. (STM32 compilation error)
MPLS VPN跨域-optionC2
【2023海康威视提前批笔试题】~ 题目及参考答案
Leetcode.19 删链表倒数第 N 个结点(栈/先后指针)









