carmembeddedstm32irq

Why are all irq disabled for retarget write on STM32?


I am looking at the following function which retargets stdout to UART in the STM32 Std peripheral library.

int _write(int fd, char *ptr, int len) {
  uint32_t primask = __get_PRIMASK();
  __disable_irq();

  for (int i = 0; i < len; i++) {
    while (USART_GetFlagStatus(RETARGET_CFG_UART, USART_FLAG_TXE) == RESET) {
    }
    USART_SendData(RETARGET_CFG_UART, (uint8_t) * (ptr + i));
  }

  if (!primask) {
    __enable_irq();
  }

  return len;
}

Before transmitting over UART it masks exceptions which can have a priority set via __disable_irq() (which I understand includes all peripheral and GPIO interrupts).

My question is, why is this UART tx implemented this way? Can the disable/enable irq calls be removed so that other functionality in the program is not delayed due to potentially lengthy data transactions?


Solution

  • I suspect the author of that code is disabling all interrupts just because there might be some interrupts that write bytes to the UART, and the author wants to ensure that all the bytes sent to the _write function get written consecutively, instead of having other, unrelated bytes in the middle.

    I'm assuming all the ISRs defined in your system are relatively quick compared to the serial transmission, and the receiver doesn't care if there are some small delays in the transmission. So it should be OK to leave any interrupts enabled if those interrupts are not related to the UART.

    You should get a firm grasp of all the ISRs in your system and what they do, and then you should use that to decide which specific IRQs should be disabled during this operation (if any).