c#串口发送数据

来源:互联网 发布:美利坚仓储淘宝王 下载 编辑:程序博客网 时间:2024/05/22 03:49
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 串口1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {            for (int i = 0; i < 256;i++ )            {                string a = i.ToString("x").ToUpper();                string b = "0X" + a;                if (i<16)                {                    b = "0X0" + a;                }                comboBox1.Items.Add(b);            }            comboBox1.Text = "0X00";        }        private void button1_Click(object sender, EventArgs e)        {            string a = comboBox1.Text.Substring(2, 2);            byte[] buffer = new byte[1];//只需要1bity            buffer[0] = Convert.ToByte(a,16);            try            {                serialPort1.Open();                serialPort1.Write(buffer,0,1);                serialPort1.Close();                label2.BackColor = Color.Red;            }            catch (System.Exception ex)            {                if (serialPort1.IsOpen)//属性调用                {                    serialPort1.Close();                }                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK);            }        }    }}
原创粉丝点击