Search code examples
arduinoreal-time-clockservo

Arduino with servo and RTC


I am making a project that involves a RTC and a servo motor so that it only turns on at a certain time. A snippet from the loop is:

void loop() {
    DateTime now = rtc.now();
    if (DateTime == 19:10) {
        //Some stuff
    } else {
        return();
    }
}

and my error is:

Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\User\Documents\Arduino\Servo_motor\Servo_motor.ino: In function 'void loop()':

Servo_motor:36: error: expected primary-expression before '==' token

  if (DateTime == 19:10) {

               ^

Servo_motor:36: error: expected ')' before ':' token

  if (DateTime == 19:10) {

                    ^

Servo_motor:45: error: expected primary-expression before '}' token

  }

  ^

Servo_motor:45: error: return-statement with a value, in function returning 'void' [-fpermissive]

Servo_motor:45: error: expected ';' before '}' token

Multiple libraries were found for "RTClib.h"
 Used: C:\Program Files (x86)\Arduino\libraries\RTClib
 Not used: C:\Users\User\Documents\Arduino\libraries\arduino_786051
exit status 1
expected primary-expression before '==' token

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I am really confused. Can someone please help?


Solution

  • I'm going to assume you're using the Adafruit RTClib located here, as this is likely the one accessible from the IDE, or that a tutorial will use. It's also a fork of the other available RTClib, so this answer is likely to pertain to both.

    If you check RTClib.h, you will find the publicly available methods for DateTime and all the RTC classes. If you do so, you'll notice that there is no operator== method, and in general this means that you can't use that as a form of comparison.

    In order to do what you want, you need to use DateTime.minute() and DateTime.hour() and compare them separately. In your loop block it would look as follows:

    void loop() {
        DateTime now = rtc.now();
        if (now.hour() == 19 && now.minute() == 10) {
            //Some stuff
        } else {
            return;
        }
    }
    

    However, this has the possibility of running the code in question quite a few times, as this check will succeed every time the loop runs during the minute following the RTC ticking over to 19:10.