首页 > 解决方案 > 有没有一种特殊的方法可以通过 arduino 通过 BLE 发送数据

问题描述

我目前正在尝试从我的 Arduino 卡 + Seeed BLE Shield HM-11 发送数据(主要是文本),但我有。我可以毫无问题地从我的 android 蓝牙终端发送文本,但是当我的手机从防护罩接收数据时,它不起作用并且不会引发任何异常。

请注意,LED 仅用于验证电话和屏蔽是否已连接。

#include <SoftwareSerial.h>   //Software Serial Port

#define RxD         3
#define TxD         4

#define PINLED      7

#define LEDON()     digitalWrite(PINLED, HIGH)
#define LEDOFF()    digitalWrite(PINLED, LOW)

#define DEBUG_ENABLED  1

SoftwareSerial Bluetooth(RxD, TxD);

void setup()
{
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
  pinMode(PINLED, OUTPUT);
  LEDOFF();

  setupBlueToothConnection();
}

void loop()
{
  char recvChar;

  while(true)
  {
    if (Bluetooth.available())
    { //check if there's any data sent from the remote bluetooth shield
      recvChar = Bluetooth.read();

      Serial.print(recvChar);
      if (recvChar == '1')
      {
        LEDON();
        Bluetooth.write("Led ON");
      }
      else if (recvChar == '0')
      {
        LEDOFF();
      }
    }
  }
}




/***************************************************************************
   Function Name: setupBlueToothConnection
   Description:  initilizing bluetooth connction
   Parameters:
   Return:
***************************************************************************/
void setupBlueToothConnection()
{



  Bluetooth.begin(9600);

  Bluetooth.print("AT");
  delay(400);

  Bluetooth.print("AT+DEFAULT");             // Restore all setup value to factory setup
  delay(2000);

  Bluetooth.print("AT+NAMESeeedBTSlave");    // set the bluetooth name as "SeeedBTSlave" ,the length of bluetooth name must less than 12 characters.
  delay(400);

  Bluetooth.print("AT+PIN0000");             // set the pair code to connect
  delay(400);

  Bluetooth.print("AT+AUTH1");             //
  delay(400);

  Bluetooth.print("AT+NOTI1");             //
  delay(400);


  Bluetooth.flush();

}

我希望该代码在收到“1”时回答“LED ON”,但没有任何反应

标签: androidarduinobluetoothbluetooth-lowenergy

解决方案


尝试从你的 loop() 代码中移除 while (true) {} 包装器。因为 Arduino 一遍又一遍地调用 loop(),所以 loop() 函数充当了一个 while (true) 循环。

让您的 loop() 函数永远不会返回 - 正如您的代码当前所做的那样 - 会阻止处理器执行其他操作,例如运行蓝牙堆栈。我还没有写过 Arduino 蓝牙代码,但是我在使用 Wifi 时看到了类似的问题:如果 loop() 耗时太长,后台功能可能会失败。

您更正后的 loop() 函数应如下所示:

void loop()
{
  char recvChar;

  if (Bluetooth.available())
  { //check if there's any data sent from the remote bluetooth shield
    recvChar = Bluetooth.read();

    Serial.print(recvChar);
    if (recvChar == '1')
    {
      LEDON();
      Bluetooth.write("Led ON");
    }
    else if (recvChar == '0')
    {
      LEDOFF();
    }
  }
}

推荐阅读