Hello,
I'm trying to control servos using an HC05 module throught my phone. However I can't make the servo move.
I'm using an arduino mega. the servo is connect to the 11th pin and the HC05 to the 0 and 1 pins. they are powered using the 5V pin from the mega however I've already tried using an external power source and I had the same issue.
Here's the code
#include<SoftwareSerial.h>
#include<Servo.h>
Servo x;
const byte servoPin = 11;
SoftwareSerial bluetooth(0, 1);
void setup()
{
x.attach(servoPin);
Serial.begin(9600);
bluetooth.begin(9600);
}
void loop()
{
if (bluetooth.available() > 0) //if bluetooth module is transmitting data
{
int pos = bluetooth.parseInt();
Serial.println(pos);
x.write(pos); //move servo head to the given position
}
}
The code comes from another post from the forum :
Any idea why my servo won't move when sending values into the terminal from my phone ? also the servo motor is hard and I can't rotate it with my hands when it's powered.
Start but not using pins 0 and 1 as they are used by the Serial interface, nor do you need to use SoftwareSerial as the Mega has 4 hardware serial interfaces so the Serial monitor and code uploading can be on Serial and bluetooth on say Serial1 on pins 18 and 19
Hi !
Not sure I get what you mean, I just changed the rx and tx pins to 19 and 18, however nothing changed the servo is still not responsive. What do you mean by not using SoftwareSerial ?
SoftwareSerial is used to add a second serial interface to boards like the Uno or Nano that only have a single hardware serial interface. This is not necessary when using a Mega because it has 4 independent hardware serial interface named Serial, Serial1, Serial2 and Serial3. Each of them have their own dedicated Tx and Rx pins
So, instead of using pins 0 and 1 as Rx and Tx on the Serial interface you can use pins 19 and 18 as Rx and Tx pins on the Serial1 interface
If you use SoftwareSreial on pins 0 and 1 it will almost certainly not work because it clashes with their use by the Serial interface
Here is your sketch rewritten to use Serial1 on pins 19 and 18 to which the Bluetooth module should be connected
#include <Servo.h>
Servo x;
const byte servoPin = 11;
void setup()
{
x.attach(servoPin);
Serial.begin(9600);
Serial1.begin(9600);
}
void loop()
{
if (Serial1.available() > 0) //if bluetooth module is transmitting data
{
int pos = Serial1.parseInt();
Serial.println(pos);
x.write(pos); //move servo head to the given position
}
}
Another issue that you may face is if whatever is sending to Bluetooth adds a line ending such as Carriage Return or Linefeed to the data because that will be read by the sketch and will be interpreted as a Servo position of zero
Wow thank you for the explanation I managed to make it work using your sketch. I had no idea about those serial interfaces, this will be really useful for the rest of my project. Thank you for the time !