ballack
ballack

Reputation: 21

How to generate a timestamp in stm32f303?

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.

Upvotes: 2

Views: 22697

Answers (2)

Bulkin
Bulkin

Reputation: 1040

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.

Upvotes: 6

MemAllox
MemAllox

Reputation: 851

This is a very broad question. With the STM32, you have different ways to implement a timestamp. I assume, you mean the elapsed milliseconds since startup. If you want the actual time on the clock, you need an RTC (real time clock).

Generally, you need to write an function called the interrupt routine (or interrupt handler), which increments a variable every 1 millisecond (or any other suitable time interval). This function will be called every time the interrupt triggers, usually due to a timer overflow.

Now you can either configure the STM32 registers directly (which I do not recommend) or use a library (such as StdPeriph or HAL). Especially the latter is very simple to use.

I.e. with the HAL, a simple call of HAL_GetTick() gives you a timestamp in ms. See this for more information.

Upvotes: 3

Related Questions