All tutorials

4 · Displays & buses

Programmable alarm clock (RTC)

Expert30 min

Goal

Trigger the buzzer at a precise time read from the DS3231.

Why it matters

Comparing a real time to a setpoint is the principle of any scheduled automation.

Steps

  1. 01Start again from the weather station sketch.
  2. 02Extract hours and minutes from the DS3231 (BCD → decimal).
  3. 03Compare them to an alarm time.
  4. 04Fire tone() for 5 seconds, then stop.

Starter sketch

// BMP280 temperature + pressure and DS3231 clock, straight over Wire.
#include <Wire.h>

const uint8_t BMP = 0x76;
const uint8_t RTC = 0x68;

uint16_t calT1; int16_t calT2; uint16_t calP1;

uint8_t readReg8(uint8_t addr, uint8_t reg) {
  Wire.beginTransmission(addr);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(addr, (uint8_t)1);
  return Wire.read();
}

uint16_t readLE16(uint8_t reg) {
  Wire.beginTransmission(BMP);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(BMP, (uint8_t)2);
  uint8_t lo = Wire.read();
  uint8_t hi = Wire.read();
  return (uint16_t)((hi << 8) | lo);
}

long read20(uint8_t reg) {
  Wire.beginTransmission(BMP);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(BMP, (uint8_t)3);
  long msb = Wire.read();
  long lsb = Wire.read();
  long xlsb = Wire.read();
  return ((msb << 16) | (lsb << 8) | xlsb) >> 4;
}

uint8_t fromBcd(uint8_t v) { return (v >> 4) * 10 + (v & 0x0F); }

void setup() {
  Serial.begin(9600);
  Wire.begin();
  calT1 = readLE16(0x88);
  calT2 = (int16_t)readLE16(0x8A);
  calP1 = readLE16(0x8E);
  Serial.print("BMP280 id 0x");
  Serial.println(readReg8(BMP, 0xD0), HEX);
}

void loop() {
  long adcT = read20(0xFA);
  long adcP = read20(0xF7);
  float tFine = ((adcT / 16384.0) - (calT1 / 1024.0)) * calT2;
  float tempC = tFine / 5120.0;
  float pa = (1048576.0 - adcP) * 6250.0 / calP1;

  Serial.print("T ");
  Serial.print(tempC);
  Serial.print(" C   P ");
  Serial.print(pa / 100.0);
  Serial.println(" hPa");

  uint8_t h = fromBcd(readReg8(RTC, 0x02));
  uint8_t m = fromBcd(readReg8(RTC, 0x01));
  uint8_t s = fromBcd(readReg8(RTC, 0x00));
  Serial.print("RTC ");
  Serial.print(h); Serial.print(":");
  Serial.print(m); Serial.print(":");
  Serial.println(s);

  delay(1000);
}

This tutorial runs inside the Circuitly simulator: your wiring and your code are checked automatically at every step.

Next tutorials