继续学习C#的桌面应用程序。
这次根据视频学习,简单的做了一下串口发送的小应用程序,能够根据设定的串口号发送选择好的一个字节数据,可选范围为256个。
首先是应用程序的界面,
另外添加了一个串口的控件,
串口控件的属性中,可以设置波特率、数据位、串口号等相关的设定。而且是,十分必要的!
然后是程序代码,如下,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 串口1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i;
string str; //用于存储i转换为的16进制字符
for (i = 0; i < 256; i++) //共计256个数据
{
str = i.ToString("x").ToUpper(); //i转换为16进制,并且转换为大写
if (str.Length == 1) //如果转换成的字符,只有1位
{
str = "0" + str; //那么,在str前边补0
}
comboBox1.Items.Add("0x"+str); //统一在前边添加0x
}
comboBox1.Text = "0x00"; //初始值显示0x00
}
private void button1_Click(object sender, EventArgs e) //按键单击事件
{
string str = comboBox1.Text; //存储按下时的值
string convertdata = str.Substring(2,2); //把字符分开,存储从第2位开始的两位数据
byte[] buffer = new byte[1]; //新建byte位,存储一个字节的数据
buffer[0]= Convert.ToByte(convertdata,16); //把字符串转化为byte型变量(16进制)(相当于单片机中的unsigned int)
try //出错检测
{
serialPort1.Open(); //打开串口
serialPort1.Write(buffer, 0, 1);//写入数据
serialPort1.Close(); //关闭串口
}
catch
{
if (serialPort1.IsOpen) //如果串口是打开状态
serialPort1.Close(); //就关闭串口
MessageBox.Show("串口错误","错误");
}
}
}
}
程序功能:下拉框选择要发送的1位数据,点击按键,就会按照指定的波特率往指定串口发送。