STM32--片上RTC的HAL库操作

(一)STM32CubeMX设置

在这里插入图片描述

在这里插入图片描述
在上面的设置中,我在【Data Format】中使用的是RTC_FORMAT_BIN ,所有的年月日时分秒的格式都是十进制。
RTC_FORMAT_BIN 使用十进制 例如 18年你得到到是 18年
RTC_FORMAT_BCD 使用16进制 例如 18年你得到的是 0x18年

(二)代码

【rtc.c】

/* USER CODE BEGIN 0 */
RTC_TimeTypeDef GetTime;   //RTC Time
RTC_DateTypeDef GetDate;   //RTC Date
uint8_t RTC_READ_Flag;
/* USER CODE END 0 */
/*!
@Brief
	Set the time of internal RTC
@Param
	ucHour 			[Hour to set]
	ucMinute		[Minute to set]
	ucSecond		[Second to set]	
@Return
	null
*/
void RTC_SetTime(uint8_t ucHour, uint8_t ucMinute, uint8_t ucSecond)
{
  /*Configure the Time*/
  GetTime.Hours = ucHour;
  GetTime.Minutes = ucMinute;
  GetTime.Seconds = ucSecond;
//  GetTime.TimeFormat = RTC_HOURFORMAT12_AM;
  GetTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  GetTime.StoreOperation = RTC_STOREOPERATION_RESET;

  if(HAL_RTC_SetTime(&hrtc, &GetTime, RTC_FORMAT_BIN) != HAL_OK)
  {
		Error_Handler();
  }
}

/*!
@Brief
	Set the date of internal RTC
@Param
	ucYear 			[Year to set]
	ucMonth			[Month to set]
	ucDay				[Day to set]	
@Return
	null
*/
void RTC_SetDate(uint8_t ucYear, uint8_t ucMonth, uint8_t ucDay)
{
  /*Configure the Date*/
	GetDate.Year = ucYear;
	GetDate.Month = ucMonth;
  GetDate.Date = ucDay;

  if (HAL_RTC_SetDate(&hrtc, &GetDate, RTC_FORMAT_BIN) != HAL_OK)
  {
    Error_Handler();
  }
}

【rtc.h】

/* USER CODE BEGIN Prototypes */

/* Set the time of internal RTC */
void RTC_SetTime(uint8_t ucHour, uint8_t ucMinute, uint8_t ucSecond);

/* Set the date of internal RTC */
void RTC_SetDate(uint8_t ucYear, uint8_t ucMonth, uint8_t ucDay);

/* USER CODE END Prototypes */

【main.c】

	/**Set the RTC time**/
	RTC_SetTime(10, 5, 16);   //set time 10:05:16
	RTC_SetDate(21, 7, 15);		//set date 2021-7-15

	while (1)
	{	
		//CANx_SendNormalData(&hcan1, CanID, Data, 5); 
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		
		HAL_RTC_GetTime(&hrtc, &GetTime, RTC_FORMAT_BIN);	//Get the time from the internal RTC
		HAL_RTC_GetDate(&hrtc, &GetDate, RTC_FORMAT_BIN);	//Get the date from the internal RTC
		
		
		printf("20%d-%d-%d %d:%d:%d\r\n", GetDate.Year, GetDate.Month, GetDate.Date, 
									GetTime.Hours, GetTime.Minutes, GetTime.Seconds);
		HAL_Delay(1000);  //delay 1s
	}

上面的HAL_RTC_GetTime要在HAL_RTC_GetDate之前调用,否则会有问题。

(三)演示效果

在这里插入图片描述

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值