Tuesday, May 12, 2015

Servo with Relay State Improvement


In this improvement, we used relay and servo motor. A relay is basically an electrically controlled mechanical switch. Inside that harmless looking plastic box is an electromagnet that, when it gets a jolt of energy, causes a switch to trip.We are changing the position of servo with looking the state of relay. 
Berrak Şişman& İlker Çam

#include "Servo.h"

const int relayPin = 2;     // use this pin to drive the transistor
const int timeDelay = 1000; // delay in ms for on and off phases
const int onPin = 7;
const int offPin = 8;
const int servoPin = 6;
int onOff = 1;
Servo servo1;

void setup()
{
  pinMode(relayPin, OUTPUT);  // set pin as an output
  pinMode(onPin,INPUT);
  pinMode(offPin,INPUT);
  servo1.attach(servoPin);
  Serial.begin(9600);
}


void loop()                
{

  digitalWrite(relayPin,HIGH);
  delay(500);
  readRelayState();
  digitalWrite(relayPin,LOW);
  delay(500);
  readRelayState();

}

void readRelayState(){
  int onState, offState;
  onState = digitalRead(onPin);
  offState = digitalRead(offPin);
  Serial.println(onState);
  Serial.println(offState);
  if(onState == HIGH && offState == LOW || onOff==1?true:false){
    onOff=0;
    for(int position = 0; position < 180; position += 2)
  {
    servo1.write(position);  // Move to next position
    delay(2);               // Short pause to allow it to move
  }
    Serial.println("Servo is at 180 degrees");
  }else if(onState == LOW && offState == HIGH || onOff==0?true:false){
    onOff=1;
      for(int position = 180; position >= 0; position -= 1)
  {                            
    servo1.write(position);  // Move to next position
    delay(2);               // Short pause to allow it to move
  }
    Serial.println("Servo is at 0 degrees");
  }
  delay(100);


}

No comments:

Post a Comment