I have been trying to make an arduino project which changes the motor directions based on serial input. I have tried everything on google search. the arduino only responds sometimes. I know my board is not fried because the same happens on other boards.
code:
const int motorApinA = 6;
const int motorApinB = 7;
const int motorBpinA = 8;
const int motorBpinB = 9;
const int LED_Strip_pos_pin = 2;
void setup() {
Serial.begin(9600);
pinMode(motorApinA, OUTPUT);
pinMode(motorApinB, OUTPUT);
pinMode(motorBpinA, OUTPUT);
pinMode(motorBpinB, OUTPUT);
pinMode(LED_Strip_pos_pin, OUTPUT);
Serial.write("yay, your code is working");
}
void loop()
{
if (Serial.read() == 'F')
{
digitalWrite(motorApinA, HIGH);
digitalWrite(motorApinB, LOW);
digitalWrite(motorBpinB, HIGH);
digitalWrite(motorBpinA, LOW);
Serial.println("Done!");
}
if (Serial.read() == 'B')
{
digitalWrite(motorApinB, HIGH);
digitalWrite(motorApinA, LOW);
digitalWrite(motorBpinA, HIGH);
digitalWrite(motorBpinB, LOW);
Serial.println("Done!");
}
if (Serial.read() == 'L')
{
digitalWrite(motorApinA, HIGH);
digitalWrite(motorApinB, LOW);
digitalWrite(motorBpinA, HIGH);
digitalWrite(motorBpinB, LOW);
Serial.println("Done!");
}
if (Serial.read() == 'R')
{
digitalWrite(motorApinB, HIGH);
digitalWrite(motorApinA, LOW);
digitalWrite(motorBpinB, HIGH);
digitalWrite(motorBpinA, LOW);
Serial.println("Done!");
}
if (Serial.read() == 'S')
{
digitalWrite(motorApinA, LOW);
digitalWrite(motorApinB, LOW);
digitalWrite(motorBpinB, LOW);
digitalWrite(motorBpinA, LOW);
Serial.println("Done!");
}
}
sorry if I asked this on the wrong site :(
Each time you call Serial.read()
, it reads the first char in the buffer. Let's say you have a 'B'
in your buffer. Unless your program happens to be at if (Serial.read() == 'B')
, it doesn't trigger the action you want. You should store a returned value from Serial.read()
and evaluate it.
void loop() {
char c = Serial.read();
if (c == 'F') {
Serial.println("F!");
}
if (c == 'B') {
Serial.println("B!");
}
if (c == 'L') {
Serial.println("L!");
}
if (c == 'R') {
Serial.println("R!");
}
if (c == 'S') {
Serial.println("S!");
}
}