HAL_AFIO does not handle changes to JTAG/SWD properly
At least on the SMT32F103x parts, the SWJ_CFG bits in the AFIO_MAPR register are write only. Reading these bits is undefined. All of the __HAL_AFIO_REMAP macros in stm32f1xx_hal_GPIO_ex.h do read/modify/write operations to this register. This can cause wild behavior.
For example, on the STM32F103VET6:
__HAL_AFIO_REMAP_SWJ_NOJTAG();
__HAL_AFIO_REMAP_TIM4_ENABLE();
This first sets AFIO_MAPR to 0x02000000 to disable the JTAG pins. Then, while remapping TIM4 it sets AFIO_MAPR to 0x04001000 which both remaps TIM4 and completely disables JTAG and SWD. This happens because the undefined read of the SWJ_CFG bits gets written back to the AFIO_MAPR.
Workaround are to cache the state AFIO_MAPR locally and write that, or use the Bit-Band memory to operate on individual bits.
#cube-hal #afio #debug