0

This code keeps on returning 'S' with the Serial.read().

#include <Servo.h>
#define trig 10
#define echo 9
int pinMotorRN=3;
int pinMotorRP=4;
int pinMotorLN=5;
int pinMotorLP=6;
long distance;
long duration;
Servo myservo;
void setup() {
  pinMode(pinMotorRP, OUTPUT);
  pinMode(pinMotorRN, OUTPUT);
  pinMode(pinMotorLP, OUTPUT);
  pinMode(pinMotorLN, OUTPUT); 
  Serial.begin(9600); 
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  myservo.attach(8);
}
void loop() {
  Lid(); 
  while(Serial.available() == 0);
  char val = Serial.read() ;//reads the signal
  delay(1);
  Serial.println(val);
  if(val == 'F'){
    Forward();
  }
  else if(val == 'B'){
    Backward();
  }
  else if(val == 'R'){
    Left();  
  }
  else if(val == 'L'){
     Right();
  }
  else
    Stop();
}
void Stop()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, HIGH);
}
void Backward()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Right()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Left()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Forward()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Lid(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration*0.034/2;
  distance = 11;
  if(distance <= 10){
    myservo.write(180);
    delay(2000);
  }
  else
    myservo.write(0);
}
  • Note that the app im using is Arduino RC bluetooth car controller – user8993691 Jan 9 at 22:08
  • Does it print 'S' over and over or keep executing the stop sequence? Because your terminal is probably sending "<some_letter><CR><LF>", so you'd see stop (the default) get executed 1 or 2 times per keystroke (depending on whether the terminal ends a line with <CR>, <LF>, or both), plus one more if you actually typed an 'S'. In any case, this code shouldn't be delivering a long stream of anything when you aren't typing. – JRobert Jan 9 at 22:36
  • If you are trying to read a character on the serial port shouldn’t “while(Serial.available() == 0);” be “while(Serial.available() > 0); – MrFixIt87 Jan 10 at 0:10
  • 2
    @MrFixIt87: The semicolon following the while-expression is an empty statement. So the whole loop translates to: "While there are zero characters in the serial buffer, do nothing". – JRobert Jan 10 at 0:23

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.