蓝牙调用串口发送数据

 自己调试通过并能正常运行

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;
using System.Text.RegularExpressions;
using System.IO.Ports;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SerialPort sp = new SerialPort();
        SerialPort sp2 = new SerialPort();
        
        private void Form1_Load(object sender, EventArgs e)
        {
            //检测并添加串口
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())//获取当前计算机的串行端口名的数组

            {                
                cbSerial.Items.Add(s);//添加到对应的下拉列表中
            }
            sp.WriteTimeout = 3000;
            sp.ReadTimeout = 3000;

            sp.ReceivedBytesThreshold = 1;

            sp.RtsEnable = true;

            sp.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//订阅委托

            cbSerial.SelectedIndex = 0; //设置cbSerial的默认选项
        }
        //接收数据事件

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

        {
            int length = sp.BytesToRead;

            byte[] recData = new byte[length];

            sp.Read(recData, 0, length);

            string recText = Encoding.GetEncoding("GB2312").GetString(recData);

            //更新接收区

            txtReceive.Invoke(new EventHandler(delegate { txtReceive.AppendText(recText); }));

        }

        //将接受到的内容显示出来

        private void AddContent(string content)

        {


            this.BeginInvoke(new MethodInvoker(delegate

            {


                txtReceive.AppendText(content);

                txtReceive.AppendText("\r\n");

            }));

        }

        //打开相应端口

        private void btn_Open_Click(object sender, EventArgs e)

        {
        }

        //发送数据

        public bool sendData(byte[] date)

        {
            if (sp.IsOpen)
            {
                try
                {
                    sp.Write(date, 0, date.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 btnSend_Click(object sender, EventArgs e)

        {


        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void txtReceive_TextChanged(object sender, EventArgs e)
        {

        }

        private void btn_Open_Click_1(object sender, EventArgs e)
        {
            if (cbSerial.Items.Count == 0)
            {
                MessageBox.Show("没有发现串口,请检查线路!");
                return;
            }

            if (sp.IsOpen == false)//端口未打开,打开端口
            {
                //设置端口属性
                sp.PortName = cbSerial.SelectedItem.ToString();//COM4
                sp.BaudRate = 19200;//设置比特率
                sp.DataBits = 8;//设置数据位长度
                sp.Parity = Parity.None;//获取或设置奇偶校验检查协议
                sp.StopBits = StopBits.One;//设置停止位
                sp2.PortName = cbSerial.SelectedItem.ToString();//COM4
                sp2.BaudRate = 19200;//设置比特率
                sp2.DataBits = 8;//设置数据位长度
                sp2.Parity = Parity.None;//获取或设置奇偶校验检查协议
                sp2.StopBits = StopBits.One;//设置停止位
                try
                {
                    sp.Open();//打开串口
                    btnSend.Enabled = true;//可发送数据
                    MessageBox.Show(sp.PortName + "被打开!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btn_Open.Text = "关闭串口";
                //pictureBox1.BackColor = System.Drawing.Color.Green;
            }
            else//串口已经被打开,关闭窗口

            {
                try
                {
                    sp.Close();
                    btnSend.Enabled = false;//端口已经被关闭不可编辑数据
                    MessageBox.Show(sp.PortName + "被打开!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btn_Open.Text = "打开串口";
            }
        }

        private void btnSend_Click_1(object sender, EventArgs e)
        {
            byte[] sendData = null;

            if (!sp.IsOpen) //如果没打开
            {
                MessageBox.Show("请先打开串口!", "Error");
                return;
            }
            String strSend = txtSend.Text;
            try
            {
                sendData = Encoding.UTF8.GetBytes(txtSend.Text.Trim());
                sp.Write(sendData, 0, sendData.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
            }
        }

        private void cbSerial_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值