0

I work on my first arduino car project and i want to turn my servo to a position with a letter input

This is my code so far

 #include <Servo.h>
Servo servo;

 void setup() {
 Serial.begin(9600);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
 }

 void loop() {

 if(Serial.available()>0){
 int  caz=Serial.read();
 switch(caz)
{
  case 'w':
      digitalWrite(8,LOW);
      digitalWrite(7,HIGH);
      break;
  case 's':
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      break;
  case'd':
       servo.attach(12);
       servo.write(0);
       break;
  case'a':
       servo.attach(11);
       servo.write(180);
       break;
   default:
       digitalWrite(7,LOW);
       digitalWrite(8,LOW);
       servo.attach(0);
  }
}

when i input 'a' or 'd' it starts turning until i input something else and i want it to stop after 10-30 degree .

And also i would like to do that to my motor , moving a bit when i input the key.

4
  • Nice use of a switch statement :D Commented Aug 18, 2016 at 16:30
  • I found out that my servo 360 Parallax has continuous rotation
    – Radu Mihai
    Commented Aug 18, 2016 at 21:13
  • You should get a 180 degree servo. You code looks fine and it should work with a 180 degree servo. Read my comment under the answer by Matt. Using .write command on continuous servos tells them the speed and direction in which to rotate, not the angle.
    – shurup
    Commented Aug 20, 2016 at 3:17
  • @user6317433 are you still in need of an answer?
    – aaa
    Commented Jan 16, 2017 at 18:41

1 Answer 1

1

Rather than writing to 180 and 0 write to a variable.

static const int MovementAmount = 30; //degrees
int position = 90;  // 90 is the start position.
...
case 'd':
   servo.attach(12);
   position += MovementAmount;
   if (position > 180)
   {
     position = 180;
   }
   servo.write(position);
   break;
6
  • Doesn't the servo.write need to be outside of the if statement?
    – Gerben
    Commented Aug 18, 2016 at 18:05
  • 'MovementAmount' it should be the position ,number?
    – Radu Mihai
    Commented Aug 18, 2016 at 19:58
  • @Matt does it matter what kind of servo i have ?
    – Radu Mihai
    Commented Aug 18, 2016 at 20:01
  • @Gerben - Doh :) That would help wouldn't it, I'll edit it. Commented Aug 19, 2016 at 12:18
  • @user6317433 - The movement amount is the amount you want it to move by every time you press the relative key. You will need a block of code like this for case 'a'. I don't think a continuous servo will affect the code, but you will have to remember to use -MovementAmount and +MovementAmount. otherwise it will turn around where you don't want it to go. Commented Aug 19, 2016 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.