/* * rtc.c * * Created on: Jul 22, 2024 * Author: colorbass */ #include #include #include uint32_t GBT_time_offset; //current time = offset+HAL_GetTick()/1000; uint8_t tmp_time[4]; uint8_t tmp_time32; uint32_t get_Current_Time(){ return GBT_time_offset + (HAL_GetTick()/1000); } void set_Time(uint32_t unix_time){ if(unix_time <= (HAL_GetTick()/1000)) return; //invalid time GBT_time_offset = unix_time - (HAL_GetTick()/1000); } uint8_t to_bcd(int value) { return ((value / 10) << 4) | (value % 10); } void unix_to_bcd(uint32_t unix_time, uint8_t *time) { struct tm *tm_info; time_t raw_time = (time_t)unix_time; tm_info = gmtime(&raw_time); time[0] = to_bcd(tm_info->tm_sec); time[1] = to_bcd(tm_info->tm_min); time[2] = to_bcd(tm_info->tm_hour); time[3] = to_bcd(tm_info->tm_mday); time[4] = to_bcd(tm_info->tm_mon + 1); // tm_mon is 0-11 time[5] = to_bcd((tm_info->tm_year + 1900) % 100); // Year in 2 digits time[6] = to_bcd((tm_info->tm_year + 1900) / 100); // Century in 2 digits } void writeTimeReg(uint8_t reg_number, uint8_t value){ tmp_time[reg_number] = value; if(reg_number == 3) set_Time((tmp_time[0])+(tmp_time[1]<<8)+(tmp_time[2]<<16)+(tmp_time[3]<<24)); }; uint8_t getTimeReg(uint8_t reg_number){ if(reg_number == 0){ tmp_time32 = get_Current_Time(); return tmp_time32 & 0xFF; }else if(reg_number == 1){ return (tmp_time32>>8) & 0xFF; }else if(reg_number == 2){ return (tmp_time32>>16) & 0xFF; }else if(reg_number == 3){ return (tmp_time32>>24) & 0xFF; }else{ return 0x00; } }; //int main() { // uint32_t unix_time = 1672531199; // Example Unix timestamp // uint8_t time[8]; // // unix_to_bcd(unix_time, time); // // // Print the BCD values for verification // for (int i = 0; i < 8; i++) { // printf("time[%d]: %02X\n", i, time[i]); // } // // return 0; //}