发送案例:
代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // 窗体创建时执行 private void Form1_Load(object sender, EventArgs e) { string str_num; // 构建combobox1列表 for(int i = 0; i < 256; i++) { str_num = i.ToString("x").ToUpper(); if(str_num.Length == 1) { str_num = "0" + str_num; } comboBox1.Items.Add("0x" + str_num); } comboBox1.Text = "0x00"; // 设置默认值 } private void button1_Click(object sender, EventArgs e) { string str_num = comboBox1.Text; // 获取combobox1的值 string Ox_num = str_num.Substring(2, 2); // 截取十六进制数值 byte[] buffer = new byte[1]; // 定义一个字节的数据 buffer[0] = Convert.ToByte(Ox_num, 16); // 将16进制的字符串转换为byte类型 // 防止出错 try { serialPort1.Open(); // 打开串口 serialPort1.Write(buffer, 0, 1); // 写入 serialPort1.Close(); // 关闭串口 } catch(Exception err) { if (serialPort1.IsOpen) { // 如果串口为开的,那么关闭 serialPort1.Close(); } MessageBox.Show(err.ToString(), "错误提示"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } // 窗体创建时执行 private void Form1_Load(object sender, EventArgs e) { string str_num; // 构建combobox1列表 for(int i = 0; i < 256; i++) { str_num = i.ToString("x").ToUpper(); if(str_num.Length == 1) { str_num = "0" + str_num; } comboBox1.Items.Add("0x" + str_num); } comboBox1.Text = "0x00"; // 设置默认值 } private void button1_Click(object sender, EventArgs e) { string str_num = comboBox1.Text; // 获取combobox1的值 string Ox_num = str_num.Substring(2, 2); // 截取十六进制数值 byte[] buffer = new byte[1]; // 定义一个字节的数据 buffer[0] = Convert.ToByte(Ox_num, 16); // 将16进制的字符串转换为byte类型 // 防止出错 try { serialPort1.Open(); // 打开串口 serialPort1.Write(buffer, 0, 1); // 写入 serialPort1.Close(); // 关闭串口 } catch(Exception err) { if (serialPort1.IsOpen) { // 如果串口为开的,那么关闭 serialPort1.Close(); } MessageBox.Show(err.ToString(), "错误提示"); } } } }