ask DS3231 Module for time and display to console. optionally set the time too.

Dependencies:   ds3231 max32630fthr USBDevice

main.cpp

Committer:
davidanasco
Date:
2021-07-23
Revision:
0:4527149f9f39

File content as of revision 0:4527149f9f39:

#include "mbed.h"
#include "max32630fthr.h"
#include "USBSerial.h"
#include "ds3231.h"
#define ESC 0x1B

MAX32630FTHR pegasus(MAX32630FTHR::VIO_3V3);

// Hardware serial port over DAPLink
Serial daplink(USBTX, USBRX);

// declare pins
DigitalOut bLED(LED3);
DigitalIn push(P2_3, PullUp);


int main(){
    Ds3231 rtc(I2C1_SDA, I2C1_SCL);
    // rtc.frequency(0);

    char buffer[32];
    daplink.printf("%c[2J", ESC); //clear screen
    daplink.printf("%c[H", ESC); //move cursor to Home
    daplink.printf("< RTC DEMO >\r\n\n");
    
    for(int ii=0;ii<3;ii++){    // blink blue 3 times
        bLED = LED_OFF;
        wait(0.5);
        bLED = LED_ON;
        wait(0.5);
        bLED = LED_OFF;
    }

    time_t epoch_time;  // declare variable for absolute time (in seconds) from Jan 1, 1970 12mn
    ds3231_time_t timeKeep; // declare time variable
    ds3231_calendar_t dateKeep; // declare calendar variable

    // set to false when just reading time. set to true when setting time too.
    bool setTime = false;
    if(setTime){
        // setting the time
        timeKeep.seconds = 0;   // 1-59
        timeKeep.minutes = 0;   // 1-59
        timeKeep.hours = 10;    // 1-12
        timeKeep.am_pm = 0;     // 0 am, 1 pm
        timeKeep.mode = 0;      // 0 military, 1 normal

        // setting the calendar
        dateKeep.day = 5;       // 1 sunday - 7 saturday
        dateKeep.date = 30;     // 1-31
        dateKeep.month = 7;     // 1-12
        dateKeep.year = 20;     // last 2 digit
        
        daplink.printf("Written Date: %u/%u/%u\r\n",dateKeep.year,dateKeep.month,dateKeep.date);
        daplink.printf("Written Time: %u:%u:%u\r\n",timeKeep.hours,timeKeep.minutes,timeKeep.seconds);

        if(rtc.set_time(timeKeep)){
            daplink.printf("Setting time failed\r\n");
        }
        if(rtc.set_calendar(dateKeep)){
            daplink.printf("Setting calendar failed\r\n");
        }
    }

    rtc.get_calendar(&dateKeep);
    daplink.printf("Initial Date: %u/%u/%u\r\n",dateKeep.year,dateKeep.month,dateKeep.date);
    rtc.get_time(&timeKeep);
    daplink.printf("Initial Time: %u:%u:%u\r\n\n",timeKeep.hours,timeKeep.minutes,timeKeep.seconds);

    while(1){
        if(!push){
            bLED = LED_ON;
            epoch_time = rtc.get_epoch();   // when button is pushed, display current date and time

            strftime(buffer, 32, "%a %b%e %G %X", localtime(&epoch_time));
            daplink.printf("%s\r\n", buffer);
            wait(1);    // wait for a second before accepting input again. without this, it would display the time multiple times.
            bLED = LED_OFF;
        }
    }
}