C#开发串口通信程序

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;

using System.IO.Ports;

namespace PowerControl
{
    public partial class Fm_Main : Form
    {
        private SerialPort comm = new SerialPort();
        //可变字符串类,用于存储接收到的字符
        private StringBuilder Builder = new StringBuilder();
        public Fm_Main()
        {
            InitializeComponent();
        }

        private void Fm_Main_Load(object sender, EventArgs e)
        {
            init();
           
            comm.NewLine = "
";
            comm.RtsEnable = true;
        }

        public void init()
        {
            btn_Send.Enabled = false;
            cbbComList.Items.AddRange(SerialPort.GetPortNames());
            if (cbbComList.Items.Count > 0)
            {
                cbbComList.SelectedIndex = 0;
            }
            cbbBaudRate.SelectedIndex = 6;
            cbbDataBits.SelectedIndex = 0;
            cbbStopBits.SelectedIndex = 0;
            cbbParity.SelectedIndex = 0;
            comm.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件   

        }

        void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {           
            int n = comm.BytesToRead;
            byte[] buf = new byte[n];
           
            comm.Read(buf, 0, n);
            //先清空
            Builder.Clear();

            //因为要访问ui资源,所以需要使用invoke方式同步ui
            this.Invoke((EventHandler)(delegate
            {               
                Builder.Append(Encoding.ASCII.GetString(buf));
                this.txGet.AppendText(Builder.ToString());

            }));
        }


        private void btn_Open_Click(object sender, EventArgs e)
        {
            //如果串口已经是打开状态,则此按钮关闭串口
            if (this.comm.IsOpen)
            {
                this.comm.Close();
                btn_Send.Enabled = false;
            }
            //串口关闭状态,打开之
            else
            {               
                comm.PortName = this.cbbComList.Text;
                comm.BaudRate = int.Parse(this.cbbBaudRate.Text);

                comm.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
                comm.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
                comm.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.SelectedItem.ToString());

                try
                {
                    comm.Open();
                }             
                catch (Exception ex)
                {
                    comm = new SerialPort();
                    MessageBox.Show(ex.Message);
                }

            }
           
            this.btn_Open.Text = comm.IsOpen ? "关闭串口" : "打开串口";            
            this.btn_Send.Enabled = comm.IsOpen;
        }

        /// <summary>        
        /// 发送数据        
        /// </summary>        
        /// <param name="sender"></param>        
        /// <param name="data"></param>        
        public bool SendData(byte[] data)
        {
            if (comm.IsOpen)
            {
                try
                {
                    comm.Write(data, 0, data.Length);//发送数据                   
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }



        private void btn_Send_Click(object sender, EventArgs e)
        {
           comm.Write(this.txSend.Text);


            byte[] sendData = null;
            sendData = strToHexByte(txSend.Text.Trim());
            if (this.SendData(sendData))  //发送数据成功计数           
            {
            }
        }

        /// <summary>        
        /// 字符串转换16进制字节数组        
        /// </summary>        
        /// <param name="hexString"></param>        
        /// <returns></returns>        
        private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
            return returnBytes;
        }

        private void Btn_ClosePower_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[6];
            data[0] = 0xDB;
            data[1] = 0xF1;
            data[2] = 0x00;
            data[3] = 0x02;
            data[4] = 0x00;
            data[5] = 0xCE;
            byte bb = new byte();
            for (int i = 0; i < 5; i++)
            {
                bb += data[i];
            }
            if (this.SendData(data))        
            {
                MessageBox.Show("发送成功!");
            }

        }

        private void btn_OpenPower_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[6];
            data[0] = 0xDB;
            data[1] = 0xF1;
            data[2] = 0x00;
            data[3] = 0x01;
            data[4] = 0x00;
            data[5] = 0xCD;
            if (this.SendData(data))          
            {
                MessageBox.Show("发送成功!");
            }
        }
    }
}

 

你可能感兴趣的