9 years, 1 month ago.

How to avoid reseting RTC when mbed starts up?

Ii seems mebed resets RTC every time starts, no matter it is triggered by watchdog or but reset button. In both cases, external power has been constantly on.

Is there a way to keep the RTC settings when application restarts when triggered by watchdog?

Thanks.

Update 1: it is a customized board built around LPC1768.

Update 2: Mbed/LPC1768 itself does retain RTC settings after reset when external power is on. The problem turns out be in difftime(). Somehow in the following code, no matter whether RTC is previously set or not, code to get time from NTP server is always triggered, based on which I thought RTC settings were cleared after reset.

difftime() error

    struct  tm Clock;
    Clock.tm_year = 2015;
    Clock.tm_mon  = 10;
    Clock.tm_mday = 1;
    Clock.tm_hour = 15;
    Clock.tm_min  = 30;
    Clock.tm_sec  = 30;
    time_t build_time = mktime(&Clock);
    timeUTC = time(NULL);
    if(difftime(timeUTC, build_time)) {
      // Get time from NTP server
    }

if I simply compare time by value like in the following code:

working code

    timeUTC = time(NULL);
    if(timeUTC < 1443713430) {
      // Get time from NTP server
    }

Code to get time from NTP server is only called when RTC is not set.

many RTC 'power domains' or chips have a 64 byte memory/register that is also RTC battery backed up; you could possibly use a flag of some sort you give no indication of board/chipset........., this is an issue and there have been other questions/answers try google search - 'mbed rtc......' Gary

posted by Gary Z 16 Oct 2015

1 Answer

9 years, 1 month ago.

Replace your rtc_api.c with this code and it will work. just copy/paste it in. If there is a vBat connection on your board and you power it with a 3v cell, it will keep time when main power is cycled.

Its located in the HAL - TARGET_STM32F4 folder.

All the STM's reset the RTC and this code does work for most of them.

It checks the RTC->ISR register to see if the RTC has been initialised.

Tested on the F401 board but should work on all this series.

rtc_api.c


/* mbed Microcontroller Library
 *******************************************************************************
 * Copyright (c) 2014, STMicroelectronics
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of STMicroelectronics nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************
 */
#include "rtc_api.h"

#if DEVICE_RTC

#include "mbed_error.h"

static RTC_HandleTypeDef RtcHandle;

void rtc_init(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct;
    uint32_t rtc_freq = 0;

    if(RTC->ISR == 7) {     // RTC initialization and status register (RTC_ISR), cold start (with no backup domain power) RTC reset value

        RtcHandle.Instance = RTC;

        // Enable Power clock
        __PWR_CLK_ENABLE();

        // Enable access to Backup domain
        HAL_PWR_EnableBkUpAccess();

        // Reset Backup domain
        __HAL_RCC_BACKUPRESET_FORCE();
        __HAL_RCC_BACKUPRESET_RELEASE();

        // Enable LSE Oscillator
        RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
        RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE; /* Mandatory, otherwise the PLL is reconfigured! */
        RCC_OscInitStruct.LSEState       = RCC_LSE_ON; /* External 32.768 kHz clock on OSC_IN/OSC_OUT */
        if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) {
            // Connect LSE to RTC
            __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSE);
            __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE);
            rtc_freq = LSE_VALUE;
        } else {
            // Enable LSI clock
            RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE;
            RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured!
            RCC_OscInitStruct.LSEState       = RCC_LSE_OFF;
            RCC_OscInitStruct.LSIState       = RCC_LSI_ON;
            if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
                error("RTC error: LSI clock initialization failed.");
            }
            // Connect LSI to RTC
            __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSI);
            __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI);
            // [TODO] This value is LSI typical value. To be measured precisely using a timer input capture
            rtc_freq = LSI_VALUE;
        }

        // Enable RTC
        __HAL_RCC_RTC_ENABLE();

        RtcHandle.Init.HourFormat     = RTC_HOURFORMAT_24;
        RtcHandle.Init.AsynchPrediv   = 127;
        RtcHandle.Init.SynchPrediv    = (rtc_freq / 128) - 1;
        RtcHandle.Init.OutPut         = RTC_OUTPUT_DISABLE;
        RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
        RtcHandle.Init.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN;

        if (HAL_RTC_Init(&RtcHandle) != HAL_OK) {
            error("RTC error: RTC initialization failed.");
        }
    }
}

