Go Down

Topic: Servo Motor (1 cycle) (Read 3765 times) previous topic - next topic

vasuleodvn

Hi guys, i would like to design a code whereby the servo motor [rotates 90 deg forward and rotate back in reverse 90 degree(initial position) ] when the Arduino magnetic contact switch door is closed. i only want this cycle to happen one time until the switch is open and close again next time. for now im facing a issue where by servo rotates forward and reverse nonstop when the switch is in contact.

#include <Servo.h>
Servo myservo;

int LED1 = 8;
int LED = 9;
const int sensor = 12;

int myservo_position = 0;
int doorState;

void setup()
{

  myservo.attach(13);
  Serial.begin(9600);
  pinMode(sensor, INPUT_PULLUP);

  pinMode(LED, OUTPUT);
  pinMode(LED1, OUTPUT);
  myservo.write(myservo_position);
  return ;
}

void loop()
{
  doorState = digitalRead(sensor);
 
  if (doorState == LOW)
  {

      digitalWrite(LED1, LOW);
      digitalWrite(LED, HIGH);
      delay (1000);
      myservo.write(90);
      delay (1000);
      myservo.write(myservo_position);
      digitalWrite(LED, LOW);
      delay (500);

  }
  else
  {
      digitalWrite(LED1, HIGH);
      digitalWrite(LED, LOW);
      myservo.write(myservo_position);     
  }
}


Go Up