Go Down

Topic: Controlling a servo - Can anybody help me? (Read 3204 times) previous topic - next topic

DamaRoja

I tried this code in order to control a servo. The idea, is that i push a slideswitch, the servo go to 180 and two leds go HIGH, and when i push again, the servo go to 0 and the leds go LOW.

Can you help me?

#include <Servo.h>

Servo myservo;
int pos=0;
int LED=12;
int LED2=13;
int BOTON=7;
int val;
int tiempo=1000;
int posicion=1;

void setup()
{
  pinMode(LED, OUTPUT);
  pinMode(BOTON,INPUT);
  myservo.attach(9);
 
}

void loop() {
 
    val=digitalRead(BOTON);
    if (val==HIGH){
      digitalWrite(LED,HIGH);
      digitalWrite(LED2,HIGH);
      if (posicion==1){
       
        for (pos = 0; pos <= 270; pos+= 1) { // goes from 0 degrees to 180 degrees in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(5);                     // waits 15ms for the servo to reach the position
        }
        posicion==2;
      }

      delay(tiempo);
   
    }
    else{
      if (posicion==2){
        digitalWrite(LED,LOW);
        digitalWrite(LED2,LOW);
        for (pos = 180; pos <= 0; pos-= 1) { // goes from 0 degrees to 180 degrees in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(5);                     // waits 15ms for the servo to reach the position
        }
        posicion=1;

      delay(tiempo);
      }
       
    }
       
}

Go Up