The project that I want to do is control dc motors using two methods: 1) using Hc-05 Bluetooth module and AMR Voice app. 2) using dual joystick.
the two works great separately, however when I combine both sketches only joystick can control the dc motors , the other method is not responding. I complied the code but no error is shown. I think there is something wrong in the code but I don't know where. Could you please help.
P.S: I use Arduino Nano
#include <SoftwareSerial.h>
//hc-05 bluetooth module
SoftwareSerial BT(5, 6); //RX, TX respetively
String voice;
//dc motors
int motor1pin1 = 12;
int motor1pin2 = 11;
int motor2pin1 = 10;
int motor2pin2 = 9;
//joystick
int Xpin = A0;
int Xvalue;
int Xvalue2;
void setup() {
// put your setup code here, to run once:
BT.begin(9600);
Serial.begin(9600);
pinMode(motor1pin1, OUTPUT);
pinMode(motor1pin2, OUTPUT);
pinMode(motor2pin1, OUTPUT);
pinMode(motor2pin2, OUTPUT);
//set joystick to be input
pinMode(Xpin, INPUT);
}
void forward()
{
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
}
void backward()
{
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, HIGH);
}
void stopit()
{
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, LOW);
}
void loop() {
//use bluetooth module and AMR Voice app to control dc motors
while (BT.available()) { //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = BT.read(); //Conduct a serial read
if (c == '#') {
break; //Exit the loop when the # is detected after the word
}
voice += c; //Shorthand for voice = voice + c
}
if (voice.length() > 0) {
Serial.println(voice);
if (voice == "*forward")
{
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
}
else if (voice == "*backward")
{
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, HIGH);
}
else if (voice == "*left")
{
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
}
else if (voice == "*right")
{
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, HIGH);
}
else if (voice == "*stop")
{
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, LOW);
}
voice = "";
}
//read the values of the joystick
Xvalue = analogRead(Xpin);
Xvalue2 = analogRead(Xpin);
//controlling the motor using the joystick
if (Xvalue > 800) { //forward
forward();
}
else { //stop
stopit();
}
if (Xvalue2 < 100) { //backward
backward();
}
}