BASIC4MCU | 질문게시판 | stm32에서 RTC 시간 함수 쓰는데 의문점
페이지 정보
작성자 라칸 작성일2023-09-25 10:13 조회619회 댓글1건본문
switch (q[1]){
case get_Time:
if(isRegistered == CONNECT && access == CONNECT){
body_q[0] = EL_ID;
time_t Timestamp;
Timestamp = gettime();
uint8_t *data_ptr = &body_q[1];
for (int i = 0; i < 4; i++) {
data_ptr[i] = (Timestamp >> (8 * (3 - i))) & 0xFF;
}
}
break;
case set_Time:
memset(time_check, 0x0, sizeof(time_check));
if(isRegistered == CONNECT && access == CONNECT){
body_q[0] = EL_ID;
for(int k = 0; k < 4; k++){
time_check[k] = body_q[k + 1];
}
settime(time_check);
time_t Timecheck;
Timecheck = gettime();
uint8_t *data_ptr = &body_q[1];
for (int i = 0; i < 4; i++) {
data_ptr[i] = (Timecheck >> (8 * (3 - i))) & 0xFF;
}
}
break;
default:
break;
}
uint32_t gettime(){
RTC_TimeTypeDef gTime;
RTC_DateTypeDef gDate;
struct tm get_timeinfo;
time_t get_Timestamp;
// STM32의 RTC에서 현재 로컬 시간 및 날짜 정보를 가져옵니다.
HAL_RTC_GetTime(&hrtc, &gTime, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&hrtc, &gDate, RTC_FORMAT_BIN); // 날짜를 가져오지 않으면 시간 정보가 업데이트되지 않습니다.
// struct tm 형식으로 변환
get_timeinfo.tm_hour = gTime.Hours - 9; // UTC로 변환
get_timeinfo.tm_min = gTime.Minutes;
get_timeinfo.tm_sec = gTime.Seconds;
get_timeinfo.tm_mday = gDate.Date;
get_timeinfo.tm_mon = gDate.Month - 1; // tm_mon은 0부터 시작
get_timeinfo.tm_year = gDate.Year + 100; // 1900을 기준으로 함
// UNIX 타임스탬프로 변환
get_Timestamp = mktime(&get_timeinfo);
return get_Timestamp;
}
void settime(uint8_t time_check[]){
// UNIX 타임스탬프 정보를 가져옵니다.
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
struct tm set_timeinfo;
time_t rawtime;
uint32_t set_Timestamp = 0;
for (int check = 0; check < 4; check++) {
set_Timestamp = (set_Timestamp << 8) | time_check[check];
}
rawtime = (time_t) set_Timestamp;
localtime_r(&rawtime, &set_timeinfo);
// 한국 시간에 맞춰 조정
set_timeinfo.tm_hour += 9;
sTime.Hours = set_timeinfo.tm_hour;
sTime.Minutes = set_timeinfo.tm_min;
sTime.Seconds = set_timeinfo.tm_sec;
sDate.Date = set_timeinfo.tm_mday;
sDate.Month = set_timeinfo.tm_mon + 1; // tm_mon은 0부터 시작하므로 1을 더함.
sDate.Year = set_timeinfo.tm_year - 100;
// 시간 및 날짜 설정
HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
}
이걸 사용해서 RTC시간 설정 및 불러오기를 하는데
set_Time에 gettime하고 배열에 추가하는거 안해도 되야하는데
왜 저걸 해야지 get_Time때 설정값했던 값이 원하는대로 나올까요
HAL_Delay로 해보고 gettime함수만 쓰는것만 해봤는데도
불러오기할때 설정값하고 다른값이 나오고
time_t Timecheck;
Timecheck = gettime();
uint8_t *data_ptr = &body_q[1];
for (int i = 0; i < 4; i++) {
data_ptr[i] = (Timecheck >> (8 * (3 - i))) & 0xFF;
}
이걸 추가해야지 왜 원하는 입력값이 불러오기가 되는걸까요?
댓글 1
조회수 619master님의 댓글
master 작성일
data_ptr[] 배열에 시간값을 읽어온 시점이 언제인지 고민 해보세요
십년전에 읽었다면 십년전 시간값이 읽히겠죠