int dirA = 12;
int dirB = 13;  // not used in this example
int speedA = 3;
int speedB = 11; // not used in this example
int sonarPin = A2;
int sonarValue = 0;

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void setup()
{
  pinMode (dirA, OUTPUT);
  pinMode (dirB, OUTPUT);
  pinMode (speedA, OUTPUT);
  pinMode (speedB, OUTPUT);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
  Serial.begin(115200);
  delay(2000);
  Serial.print("$$$");
  delay(1000);
  Serial.println("S~,0");
  delay(1000);
  Serial.println("R,1");
  delay(5000);
}

void loop()
{
  // print the string when a newline arrives:
  if (stringComplete) {
    if (inputString=="STOP") {
        analogWrite (speedA, 0);
        analogWrite (speedB, 0);
    } else if(inputString=="FORWARDS") {
        digitalWrite(dirA, HIGH);
        digitalWrite(dirB, HIGH);
        analogWrite (speedA, 200);
        analogWrite (speedB, 200);
    } else if(inputString=="BACKWARDS") {
        digitalWrite(dirA, LOW);
        digitalWrite(dirB, LOW);
        analogWrite (speedA, 200);
        analogWrite (speedB, 200);
    } else if(inputString=="TURNLEFT") {
        digitalWrite(dirA, HIGH);
        digitalWrite(dirB, LOW);
        analogWrite (speedA, 200);
        analogWrite (speedB, 200);
    } else if(inputString=="TURNRIGHT") {
        digitalWrite(dirA, LOW);
        digitalWrite(dirB, HIGH);
        analogWrite (speedA, 200);
        analogWrite (speedB, 200);
    }

    //Serial.println(inputString); 
    // clear the string:
    inputString = "";
    stringComplete = false;
  }

  //Serial.println(sonarValue);

}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    } 
  }
}

 

Leave a Reply