Go Down

Topic: Serial Servo Control (Read 374 times) previous topic - next topic

Chaffy

Thanks for your quick replies! Please see code below which has been ripped from another thread on this forum.

Code: [Select]
#include <Servo.h>

int moveServo;

Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4; // name servos


void setup()
{
 
  servo1.attach(2);
  servo2.attach(3);
  servo3.attach(4);
  servo4.attach(5);
  Serial.begin(9600);
  Serial.println("      Cam L  7  Forward   8  Cam R  9");
  Serial.println("      Left   4  Straight  5  Right  6");
  Serial.println("      CamDn  1  Reverse   2  CamUp  3");
  Serial.println("      Stop   0");
  Serial.println(); // on screen notes
 
}

void loop () {
 
  if (Serial.available() > 0) {
    moveServo = Serial.read();
   
    if (moveServo == '0') { servo1.write(90); }  // stop
    else if (moveServo == '1') { servo4.write(1); } // cam down
    else if (moveServo == '2') { servo1.write(1); } // reverse
    else if (moveServo == '3') { servo4.write(180); } // cam up
    else if (moveServo == '4') { servo2.write(1); } // left
    else if (moveServo == '5') { servo2.write(90); } // straight
    else if (moveServo == '6') { servo2.write(180); } // right
    else if (moveServo == '7') { servo3.write(1); } // cam left
    else if (moveServo == '8') { servo1.write(180); } // forward
    else if (moveServo == '9') { servo3.write(180); } // cam right
  }
}


As you can see its v.basic, I have never coded anything before.  I was hoping it would be as simple as an "else if" line with a 'no serial' comand then a 'servo write' comand!

Thanks

AWOL

Quote
I was hoping it would be as simple as an "else if" line with a 'no serial' comand then a 'servo write' comand!
No, I'm afraid it isn't that simple.
Serial is really slow, so the "no serial" condition is pretty much most of the time, as someone already pointed out.
What you should do is note the time ("millis ()" ) each time you receive a character, then every time through the main loop, check to see if 'x' seconds have elapsed.
As usual, the blink without delay tutorial will give you some clues.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up