I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:
int output = 9; //I will be using to control a DC motor(LED is just for testing).
int output2 = 10;
char final[4];
char correct[4] = {'Q','W','E','R'};
int pass_true;
void setup() {
pinMode(output, OUTPUT);
pinMode(output2, OUTPUT);
Serial.begin(9600);
}
void loop() {
while(Serial.available()){
for(int i=0; i<4; i++){
final[i] = Serial.read();
}
for(int i=0; i<4; i++){
if(final[i]==correct[i]){
pass_true = 1;
}
else{
pass_true = 0;
break;
}
}
}
if(pass_true==1){
digitalWrite(output, HIGH);
Serial.println("ON");
delay(3000);
pass_true = 0;
}
else{
digitalWrite(output, LOW);
}
}
I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")
The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?
-
1Read and digest this: hacking.majenko.co.uk/reading-serial-on-the-arduinoMajenko– Majenko2015年10月20日 12:02:53 +00:00Commented Oct 20, 2015 at 12:02
-
Please start by verifying that the connection is even working, before trying to parse a message that "should" come in.aaa– aaa2016年12月02日 16:54:40 +00:00Commented Dec 2, 2016 at 16:54
-
Try using the serialLoopback sketch, how can you be sure it is set to 9600 baud anyway?aaa– aaa2016年12月02日 16:56:04 +00:00Commented Dec 2, 2016 at 16:56
2 Answers 2
Try using the following code you need to use String and concatenate that
String rcev_data="";
bool chk=false;
\#define output 9
\#define output2 10
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(output, OUTPUT);
pinMode(output2, OUTPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
while(Serial.available())
{
char rxx = Serial.read();
recv.concat(rxx);
delay(10);
if (recv == "QWER")
{
chk=1;
break;
}
else
chk=0;
}
if (chk)
{
digitalWrite(output,HIGH);
Serial.println("ON");
delay(3000);
chk=0;
}
else
{
digitalWrite(output,LOW);
}
recv="";
}
Instead of
while(Serial.available()){
please try
while(Serial.available() >= 4){
Depending on how your transmitting application is buffering the writes, the loop()'s password check may be triggering on a single byte of input each time.
You may also want to make the code a bit more fault-tolerant. For example what if there's a bit of noise in the line, or the operator pushes [Enter] first before entering the code. The input buffer will fill up a few characters, then the password will not match because it spans, say input bytes 3,4,5,6. Maybe throw away any old input based on elapsed time, etc.