How to generate a timestamp in stm32f303?

ballack picture ballack · Jan 25, 2018 · Viewed 10.9k times · Source

I am writing code to generate a timestamp to use it as a reference for to perform a certain function. can anyone help me how to do it. i am new to embedded programming.

Answer

Bulkin picture Bulkin · Jan 26, 2018

First of all, you must init RTC. Hope you know, how to do this STM32CubeMX.

Then it is simple code:

#include <time.h>

/* Global Vars */
RTC_TimeTypeDef currentTime;
RTC_DateTypeDef currentDate;
time_t timestamp;
struct tm currTime;


/* Code to get timestamp 
*
*  You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values 
*  in the higher-order calendar shadow registers to ensure consistency between the time and date values.
*  Reading RTC current time locks the values in calendar shadow registers until Current date is read
*  to ensure consistency between the time and date values.
*/

HAL_RTC_GetTime(&hrtc, &currentTime, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, &currentDate, RTC_FORMAT_BIN);

currTime.tm_year = currentDate.Year + 100;  // In fact: 2000 + 18 - 1900
currTime.tm_mday = currentDate.Date;
currTime.tm_mon  = currentDate.Month - 1;

currTime.tm_hour = currentTime.Hours;
currTime.tm_min  = currentTime.Minutes;
currTime.tm_sec  = currentTime.Seconds;

timestamp = mktime(&currTime);

P.S. I do not check if Date and Time data are correct. If you wanna to - make some checks for correct data yourself.