/*========================================================== 函数名称:initRCCJJY…
- User
/========================================================== 函数名称:init_RCC_JJY 函数功能:初始化JJY接收参数,重新启动接收 输入参量: 输出参量: ==========================================================/ void init_RCC_JJY(void) { JJY_status = 0; JJY_TCO_time = 0; JJY_TCO_new_time = 0; JJY_sync_time = 0;
for(JJY_counter=0;JJY_counter<_JJY_BUF;JJY_counter++) { JJY_buf[JJY_counter]=0; } JJY_counter = 0;}
/========================================================== 函数名称:JJY_encoder 函数功能:将接收到的JJY编码转换为时间代码 输入参量: 输出参量: ==========================================================/ void JJY_encoder(void) { unsigned short temp_day; unsigned char i,j,k,z;
//BCD CODE to HEX JJY_second = 0; JJY_minute = ((JJY_buf[7]&0x7)*10) + ((JJY_buf[6]>>3)&0xf); JJY_hour = ((JJY_buf[5]>>6)*10) + ((JJY_buf[5]>>1)&0xf); temp_day = (((JJY_buf[4]>>4&0x3))*100) + (((JJY_buf[4]<<1)&0xf)*10) + ((JJY_buf[3]>>7)*10) + ((JJY_buf[3]>>2)&0xf); JJY_year = (((JJY_buf[2]<<1)&0xf)*10) + ((JJY_buf[1]>>7)*10) + ((JJY_buf[1]>>3)&0xf); JJY_week = ((JJY_buf[1]<<1)&0x7) + (JJY_buf[1]>>7); JJY_day = 1; JJY_month = 1; while(temp_day) //总日期转换为月份和日期 { if((JJY_month==1)||(JJY_month==3)||(JJY_month==5)||(JJY_month==7)\ ||(JJY_month==8)||(JJY_month==10)||(JJY_month==12)) { i=31; } else if((JJY_month==4)||(JJY_month==6)||(JJY_month==9)||(JJY_month==10)) { i=30; } else { if(JJY_year%4==0) { i=29; } else { i=28; } } if(temp_day > i) { temp_day-=i; JJY_month++; } else { JJY_day = temp_day; temp_day=0; } }; //在这后面加入校验,可在一定程度上防止出错 i=1; j=1; z=0; for(k=0;k<8;k++) { if(JJY_hour&j) { z++; } j<<=1; } if((JJY_buf[2]>>7) != (z&0x1)) //小时奇偶校验 { i=0; } j=1;z=0; for(k=0;k<8;k++) { if(JJY_minute&j){z++;} j<<=1; } if(((JJY_buf[2]>>6)&0x1) != (z&0x1)) {i=0;} //分钟奇偶校验 if((i==1)\ //奇偶校验 &&(JJY_minute<60)\ //分钟校验 &&(JJY_hour<24)\ //小时校验 &&((JJY_day>=1)&&(JJY_day<=31))\ //日期校验 &&((JJY_month>=1)&&(JJY_month<=12))\ //月份校验 &&(JJY_year<=99)) //年份校验 { //校验正确,将数据送给实时时钟 //................. //................. } else { //校验出错,得重新接收 JJY_status &= (~_JJY_START_F); JJY_status &= (~_JJY_OK_F); JJY_counter=0; }}
/========================================================== 函数名称:save_TCO_code 函数功能:保存一位接收到的编码 输入参量: 输出参量: ==========================================================/ void save_TCO_code(unsigned char TCO_code) { unsigned char i;
for(i=_JJY_BUF-1;i>0;i--) { JJY_buf[i] <<= 1; if(JJY_buf[i-1]&0x80) { JJY_buf[i] |= 0x1; } } JJY_buf[0] <<= 1; if(TCO_code) { JJY_buf[0] |= 0x1; } if(++JJY_counter >= _MAX_JJY_CODE) { JJY_encoder(); //JJY解码 JJY_status |= _JJY_OK_F; }}
/========================================================== 函数名称:Receiver_JJY 函数功能:JJY接收程序 输入参量: 输出参量: ==========================================================/ void Receiver_JJY(void) { unsigned char new_tco,new_code;
if(JJY_status&_JJY_OK_F) return;#if(TCO_SIGNAL_LEVEL == 1) if(TCO_IN) { new_tco = 1; } else { new_tco = 0; } #else if(TCO_IN) { new_tco = 1; } else { new_tco = 0; } #endif
if(++JJY_sync_time >= 100) { JJY_sync_time = 0; JJY_TCO_new_time = 0; } if(((new_tco)&&(!(JJY_status&_JJY_TCO_F)))||(!(new_tco)&&(JJY_status&_JJY_TCO_F))) { if(++JJY_TCO_new_time >= _NEW_TCO_TIME) //新的数据有效 { if((JJY_TCO_time>=(_TCO_0_TIME-_TCO_OFFSET_TIME))&&(JJY_TCO_time<=(_TCO_0_TIME+_TCO_OFFSET_TIME)&&(JJY_status&_JJY_TCO_F))) { new_code=_TCO_CODE_0; } else if((JJY_TCO_time>=(_TCO_1_TIME-_TCO_OFFSET_TIME))&&(JJY_TCO_time<=(_TCO_1_TIME+_TCO_OFFSET_TIME)&&(JJY_status&_JJY_TCO_F))) { new_code=_TCO_CODE_1; } else if((JJY_TCO_time>=(_TCO_P_TIME-_TCO_OFFSET_TIME))&&(JJY_TCO_time<=(_TCO_P_TIME+_TCO_OFFSET_TIME)&&(JJY_status&_JJY_TCO_F))) { new_code=_TCO_CODE_P; } else if(JJY_status&_JJY_TCO_F) { new_code=_TCO_CODE_ERR; } if(!(JJY_status&_JJY_SYNC_F)) //准备时间同步 { if(!(JJY_status&_JJY_TCO_F)) { if((JJY_sync_time<=_SYNC_OFFSET_TIME)||(JJY_sync_time>=(100-_SYNC_OFFSET_TIME))) { if(++JJY_counter >= _SYNC_TIME) { JJY_status |= _JJY_SYNC_F; JJY_counter = 0; } } else { JJY_counter = 0; } JJY_sync_time = JJY_TCO_new_time; } } else if(!(JJY_status&_JJY_START_F)) //启动信号 { if(JJY_status&_JJY_TCO_F) { if((JJY_TCO_code==_TCO_CODE_P)&&(new_code==_TCO_CODE_P)) { JJY_status|=_JJY_START_F; for(JJY_counter=0;JJY_counter<_JJY_BUF;JJY_counter++) { JJY_buf[JJY_counter]=0; } JJY_counter = 0; save_TCO_code(0); } else if(++JJY_counter >= _MAX_START_TIME) { init_RCC_JJY(); //防止同步时间出错后收不到 } } } else if(JJY_status&_JJY_TCO_F)//接收数据 { if((new_code==_TCO_CODE_0)||(new_code==_TCO_CODE_P)) { save_TCO_code(0); } else if(new_code==_TCO_CODE_1) { save_TCO_code(1); } else //出错了,重来 { for(JJY_counter=0;JJY_counter<_JJY_BUF;JJY_counter++) { JJY_buf[JJY_counter]=0; } JJY_counter = 0; JJY_status &= (~_JJY_START_F); } if((JJY_TCO_code==_TCO_CODE_P)&&(new_code==_TCO_CODE_P)) { if(!(JJY_status&_JJY_OK_F)) //发现新的同步信号,重来 { for(JJY_counter=0;JJY_counter<_JJY_BUF;JJY_counter++) { JJY_buf[JJY_counter]=0; } JJY_counter = 0; } } } if(JJY_status&_JJY_TCO_F) { JJY_TCO_code = new_code; } if(new_tco) { JJY_status |=_JJY_TCO_F; } else { JJY_status &= ~_JJY_TCO_F; } JJY_TCO_time = JJY_TCO_new_time; JJY_TCO_new_time=0; } } else { if(JJY_TCO_new_time > 0) { JJY_TCO_time += JJY_TCO_new_time; JJY_TCO_new_time=0; } if(JJY_TCO_time < 100) { JJY_TCO_time++; } }}
Assistant
Of course. This is a set of C functions for a microcontroller designed to receive and decode the Japanese JJY radio time signal. Here is a detailed analysis of the code, including its functionality, strengths, weaknesses, and a refactored version with improvements.
Code Description and Analysis
The code implements a state machine to receive and interpret the amplitude-modulated JJY signal, which encodes the time and date.
-
init_RCC_JJY():- Functionality: This is a reset function. It initializes all global state variables, clears the receive buffer, and sets the system to its initial state, ready to start a new reception attempt.
- Analysis: Simple and effective. It correctly resets the state, which is crucial for recovering from errors.
-
save_TCO_code():- Functionality: This function acts as a software shift register. It takes a single bit (
0or1) and shifts it into a multi-byte buffer (JJY_buf). The bits are shifted from right to left, with the new bit entering atJJY_buf[0], bit 0. - Analysis: The implementation is correct for a "big-endian" bit buffer. It's a bit complex to visualize but it works. When the buffer is full (
JJY_counter >= _MAX_JJY_CODE), it triggers the decoding process.
- Functionality: This function acts as a software shift register. It takes a single bit (
-
Receiver_JJY():- Functionality: This is the heart of the system. It's a state machine that should be called periodically (e.g., by a timer interrupt every 1-10ms). It performs the following steps:
- Reads the input pin (
TCO_IN). - Measures the duration of high and low signal levels to determine the type of pulse received (a '0' bit, a '1' bit, or a 'P' marker bit).
- Synchronization State (
!_JJY_SYNC_F): First, it tries to synchronize its internal clock with the 1-second pulses of the JJY signal. - Start-of-Frame State (
!_JJY_START_F): After syncing, it waits for the unique start-of-frame sequence, which is typically two consecutive marker pulses. - Data Reception State (
_JJY_START_F): Once the frame has started, it receives each bit, callingsave_TCO_code()to store it. - Error Handling: If an invalid pulse duration is detected or the start sequence appears mid-frame unexpectedly, it resets parts of the state machine to recover.
- Reads the input pin (
- Analysis: This function is very dense and uses a complex series of nested
ifstatements and status flags (JJY_status). This makes it difficult to read, debug, and maintain. The logic is tightly coupled and relies heavily on global variables.
- Functionality: This is the heart of the system. It's a state machine that should be called periodically (e.g., by a timer interrupt every 1-10ms). It performs the following steps:
-
JJY_encoder()(misnamed, should beJJY_decoder):- Functionality: Once a full frame of data is in
JJY_buf, this function is called to:- Extract the BCD (Binary-Coded Decimal) values for minute, hour, day-of-year, and year from the bit buffer.
- Convert the day-of-year into a month and day.
- Perform parity checks on the hour and minute data.
- Perform sanity checks on the final values (e.g.,
minute < 60). - If all checks pass, the time is considered valid. If not, it resets the receiver to try again.
- Analysis:
- The bit-fiddling to extract data (
((JJY_buf[7]&0x7)*10) + ...) is highly specific to the JJY format and the waysave_TCO_codebuilds the buffer. It's functional but brittle. - The day-of-year conversion loop is correct in principle but has a critical bug.
- The parity and sanity checks are excellent for ensuring data integrity.
- The bit-fiddling to extract data (
- Functionality: Once a full frame of data is in
Strengths and Weaknesses
Strengths:
- Complete Implementation: It covers all necessary steps from signal edge detection to final data validation.
- Robustness: Includes parity checks, sanity checks, and error recovery mechanisms (resetting on invalid data).
- Stateful Design: Correctly uses a state machine to handle the time-dependent nature of the protocol.
Weaknesses & Bugs:
- CRITICAL BUG: In
JJY_encoder, the check for months with 30 days iselse if((JJY_month==4)||(JJY_month==6)||(JJY_month==9)||(JJY_month==10)). The second10should be11. This will cause incorrect date calculations for November and December. - Poor Readability: The state machine in
Receiver_JJYis a "spaghetti" of nestedif-elseconditions and flags. This is very hard to follow. Aswitchstatement on an enumerated state would be vastly superior. - Redundant Code: The
#if(TCO_SIGNAL_LEVEL == 1)block inReceiver_JJYhas identical code in itsifandelseparts, making it useless. - Misleading Name:
JJY_encoderactually decodes the data. It should be namedJJY_decoderorJJY_decode_frame. - Inefficiency: The loop to convert day-of-year to month/day can be replaced by a faster and cleaner lookup table. The
forloop to clearJJY_bufcan be replaced withmemset. - Tight Coupling: All functions communicate through a large set of global variables, making the code harder to test and reuse.
Refactored and Improved Code
Here is a rewritten version of the code that addresses the identified issues. It's more readable, robust, and maintainable.
Assumptions for the new code:
- We'll define the missing macros and types.
- We'll group state variables into a
struct. - We'll use
enumfor states to improve readability.
#include <string.h> // For memset // --- Assumed Constants and Definitions (replace with actual values) --- #define _JJY_BUF 8 // Size of the buffer in bytes (64 bits) #define _MAX_JJY_CODE 60 // Number of bits in a JJY frame (1 minute) #define TCO_IN P1.0 // Example input pin #define _NEW_TCO_TIME 3 // Debounce time for new signal (e.g., 3 * 10ms = 30ms) #define _TCO_CODE_0 0 #define _TCO_CODE_1 1 #define _TCO_CODE_P 2 // Marker pulse #define _TCO_CODE_ERR 3 // Error/invalid pulse #define _TCO_0_TIME 80 // Duration of '0' pulse (e.g., 80 * 10ms = 800ms) #define _TCO_1_TIME 50 // Duration of '1' pulse (e.g., 50 * 10ms = 500ms) #define _TCO_P_TIME 20 // Duration of Marker pulse (e.g., 20 * 10ms = 200ms) #define _TCO_OFFSET_TIME 10 // Tolerance for pulse duration (e.g., 10 * 10ms = 100ms) #define _SYNC_OFFSET_TIME 5 #define _SYNC_TIME 2 #define _MAX_START_TIME 5 // --- Global Variables for Final Time --- // It's good practice to mark them volatile if they are accessed in an ISR and main loop volatile unsigned char JJY_minute; volatile unsigned char JJY_hour; volatile unsigned char JJY_day; volatile unsigned char JJY_month; volatile unsigned char JJY_year; // 0-99 volatile unsigned char JJY_week; // --- State Machine Enumeration for Clarity --- typedef enum { STATE_RESET, STATE_SYNCING, STATE_WAIT_FOR_START, STATE_RECEIVING, STATE_FRAME_RECEIVED, STATE_ERROR } JJY_ReceiverState_t; // --- State Struct to Group Related Variables --- typedef struct { JJY_ReceiverState_t state; unsigned char buf[_JJY_BUF]; unsigned char bit_counter; unsigned char sync_counter; unsigned char last_signal_level; unsigned int pulse_duration_ticks; // Measures duration of high/low pulses } JJY_Control_t; JJY_Control_t jjy; // --- Forward Declarations --- void JJY_decode_and_validate(void); /*========================================================== 函数名称: init_RCC_JJY 函数功能: 初始化JJY接收参数, 重新启动接收 ==========================================================*/ void init_RCC_JJY(void) { // Using memset is cleaner and often faster memset(&jjy, 0, sizeof(JJY_Control_t)); jjy.state = STATE_SYNCING; // Start by looking for sync } /*========================================================== 函数名称: JJY_decode_and_validate (Formerly JJY_encoder) 函数功能: 将接收到的JJY编码转换为时间代码并校验 ==========================================================*/ void JJY_decode_and_validate(void) { unsigned short temp_day; unsigned char temp_minute, temp_hour, temp_year, temp_month, temp_day_of_month, temp_week; unsigned char i, parity_h, parity_m; int is_valid = 1; // Assume valid until a check fails // BCD CODE to HEX // The bit extraction logic is specific to the JJY format and how bits are stored. // This part remains the same as it depends on the hardware/protocol. temp_minute = ((jjy.buf[7] & 0x07) * 10) + ((jjy.buf[6] >> 3) & 0x0F); temp_hour = ((jjy.buf[5] >> 6) * 10) + ((jjy.buf[5] >> 1) & 0x0F); temp_day = (((jjy.buf[4] >> 4) & 0x03) * 100) + (((jjy.buf[4] << 1) & 0x0F) * 10) + ((jjy.buf[3] >> 7) * 10) + ((jjy.buf[3] >> 2) & 0x0F); temp_year = (((jjy.buf[2] << 1) & 0x0F) * 10) + ((jjy.buf[1] >> 7) * 10) + ((jjy.buf[1] >> 3) & 0x0F); temp_week = ((jjy.buf[1] << 1) & 0x07); // This calculation seemed unusual, simplified for clarity // --- Validation Step 1: Parity Checks --- parity_h = 0; for (i = 0; i < 8; i++) { if ((temp_hour >> i) & 1) parity_h++; } parity_m = 0; for (i = 0; i < 8; i++) { if ((temp_minute >> i) & 1) parity_m++; } // Compare with received parity bits if (((jjy.buf[2] >> 7) & 1) != (parity_h & 1)) is_valid = 0; // Hour parity mismatch if (((jjy.buf[2] >> 6) & 1) != (parity_m & 1)) is_valid = 0; // Minute parity mismatch // --- Validation Step 2: Sanity Checks on Raw Values --- if ((temp_minute >= 60) || (temp_hour >= 24) || (temp_day == 0 || temp_day > 366)) { is_valid = 0; } // --- Convert Day-of-Year to Month and Day --- if (is_valid) { // Use a lookup table for speed and clarity const int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int is_leap = (temp_year % 4 == 0); // JJY years are 00-99, so this is sufficient temp_month = 1; while (temp_day > 0) { int days = days_in_month[temp_month]; if (is_leap && temp_month == 2) { days = 29; } if (temp_day > days) { temp_day -= days; temp_month++; } else { temp_day_of_month = temp_day; temp_day = 0; // Exit loop } } // Final sanity check on calculated date if (temp_month > 12) is_valid = 0; if (is_valid) { // --- ALL CHECKS PASSED --- // Update the global time variables JJY_minute = temp_minute; JJY_hour = temp_hour; JJY_day = temp_day_of_month; JJY_month = temp_month; JJY_year = temp_year; JJY_week = temp_week; // Set state to indicate success jjy.state = STATE_FRAME_RECEIVED; } } if (!is_valid) { // --- VALIDATION FAILED --- // Reset to start reception again init_RCC_JJY(); } } /*========================================================== 函数名称: save_TCO_code 函数功能: 保存一位接收到的编码 ==========================================================*/ void save_TCO_code(unsigned char bit_value) { // Shift the entire buffer one bit to the left for (int i = _JJY_BUF - 1; i > 0; i--) { jjy.buf[i] <<= 1; if (jjy.buf[i - 1] & 0x80) { // Carry bit from previous byte jjy.buf[i] |= 0x01; } } jjy.buf[0] <<= 1; if (bit_value) { jjy.buf[0] |= 0x01; } if (++jjy.bit_counter >= _MAX_JJY_CODE) { JJY_decode_and_validate(); } } /*========================================================== 函数名称: Receiver_JJY_Tick 函数功能: JJY接收状态机 - 应被定时器周期性调用(如每10ms) ==========================================================*/ void Receiver_JJY_Tick(void) { unsigned char current_signal_level = TCO_IN ? 1 : 0; // If we have a valid frame, do nothing until reset. if (jjy.state == STATE_FRAME_RECEIVED) { return; } // Increment pulse timer while signal is stable jjy.pulse_duration_ticks++; // --- Edge Detection --- if (current_signal_level != jjy.last_signal_level) { // The signal level has changed, a pulse has just ended. // Debounce: ignore very short glitches if (jjy.pulse_duration_ticks < _NEW_TCO_TIME) { jjy.last_signal_level = current_signal_level; // Update level jjy.pulse_duration_ticks = 0; // Reset timer and ignore return; } // --- Decode the Pulse based on its duration --- unsigned char decoded_pulse = _TCO_CODE_ERR; // JJY encodes information in the duration of the HIGH pulse if (jjy.last_signal_level == 1) { if ((jjy.pulse_duration_ticks >= (_TCO_0_TIME - _TCO_OFFSET_TIME)) && (jjy.pulse_duration_ticks <= (_TCO_0_TIME + _TCO_OFFSET_TIME))) { decoded_pulse = _TCO_CODE_0; } else if ((jjy.pulse_duration_ticks >= (_TCO_1_TIME - _TCO_OFFSET_TIME)) && (jjy.pulse_duration_ticks <= (_TCO_1_TIME + _TCO_OFFSET_TIME))) { decoded_pulse = _TCO_CODE_1; } else if ((jjy.pulse_duration_ticks >= (_TCO_P_TIME - _TCO_OFFSET_TIME)) && (jjy.pulse_duration_ticks <= (_TCO_P_TIME + _TCO_OFFSET_TIME))) { decoded_pulse = _TCO_CODE_P; } } // --- State Machine Logic --- switch (jjy.state) { case STATE_SYNCING: // To sync, we look for two consecutive marker pulses if (decoded_pulse == _TCO_CODE_P) { jjy.sync_counter++; if (jjy.sync_counter >= 2) { jjy.state = STATE_WAIT_FOR_START; jjy.bit_counter = 0; // Ready for start of frame } } else { jjy.sync_counter = 0; // Reset if not a marker } break; case STATE_WAIT_FOR_START: // The frame starts with a marker pulse at second 59 if (decoded_pulse == _TCO_CODE_P) { jjy.state = STATE_RECEIVING; jjy.bit_counter = 0; memset(jjy.buf, 0, _JJY_BUF); // Clear buffer for new frame } break; case STATE_RECEIVING: if (decoded_pulse == _TCO_CODE_0) { save_TCO_code(0); } else if (decoded_pulse == _TCO_CODE_1) { save_TCO_code(1); } else if (decoded_pulse == _TCO_CODE_P) { // A marker pulse here indicates the end of a minute. // If we haven't received enough bits, it's an error. init_RCC_JJY(); // Reset and try again } else { // _TCO_CODE_ERR init_RCC_JJY(); // Invalid pulse, reset } break; default: // Should not happen, but as a safeguard: init_RCC_JJY(); break; } // --- Cleanup for next edge --- jjy.last_signal_level = current_signal_level; jjy.pulse_duration_ticks = 0; } // Timeout: If pulse is too long (e.g., > 2 seconds), signal is lost. if (jjy.pulse_duration_ticks > 200) { // 200 * 10ms = 2s init_RCC_JJY(); } }Summary of Improvements in the Refactored Code
- Bug Fixed: The critical bug in the month calculation (
10vs11) is fixed by using a correct lookup table. - Readability:
- The state machine in
Receiver_JJY_Ticknow uses anenumand aswitchstatement, making the logic flow explicit and easy to understand. - Global variables are grouped into a
JJY_Control_tstruct, clarifying what constitutes the "state" of the receiver. JJY_encoderis renamed to the more accurateJJY_decode_and_validate.
- The state machine in
- Efficiency:
memsetis used to clear buffers.- A lookup table
days_in_month[]is used for faster date conversion.
- Maintainability:
- The logic is decoupled.
Receiver_JJY_Tickhandles signal timing,save_TCO_codehandles bit storage, andJJY_decode_and_validatehandles data interpretation. This separation of concerns makes future modifications easier. - Redundant code has been removed.
- Self-documenting names (
STATE_SYNCING,pulse_duration_ticks) are used.
- The logic is decoupled.
- Robustness: A timeout was added to handle cases where the signal is completely lost (stuck high or low). The error handling is more centralized.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.