Hello everyone!
I am working on a little project that is basically a door opener with Bluetooth presence detection.
Here is how it works.
A HC-05 Bluetooth module is connected to an Arduino. The HC-05 is constantly inquiring near devices. Once a whitelisted device has been found the door will open and set the status for that device to "entered". Otherwise the door would constalty be opening.
Exactly here is the problem. Once the device has passed the door, and the device gets OUT of reach of the HC-05 I need the device status to be set back to "false".
But since the HC-05 is constantly inquiring and might find different devices I can not be sure to set the status of the correct device.
Here is what the output of the HC-05 will look like:
+INQ:BCF5:AC:74DDB7,5A020C,FFD2
+INQ:C829:2A:144E44,0,FFB7
+INQ:C829:2A:144E44,0,FFB7
+INQ:C829:2A:144E44,0,FFB9
+INQ:BCF5:AC:74DDB7,5A020C,FFD6
+INQ:BCF5:AC:74DDB7,5A020C,FFD7
+INQ:BCF5:AC:74DDB7,5A020C,FFD6
+INQ:BCF5:AC:74DDB7,5A020C,FFD8
+INQ:BCF5:AC:74DDB7,5A020C,FFD7
and so on...
Here is my code:
int doorPin = 13;
int commaPosition;
String serialData;
String michaelMac = "+INQ:BCF5:AC:74DDB7\n";
String maikeMac = "+INQ:ABCD:AC:74DDB7\n";
unsigned long currentTime, michaelTime, maikeTime;
boolean michaelEntered, maikeEntered;
void setup() {
Serial.begin(9600);
Serial.println("Waiting for input");
pinMode(doorPin, OUTPUT);
michaelTime = currentTime;
maikeTime = currentTime;
}
void loop() {
currentTime = millis();
while (Serial.available() > 0) {
char received = Serial.read();
serialData += received;
if (received == '\n') {
String mac = getToken(serialData, ',', 0);
Serial.print(mac); //debug
Serial.println(currentTime); //debug
Serial.println(michaelTime); //debug
Serial.println(maikeTime); //debug
if(mac != michaelMac && currentTime - michaelTime >= 10000) {
Serial.println("Michael is not in reach!");
michaelEntered = false;
}
if(mac != maikeMac && currentTime - maikeTime >= 10000) {
Serial.println("Maike is not in reach!");
maikeEntered = false;
}
if (mac == michaelMac) {
michaelTime = currentTime;
if (michaelEntered == false) {
Serial.print("MAC from Michael found: " + michaelMac);
openDoor();
michaelEntered = true;
}
}
if (mac == maikeMac) {
maikeTime = currentTime;
if (maikeEntered == false) {
Serial.print("MAC from Maike found: " + maikeMac);
openDoor();
maikeEntered = true;
}
}
serialData = "\0";
}
}
}
String getToken(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for(int i = 0; i <= maxIndex && found <= index; i++) {
if(data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void openDoor() {
digitalWrite(doorPin, HIGH);
delay(1000);
digitalWrite(doorPin, LOW);
}
I hope someone can push me in the right direction.
If I need to explain anything, please let me know!
Thanks!