@@ -27,24 +27,36 @@ void* TimerDomain::callback_data[TimerDomain::max_instances] = {nullptr};
2727TimerDomain::InputCaptureInfo input_capture_info_dummy = {
2828 .channel_rising = 0xFF , // any value that isn't possible here
2929 .channel_falling = 0xFF , // any value that isn't possible here
30+
31+ .value_rising = 0 ,
32+ .value_falling = 0 ,
33+ .period = 0 ,
34+
35+ .duty_cycle = 0 ,
36+ .frequency = 0 ,
3037};
3138
3239TimerDomain::InputCaptureInfo* TimerDomain::input_capture_info[max_instances]
33- [input_capture_channels] = {
34- {&input_capture_info_dummy}
35- };
40+ [input_capture_channels];
3641TimerDomain::InputCaptureInfo TimerDomain::input_capture_info_backing[max_instances]
3742 [input_capture_channels];
3843
3944static void TIM_IC_CaptureCallback (const uint32_t timer_idx, uint32_t channel) {
4045 TIM_HandleTypeDef* htim = TimerDomain::hal_handles[timer_idx];
4146
4247 TimerDomain::InputCaptureInfo* info = TimerDomain::input_capture_info[timer_idx][channel];
48+ uint32_t current = (*(((volatile uint32_t *)&htim->Instance ->CCR1 ) + channel));
4349 if (info->channel_rising == channel) {
4450 // NOTE: CCR1 - CCR4 are contiguous
4551 // NOTE: CCxIF flag is cleared by software by reading the captured data in CCRx
46- uint32_t current = (*(((volatile uint32_t *)&htim->Instance ->CCR1 ) + channel));
47- uint32_t period = current - info->value_rising ;
52+ uint32_t period;
53+ if (current >= info->value_rising ) {
54+ period = current - info->value_rising ;
55+ } else {
56+ // counter wrap around
57+ uint32_t max_count = htim->Instance ->ARR - 1 ;
58+ period = (current + max_count) - info->value_rising ;
59+ }
4860
4961 if ((period != 0 ) && (info->value_falling < period)) {
5062 uint32_t ref_clock =
@@ -55,8 +67,14 @@ static void TIM_IC_CaptureCallback(const uint32_t timer_idx, uint32_t channel) {
5567 }
5668 info->value_rising = current;
5769 } else if (info->channel_falling == channel) {
58- uint32_t falling_value =
59- *(((volatile uint32_t *)&htim->Instance ->CCR1 ) + channel) - info->value_rising ;
70+ uint32_t falling_value;
71+ if (current >= info->value_rising ) {
72+ falling_value = current - info->value_rising ;
73+ } else {
74+ uint32_t max_count = htim->Instance ->ARR - 1 ;
75+ falling_value = (current + max_count) - info->value_rising ;
76+ }
77+
6078 if (falling_value < info->period )
6179 info->value_falling = falling_value;
6280 } else [[unlikely]] {
0 commit comments