void rtc_free(void)
{
    // Enable Power clock
    __PWR_CLK_ENABLE();

    // Enable access to Backup domain
    HAL_PWR_EnableBkUpAccess();

    // Reset Backup domain
    __HAL_RCC_BACKUPRESET_FORCE();
    __HAL_RCC_BACKUPRESET_RELEASE();

    // Disable access to Backup domain
    HAL_PWR_DisableBkUpAccess();

    // Disable LSI and LSE clocks
    RCC_OscInitTypeDef RCC_OscInitStruct;
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE;
    RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE;
    RCC_OscInitStruct.LSIState       = RCC_LSI_OFF;
    RCC_OscInitStruct.LSEState       = RCC_LSE_OFF;
    HAL_RCC_OscConfig(&RCC_OscInitStruct);
}

int rtc_isenabled(void)
{
    if(RTC->ISR != 7) {
        return 1;
    } else {
        return 0;
    }
}

/*
 RTC Registers
   RTC_WeekDay 1=monday, 2=tuesday, ..., 7=sunday
   RTC_Month   1=january, 2=february, ..., 12=december
   RTC_Date    day of the month 1-31
   RTC_Year    year 0-99
 struct tm
   tm_sec      seconds after the minute 0-61
   tm_min      minutes after the hour 0-59
   tm_hour     hours since midnight 0-23
   tm_mday     day of the month 1-31
   tm_mon      months since January 0-11
   tm_year     years since 1900
   tm_wday     days since Sunday 0-6
   tm_yday     days since January 1 0-365
   tm_isdst    Daylight Saving Time flag
*/
time_t rtc_read(void)
{
    RTC_DateTypeDef dateStruct;
    RTC_TimeTypeDef timeStruct;
    struct tm timeinfo;

    RtcHandle.Instance = RTC;

    // Read actual date and time
    // Warning: the time must be read first!
    HAL_RTC_GetTime(&RtcHandle, &timeStruct, FORMAT_BIN);
    HAL_RTC_GetDate(&RtcHandle, &dateStruct, FORMAT_BIN);

    // Setup a tm structure based on the RTC
    timeinfo.tm_wday = dateStruct.WeekDay;
    timeinfo.tm_mon  = dateStruct.Month - 1;
    timeinfo.tm_mday = dateStruct.Date;
    timeinfo.tm_year = dateStruct.Year + 100;
    timeinfo.tm_hour = timeStruct.Hours;
    timeinfo.tm_min  = timeStruct.Minutes;
    timeinfo.tm_sec  = timeStruct.Seconds;

    // Convert to timestamp
    time_t t = mktime(&timeinfo);

    return t;
}

void rtc_write(time_t t)
{
    RTC_DateTypeDef dateStruct;
    RTC_TimeTypeDef timeStruct;

    RtcHandle.Instance = RTC;

    // Enable write access to Backup domain
    HAL_PWR_EnableBkUpAccess();

    // Convert the time into a tm
    struct tm *timeinfo = localtime(&t);

    // Fill RTC structures
    dateStruct.WeekDay        = timeinfo->tm_wday;
    dateStruct.Month          = timeinfo->tm_mon + 1;
    dateStruct.Date           = timeinfo->tm_mday;
    dateStruct.Year           = timeinfo->tm_year - 100;
    timeStruct.Hours          = timeinfo->tm_hour;
    timeStruct.Minutes        = timeinfo->tm_min;
    timeStruct.Seconds        = timeinfo->tm_sec;
    timeStruct.TimeFormat     = RTC_HOURFORMAT12_PM;
    timeStruct.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
    timeStruct.StoreOperation = RTC_STOREOPERATION_RESET;

    // Change the RTC current date/time
    HAL_RTC_SetDate(&RtcHandle, &dateStruct, FORMAT_BIN);
    HAL_RTC_SetTime(&RtcHandle, &timeStruct, FORMAT_BIN);
}

#endif

Accepted Answer

Thanks very much Paul. I almost started adding an external RTC chp. My board is built around LPC1768, but I believe it will be fairly easy to adapt the code.

posted by Zhiyong Li 16 Oct 2015

The LPC1768 MBed does keep RTC time on reset. It is only the STM's that have this issue. If your LPC1768 RTC is not keeping time then check the VBATTERY voltage on the MCU itself, there have been some problems with the diodes (D3 and D4) and connections on some boards.

posted by Paul Staron 16 Oct 2015

Mine is a customized board with VBat connected to VCC. I was under the impression that mbed/LPC1768 keeps RTC when reset, but at least on my customized board all RTC settings are cleared on each power up. I will test it on original mbed and see what could go wrong.

posted by Zhiyong Li 16 Oct 2015