Motor driver shield. I wanna control it using Bluetooth

I can't make the other if else occur. only W works
WASD with Q as stop

<CODE/>
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(2, OUTPUT);//
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  while (Serial.available() == 0)
  {}
  


if(Serial.read()=='W')
{
  digitalWrite(2,HIGH);
  analogWrite(5,255);
  digitalWrite(4,LOW);
  analogWrite(6,255);
  
} 

else if(Serial.read()=='S')
{
  digitalWrite(2,LOW);
  analogWrite(5,255);
  digitalWrite(4,HIGH);
  analogWrite(6,255);
  
}
else if(Serial.read()=='D')
{
digitalWrite(2,HIGH);
  analogWrite(5,50);
  digitalWrite(4,HIGH);
  analogWrite(6,50);
}
else
if(Serial.read()=='A')
{
  digitalWrite(2,LOW);
  analogWrite(5,50);
  digitalWrite(4,LOW);
  analogWrite(6,50);

}
else
if(Serial.read()=='Q')
{
   digitalWrite(2,LOW);
  analogWrite(5,0);
  digitalWrite(4,LOW);
  analogWrite(6,0);
 
}
}
<CODE/>

Don't put the Serial.read() in the if statements.
Do one Serial.read() right after the while statement and put the result into a int variable, then use that variable in the if statements.

String motion = "";


void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(2, OUTPUT);//
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  while (Serial.available() > 0)
  {
motion = Serial.read();
}
  


if(motion=='W')
{
  digitalWrite(2,HIGH);
  analogWrite(5,255);
  digitalWrite(4,LOW);
  analogWrite(6,255);
  
} 

else if(motion=='S')
{
  digitalWrite(2,LOW);
  analogWrite(5,255);
  digitalWrite(4,HIGH);
  analogWrite(6,255);
  
}
else if(motion=='D')
{
digitalWrite(2,HIGH);
  analogWrite(5,50);
  digitalWrite(4,HIGH);
  analogWrite(6,50);
}
else
if(motion=='A')
{
  digitalWrite(2,LOW);
  analogWrite(5,50);
  digitalWrite(4,LOW);
  analogWrite(6,50);

}
else
if(motion=='Q')
{
   digitalWrite(2,LOW);
  analogWrite(5,0);
  digitalWrite(4,LOW);
  analogWrite(6,0);
 
}
}

Make motion an int not string
Don't put the Serial.read inside the brackets.
Put it after the last bracket.
Put the while statement back to the way it was

Like this

void loop() {
  while (Serial.available() == 0)
  {}
	int motion = Serial.read();


Avoid using Strings on Arduino. Due to poor memory management, they lead to program crashes, especially on AVR based Arduinos like the Uno, Mega, etc.

Use char variables instead. This is faster, takes less program memory and above all, is reliable:

char motion = Serial.read();
...
if(motion=='W')
{

You can try using numbers, sometimes I encounter errors with using WASD

void loop() {
if(Serial.available()){
motion = Serial.read();
Serial.println(motion);
}
 
if(motion == '1'){ 

and then continue the code using numbers.

Did it work OK?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.