/* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. Created 9 May 2011 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/SerialEvent Control ------- Hello. M1F255. M2F255. M1F255_M2F255. */ String inputString = ""; // a string to hold incoming data boolean stringComplete = false; // whether the string is complete //Motor 1 int dir1PinA = 2; int dir2PinA = 3; int speedPinA = 9; //Motor 2 int dir1PinB = 4; int dir2PinB = 5; int speedPinB = 10; void setup() { delay(5000); // initialize serial: Serial.begin(115200); // reserve 200 bytes for the inputString: inputString.reserve(20); pinMode(dir1PinA,OUTPUT); pinMode(dir2PinA,OUTPUT); pinMode(speedPinA,OUTPUT); pinMode(dir1PinB,OUTPUT); pinMode(dir2PinB,OUTPUT); pinMode(speedPinB,OUTPUT); } int motorspeed(String pwmspeed){ int mspeed; if (pwmspeed.substring(3,6)=="000"){ mspeed=0; } else{ mspeed=pwmspeed.substring(3,6).toInt(); } Serial.print("PWM:"); Serial.println(mspeed); return mspeed; } void loop() { int m1, m2; boolean dir1, dir2; String pwmcmd; // print the string when a newline arrives: if (stringComplete) { Serial.print(inputString); Serial.println("OK"); if (inputString.substring(0,6)=="Hello.") { Serial.println("Namaste :)\n"); } else { if (inputString.substring(0,2) == "M1") { if (inputString[2]=='F'){ dir1=true; digitalWrite(dir1PinA, LOW); digitalWrite(dir2PinA, HIGH); Serial.println("M1-FORWARD is set"); pwmcmd=inputString.substring(0,7); m1= motorspeed(pwmcmd); } if (inputString[2]=='R'){ dir1=false; digitalWrite(dir1PinA, HIGH); digitalWrite(dir2PinA, LOW); Serial.println("M1-REVERSE is set"); pwmcmd=inputString.substring(0,7); m1= motorspeed(pwmcmd); } } if (inputString.substring(7,9)=="M2"){ if (inputString[9]=='F') { dir2=true; digitalWrite(dir1PinB, LOW); digitalWrite(dir2PinB, HIGH); Serial.println("M2-FORWARD is set"); pwmcmd=inputString.substring(7,13); m2= motorspeed(pwmcmd); } if (inputString[9]=='R') { dir2=false; digitalWrite(dir1PinB, HIGH); digitalWrite(dir2PinB, LOW); Serial.println("M2-REVERSE is set"); pwmcmd=inputString.substring(7,13); m2= motorspeed(pwmcmd); } } analogWrite(speedPinA, m1);//Sets speed variable via PWM analogWrite(speedPinB, m2); } inputString = ""; stringComplete = false; } } /* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; if (inChar=='.'){ stringComplete=true; } } }