Serial DC Motor Control

I need to combine these too code, I tried to but it ended up not working at all. If you would like can you guys guide me on how to combine these code. I'm still a rookie. The codes work perfectly individually.

int ad=8;  
int cd=7;  
int incom;


void setup(){
  Serial.begin(9600); 
}


void loop(){
  if(Serial.available()){ 
    incom=Serial.read();  
  }
  switch(incom){
    case'a': 
    pinMode(ad,OUTPUT);
    pinMode(cd,OUTPUT);
    digitalWrite(ad,HIGH);
    digitalWrite(cd,LOW);
    Serial.println("FORWARD");
    break;
    case's': 
    pinMode(ad,OUTPUT);
    pinMode(cd,OUTPUT);
    digitalWrite(ad,LOW);
    digitalWrite(cd,HIGH);
    Serial.println("REVERSE"); 
    break;
    case'd': 
    pinMode(ad,OUTPUT);
    pinMode(cd,OUTPUT);
    digitalWrite(ad,LOW);
    digitalWrite(cd,LOW);
    Serial.println("BRAKE"); 
    break;
    case'f': 
    pinMode(ad,INPUT);
    pinMode(cd,INPUT);
    Serial.println("FREE-RUN");
    break;
    default:
    Serial.println("Please key in command"); 
    delay(1000);
    break;
  }
}

And here is the second code set

int motorPin = 3;
 
void setup() 
{ 
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
  while (! Serial);
  Serial.println("Speed 0 to 255");
} 
 
 
void loop() 
{ 
  if (Serial.available())
  {
    int speed = Serial.parseInt();
    if (speed >= 0 && speed <= 255)
    {
      analogWrite(motorPin, speed);
    }
  }
}

Please help, i will be really grateful. Thank you 8)

Criss Chicas

Crazycr1ss:
I need to combine these too code, I tried to but it ended up not working at all. If you would like can you guys guide me on how to combine these code. I'm still a rookie. The codes work perfectly individually.

The first sketch is pretty poor - it will keep repeatedly processing the last command until you enter a new one.

The first sketch accepts a single character as a command. The second one accepts a numeric string as a command.

If you want to support both types of command then you have a couple of options. The quick and dirty way is to use Serial.peek() to see what the incoming character is. If it's a letter, call the logic from your first sketch to read and process it. If it's a number, call the logic from your second sketch to read and process it.

A better approach would be to read and buffer the whole command line and then parse it to see what command is being sent. This would enable you to cope with more complex command syntaxes in future such as 'move forward for a distance', or 'move forward for a time'. THere are plenty of examples of receiving commands over the serial port that will show you how to do this sort of buffering and parsing.

Thank you, that helped me a lot. I'm going to rewrite the first sketch, and then combine it so it will be more solid