-1

I am using HC-05 Bluetooth module to control two servos. I use Bluetooth terminal in my android phone to control them.

Problem is that myServo1 is moving like I want but I can't control myServo2. Code is reading the variable a but it can't read variable b.

#include <SoftwareSerial.h>
#include <Servo.h>
Servo myServo1;
Servo myServo2;
int servo;
SoftwareSerial BT(2, 3); 
void setup()  
{
myServo1.attach(11);
myServo2.attach(10);
servo = 90;


Serial.begin(9600);
BT.begin(9600);
}
char a; 
char b;
void loop() 
{
 if (BT.available())
{
a=(BT.read());
b = (BT.read());
if (a=='1')
{
  myServo1.write(180);
  delay(50);


}
if (a=='2')
{
  myServo1.write(-180);
  delay(50);


 }
  if (b=='3')
{
  myServo2.write(90);
  delay(50);


}
  if (b=='4')
{
  myServo2.write(-90);
  delay(50);


}
}
}

Where is the problem?

1
  • your sketch has no debugging code .... why are you not printing the values of a and b to the serial monitor?
    – jsotola
    Commented Mar 29, 2020 at 2:55

1 Answer 1

0

When using

if(BT.available())

that's doing the same as

if(BT.available() > 0)

But then you are reading 2 bytes, though you cannot be sure, that there are 2 bytes to read. The data is transmitted serially, so even when you send it on your phone in one bunch, it does not get transmitted as bunch.

Try to use

if(BT.available() >= 2)

Also makes sure, that nothing else gets send over serial besides the numbers (often there is a line ending send implicitly depending on the used app).

8
  • If I use the " if(BT.available() >= 2) " it will mix the whole system Commented Mar 28, 2020 at 18:37
  • What do you mean by that? @engineerstudent
    – chrisl
    Commented Mar 28, 2020 at 19:08
  • It does not work properly. If I put "1", "2", "3" or "4" it turns one servo randomly. In some cases it doesn't work at all Commented Mar 28, 2020 at 19:12
  • Then you also have another problem. Have you confirmed, that the comminication with the HC-05 works correctly? You can do this by using a testsketch, where you forward the received data from bluetooth to the serial monitor. If everything is transmitted correctly, we can rule out that part
    – chrisl
    Commented Mar 28, 2020 at 19:16
  • I don't think that there is problem in the connection because if I use "BT.available()>0" and I type "1" or "2" then it work properly and turns the myServo1 between 180 and -180. Commented Mar 28, 2020 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.