c#串口发送数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bayinglong/article/details/72672834
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);

            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/bayinglong/article/details/72672834