0

I am making a fish feeder using an Arduino Mega 2560, servo motor SG90 and RTC DS3231. I want to make it rotate twice a day, i.e. morning and 9 o'clock evening.

Whenever I plug my Arduino board to my laptop for first time it rotates correctly during specified time 9 o'clock and I change the time to 9 o'clock 10 mins to check again and it rotates after I plug it to my laptop for 180 degrees and then rotates during the specified time.

What should I do to avoid that initial rotation?

Here is my code:

#include<Wire.h>
#include<LiquidCrystal.h>
#include "RTClib.h"
#include <Servo.h>

Servo myservo;

int pos = 0;


RTC_DS3231 rtc;
DateTime now;

const int OnHour = 9;
const int OnMin = 15;

void setup() {
  Serial.begin(9600);
  rtc.begin();
  myservo.attach(9);
  rtc.adjust(__DATE__,__TIME__));
}

void loop() {

  now= rtc.now();
  Serial.print(now.hour);
  Serial.print(" hour(s), ");
  Serial.print(now.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (1000);
  if (now.hour == OnHour  &&   now.min == OnMin) 
  {
  Serial.println("feeder ON");
  myservo.write(90); 
  delay(1000);
  myservo.write(180); 
  } 
  else
  {
     Serial.println("feeder OFF");
     delay(10); 
  }
  }
  • Hint: What is the initial setting of the Servo? – Mikael Patel Jan 2 at 8:25
  • @user52610 ... did you try my solution? – Michel Keijzers 2 days ago
0

I'm not fully understanding the problem, but I assume you want it on for 9:00 / 9AM and 21:00 / 9 PM on for 15 minutes.

const int onTime1 =  9 * 60 +  0; // 9:00 AM
const int onTime2 = 21 * 60 + 30; // 9:30 PM
const int onMinutes   = 15; // Minutes

void loop()
{
  now = rtc.now();
  int nowTime = now.hour * 60 + now.min; // Minutes from current day

  if (((onTime1 <= nowTime) && (nowTime < onTime1 + onMinutes)) ||
      ((onTime2 <= nowTime) && (nowTime < onTime2 + onMinutes)))
  {
     myservo.write(90); // On
  }
  else
  {
     myservo.write(180); // Off
  }
  delay(1000); // 1 s delay
}

You can make the above if statement easier by:

  mysesrvo.write(180 - 90 * (int) (
   ((onTime1 <= nowTime) && (nowTime < onTime1 + onMinutes)) ||
   ((onTime2 <= nowTime) && (nowTime < onTime2 + onMinutes))));

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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