2026-05-15 1:25 AM - edited 2026-05-15 1:27 AM
Hello, I'm curious why TIM2 is correctly repeating in my code, whereas TIM4 with equivalent settings is not.
In this code, the TIM2 indicator (fired by the TIM2 interrupt) is blinking twice a second (clock set to LSI, meaning 128kHz). I would expect the TIM4 indicator (fired by the TIM4 interrupt) to do the same; but it is being triggered immediately and much faster: so fast that to the eye it appears as a constant on.
The reference manual RM0016 and datasheet DS7147 indicate that, given similar settings, both timers should be exhibiting similar behavior. What am I missing?
Here's the code:
; some typical setup hidden before this point
; PD3 is on, indicating LSI is clock source
ld a, CLK_SWR
cp a, #0xd2
jrne 1$
bset PD_ODR, #3
; timer setup
sim
; F_Master Prescalar tim clk
; 128_000 Hz / 1024 = 125
mov TIM2_PSCR, #0b1010 ; 2 ** 0b1010 = 1024 prescaler
mov TIM2_ARRH, #0d0
mov TIM2_ARRL, #0d125
bset TIM2_IER, #0 ; UIE: Update interrupt enable
bset TIM2_CR1, #0 ; CEN: Counter enable
; same as TIM2
mov TIM4_PSCR, #0b1010
mov TIM4_ARR, #0d125
bset TIM4_IER, #0 ; UIE: Update interrupt enable
bset TIM4_CR1, #0 ; CEN: Counter enable
rim
; loop
1$:
wfi
jp 1$
tim2_up_isr:
bres TIM2_SR1, #0 ; UIF: Update interrupt flag
; blinks twice per second
bcpl PC_ODR, #6
iret
tim4_up_isr:
bres TIM4_SR, #0 ; UIF: Update interrupt flag
; blinks continuously
bcpl PC_ODR, #7
iret
Solved! Go to Solution.
2026-05-15 4:46 AM
Yes, you missed one bit:
As a result, for TIM4 with PSCR = (0b1010 AND 0b0111), this gives a prescaler of 4 instead of 1024, i.e. 256Hz instead of the required 1Hz.
Regards
/Peter
2026-05-15 1:32 AM
TIM2 is a 16-bit timer, whereas TIM4 is only an 8-bit timer. Please take another look at your programme in light of this premise.
Regards
/Peter
2026-05-15 1:59 AM
> TIM2 is a 16-bit timer, whereas TIM4 is only an 8-bit timer.
Thank you for replying. I can understand when this would matter if I'm attempting to use values that wouldn't fit into an 8 bit timer. But in this case the ARR value for both timers is clearly able to fit into both 8 bits and 16 bits. Perhaps I'm overlooking something?
2026-05-15 4:46 AM
Yes, you missed one bit:
As a result, for TIM4 with PSCR = (0b1010 AND 0b0111), this gives a prescaler of 4 instead of 1024, i.e. 256Hz instead of the required 1Hz.
Regards
/Peter
2026-05-15 5:06 AM
Thank you! That is indeed the missing piece I was overlooking.