// This code is written by Paul MacDougal for the December 11, 2017 meeting of TriEmbed.org // It is released to the public domain // It does what it does. // DS3231 breakout board is: // Vcc (3.3v) // SDA (A4) // SCL (A5) // NC // GND // pin 3 of SOIC16 package (int/sqw) is hooked to INTR_PIN // Buzzer is connected as: // BUZZER_PIN -> buzzer -> GND #include #include #include #include "RTClib.h" uint8_t read_i2c_register(uint8_t addr, uint8_t reg); void write_i2c_register(uint8_t addr, uint8_t reg, uint8_t val); RTC_DS3231 rtc; #define INTR_PIN 2 #define BUZZER_PIN 5 volatile byte count = 0; void handleISR() { // ISR count++; } void printTime() { DateTime now = rtc.now(); if (now.month() < 10) { Serial.print("0"); } Serial.print(now.month()); Serial.print('/'); if (now.day() < 10) { Serial.print("0"); } Serial.print(now.day()); Serial.print('/'); Serial.print(now.year()); Serial.print(" "); if (now.hour() < 10) { Serial.print("0"); } Serial.print(now.hour(), DEC); Serial.print(':'); if (now.minute() < 10) { Serial.print("0"); } Serial.print(now.minute(), DEC); Serial.print(':'); if (now.second() < 10) { Serial.print("0"); } Serial.print(now.second(), DEC); Serial.println(); } void setup() { pinMode(INTR_PIN, INPUT_PULLUP); pinMode(BUZZER_PIN, OUTPUT); Serial.begin(19200); // Serial port to PC while (!Serial); // for Leonardo Serial.println(F("Initialized ds3231 example4 v1.0")); // initialize the RTC rtc.begin(); printTime(); // Set A2M2, A2M3, A2M4 so that we get an alarm2 every minute write_i2c_register(DS3231_ADDRESS, 0x0B, 0x80 | read_i2c_register(DS3231_ADDRESS, 0x0B)); write_i2c_register(DS3231_ADDRESS, 0x0C, 0x80 | read_i2c_register(DS3231_ADDRESS, 0x0C)); write_i2c_register(DS3231_ADDRESS, 0x0D, 0x80 | read_i2c_register(DS3231_ADDRESS, 0x0D)); // set INTCN and A2IE uint8_t val = read_i2c_register(DS3231_ADDRESS, DS3231_CONTROL); val |= 0x06; // set INTCN and A2IE write_i2c_register(DS3231_ADDRESS, DS3231_CONTROL, val); // Attach the ISR attachInterrupt(INT0, handleISR, FALLING); delay(500); // allow serial data to go out } void loop() { // read status register uint8_t val = read_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG); // OSF 0 0 0 EN32kHz BSY A2F A1F // clear alarm flags write_i2c_register(DS3231_ADDRESS, DS3231_STATUSREG, (~0x03) & val); if (val&2) // alarm2 has fired { printTime(); // read temperature register int8_t valMSB = read_i2c_register(DS3231_ADDRESS, 0x11); uint8_t valLSB = read_i2c_register(DS3231_ADDRESS, 0x12); double temp = valMSB; temp += (double)(valLSB>>6)/ 4.0; // convert to F temp = 9.0*temp / 5.0 + 32.0; Serial.print("Temperature is "); Serial.println(temp); delay(100); // to allow serial bytes to go out to PC } digitalWrite(BUZZER_PIN, LOW); set_sleep_mode(SLEEP_MODE_PWR_DOWN); // SLEEP_MODE_PWR_DOWN is lowest power state sleep_mode(); // go to sleep // wake up here on interrupt // sound the buzzer while awake digitalWrite(BUZZER_PIN, HIGH); }