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.

  • Nice use of a switch statement :D – Code Gorilla Aug 18 '16 at 16:30
  • I found out that my servo 360 Parallax has continuous rotation – Radu Mihai Aug 18 '16 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 Aug 20 '16 at 3:17
  • @user6317433 are you still in need of an answer? – Paul Jan 16 '17 at 18:41
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;
| improve this answer | |
  • Doesn't the servo.write need to be outside of the if statement? – Gerben Aug 18 '16 at 18:05
  • 'MovementAmount' it should be the position ,number? – Radu Mihai Aug 18 '16 at 19:58
  • @Matt does it matter what kind of servo i have ? – Radu Mihai Aug 18 '16 at 20:01
  • @Gerben - Doh :) That would help wouldn't it, I'll edit it. – Code Gorilla Aug 19 '16 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. – Code Gorilla Aug 19 '16 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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