This is a pure programming question (which also could have been asked on https://arduino.stackexchange.com/).
There are 3 reference threads with similiar problems (and the same solution):
- Help: calling wifi class from a 2nd cpp file - #2 by maxgerhardt
- Project won't compile - #2 by maxgerhardt
- Getting Error 1 when building [Solved] - #2 by maxgerhardt
Short version:
In this case you don’t want to duplicate the creation of the clock
object. You want to have it created once and have the other files reference the object.
You can create a third file clock.cpp
and clock.h
which create and declare the clock.
You can also choose to just create it in one file, e.g. in setTime.cpp
:
#include <Arduino.h>
#include <DS3231.h>
//Instantiate object here
DS3231 clock(SDA, SCL);
void setTime(uint8_t hour, uint8_t min, uint8_t sec, uint8_t date, uint8_t mon, uint16_t year)
{
clock.begin();
clock.setTime(hour, min, sec);
clock.setDate(date, mon, year);
}
setTime.h
#ifndef SETTIME_H
#define SETTIME_H
#include <Arduino.h>
#include <DS3231.h>
//Declare that somewhere a DS3231 clock object is created by some file.
extern DS3231 clock;
//Available function prototypes
void setTime(uint8_t hour, uint8_t min, uint8_t sec, uint8_t date, uint8_t mon, uint16_t year);
#endif /* SETTIME_H */
getTime.cpp
#include <Arduino.h>
#include "setTime.h" //includes declarations for clock object
String getTime()
{
clock.begin();
String result = String(clock.getDateStr()) + " ";
result += String(clock.getTimeStr());
return result;
}
getTime.h
#ifndef GETTIME_H
#define GETTIME_H
#include <Arduino.h>
String getTime();
#endif /* GETTIME_H */
In general when you only have two functions which are both related to the time, why not just have it in one file, together with the .h
header declaring all available functions