Good day, I currently have a problem where I want to use my RTC (DS1302) to give me the time, whilst also pinging and receiving data from another slave device. Both i2c communication works separately but not together, when I combine the code nothing works at all. Help would be greatly appreciated! Note: I am using an ESP32 device. Here is my code:
#include <RtcDS1302.h>
#include <Wire.h>
#define DS1302_SCLK_PIN 22
#define DS1302_IO_PIN 21
#define DS1302_CE_PIN 2
ThreeWire myWire(DS1302_IO_PIN, DS1302_SCLK_PIN, DS1302_CE_PIN);
RtcDS1302<ThreeWire> Rtc(myWire);
#define I2C_SLAVE_ADDR 0x08 // 7-bit I2C address of the PIC16F1829
void setup()
{
Serial.begin(9600);
Serial.print("compiled: ");
Serial.print(__DATE__);
Serial.println(__TIME__);
Rtc.Begin();
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
printDateTime(compiled);
Serial.println();
Wire.begin();
if (!Rtc.GetIsRunning())
{
Serial.println("RTC was not actively running, starting now");
Rtc.SetIsRunning(true);
}
}
void loop()
{
RtcDateTime now = Rtc.GetDateTime();
Wire.requestFrom(I2C_SLAVE_ADDR, 1); // Requests data from slave
byte data = Wire.read(); // NACK sent by slave once read
if (data != 0 && data != 255) // Use && instead of || to check for equality
{
if (data == 5)
{
Serial.println("Correct Token Received: 01x02x03x05");
printDateTime(now);
if (!now.IsValid())
{
// Common Causes:
// 1) the battery on the device is low or even missing and the power line was disconnected
Serial.println("RTC lost confidence in the DateTime!");
}
}
if (data == 6)
{
Serial.println("Correct Token Received: 01x02x03x06");
printDateTime(now);
if (!now.IsValid())
{
// Common Causes:
// 1) the battery on the device is low or even missing and the power line was disconnected
Serial.println("RTC lost confidence in the DateTime!");
}
}
}
delay(500); // two seconds
}
void printDateTime(const RtcDateTime& dt)
{
char datestring[26];
snprintf_P(datestring,
countof(datestring),
PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
dt.Month(),
dt.Day(),
dt.Year(),
dt.Hour(),
dt.Minute(),
dt.Second());
Serial.println(datestring);
}