Want to understand code of RTC DS3231

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}
  
  // Initialize the rtc object
  rtc.begin();
  
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");
  
  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());
  
  // Wait one second before repeating :)
  delay (1000);
}

Taken from http://www.RinkyDinkElectronics.com/
I want to know what is the use of line
DS3232 rtc(SDA,SCL);

I know as much that an object of type DS3231 is being defined named rtc but what is the meaning of arguments SDA and SCL in rtc.
I know they are serial data and serial clock used in I2C communication but why are we writing it here?

The code has to be instructed what pins to use.

Object instantiation (create the object in memory) requires that we provide the I2C signal pins.

There are other ways this can be done, but generally speaking we do NOT want global variables to infiltrate our private object classes. It can also be done with importing name spaces, but we really, really try and not do that with Arduino.

Many Arduino libraries are written to NOT need default I2C pins UNLESS the intent is to override, this creates a library with "overloaded operators" which is an aspect of OOP and a very powerful way of dealing with all the various pinouts of the Arduino chipsets.

Ok, we got faster answers than mine... :grinning:

You should take a look on DS3231.h library for reference.

The library that I used in my project "RTClib.h" just uses the commmand "RTC_DS3231 object" with no parameters. It of course presumes that you´re using the standard I2C pins of your board.

There is not only one of those.

1 Like