目标:
让ardiuno检查它是否通过蓝牙连接到android。然后在连接时执行动作,如果未连接则重新连接。
我正在使用什么:
Bluesmirf silver with arduino uno 和 note 3
到目前为止我所做的:
[阿杜诺代码]
Bluesmirf 处于主模式自动连接。arduino 应该检查 android 应用程序是否正在发送 H 字符。如果是,则意味着它已连接。如果没有,则需要继续重新连接。
#include <SoftwareSerial.h>
#include <TextFinder.h>
int bluetoothTx = 2; // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = 3; // RX-I pin of bluetooth mate, Arduino D3
boolean running = false;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
Serial.begin(9600); // Begin the serial monitor at 9600bps
bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps
bluetooth.print("$"); // Print three times individually
bluetooth.print("$");
bluetooth.print("$"); // Enter command mode
delay(100); // Short delay, wait for the Mate to send back CMD
bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity
delay(100);
bluetooth.begin(9600); // Start bluetooth serial at 9600
}
void loop()
{
//Check If Connected
if(bluetooth.available()) // If the bluetooth sent any characters
{
//Check if bluetooth recieved an H and store in a value
char val = bluetooth.read();
if(val == 'H')
{
running = true;
}
else if(val != 'H')
{
running = false;
}
}
else if(!bluetooth.available())
{
running = false;
}
//Actions to perform if arduino is connected or not connected
if(running == true)
{
//It's connected so wait 5 seconds
delay(5000);
}
else if(running == false)
{
//It's not connected: Attempt to reconnect
bluetooth.print("$"); // Print three times individually
bluetooth.print("$");
bluetooth.print("$"); // Enter command mode
delay(100); // Short delay, wait for the Mate to send back CMD
bluetooth.println("C,30196692D7C0");
delay(500);
bluetooth.println("---");
delay(3000);
}
}
[安卓代码]
这是安卓应用程序在连接应用程序后发送 H 的方法。
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = (msg).getBytes();
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
边注:
我已经尝试了很多方法来让这个 arduino 检查它是否连接。我 3 周前才刚刚开始编程,所以这变得越来越困难。任何帮助,将不胜感激。