Gentleman Im having some problems.
I have a cereal dispenser that is attached to a servo MG938. Servo connected to Arduino uno (ground, 5V and pin9) and also a RTC DS3231.
The main ideia is to set a time on the program and when this time is reached the servo sweps from 0 to 100 degrees but just one time and returns to 0 degree (dispenser closed position). And this operation repeats every day on the set time.
My problem is that it keeps or sweeping, or stopping in an open dispenser position and I have no clue what to do. The sketch is:
#include <Wire.h>
#include <DS3231.h>
#include <Servo.h>
Servo myservo;
DS3231 rtc(SDA, SCL);
Time t;
const int OnHour=8; //Servo On Hour
const int OnMin=10; //Servo On Minute
const int OnSec=00; //Servo On Second
const int OffHour=8; //Servo Off Hour
const int OffMin=10; //Servo Off Minute
const int OffSec=2; //Servo Off SEcond
int Hor;
int Min;
int Sec;
int pos = 0; //initial servo position
void setup()
{
Wire.begin();
rtc.begin();
Serial.begin(9600);
rtc.setDOW(MONDAY); //week day
rtc.setTime(8, 9, 0); //time
rtc.setDate(11, 12, 2017); //date
delay(1000);
}
void loop()
{
Time t;
t=rtc.getTime();
Hor=t.hour;
Min=t.min;
Sec=t.sec;
Serial.print(t.hour);
Serial.print(t.min);
Serial.print(t.sec);
delay(1000);
if(t.hour>=OnHour&&t.hour<=OffHour && t.min >= OnMin&&t.min <= OffMin && t.sec >=OnSec&&t.sec <=OffSec) //define horario de ativacao/desativacao do servo
{
myservo.attach(9); //attaches servo to pin 9
for (pos = 0; pos <= 100; pos += 1) // servo goes from 0 to 100 degrees in 1 degree step clockwise
{
myservo.write(pos); // send servo to position
delay(15); // wait 15 ms to the servo to reach position
}
for (pos = 100; pos >= 0; pos -= 1) // servo goes from 100 to 0 degrees in 1 degree step anti clock
{
myservo.write(pos); // send servo to position
delay(15); // wait 15 ms to the servo to reach position
myservo.detach(); // detach servo in order to spare battery
Serial.println("ServoLigado");
}
}
else
myservo.write(0);
Serial.println("ServoDesligado");
}