What is the fastest way to change pin mode from INPUT_PULLUP to OUTPUT and back

Post here first, or if you can't find a relevant section!
Post Reply
dusan82
Posts: 2
Joined: Wed Jan 18, 2023 4:38 pm

What is the fastest way to change pin mode from INPUT_PULLUP to OUTPUT and back

Post by dusan82 »

I need to change pin mode on PB6 and PB7 fast on STM32F103. Originally I was using:

Code: Select all

pinMode(PB6, INPUT_PULLUP);
...
pinMode(PB6, OUTPUT);
Then I extracted minimal code from pinMode function:

Code: Select all

void pin_function_fast(PinName pin, int function) {
  uint32_t mode  = function == INPUT ? 0 : 1; // STM_PIN_FUNCTION(function);
  uint32_t port = 1; // STM_PORT(pin);
  uint32_t ll_pin  = pin == PB_6 ? 16448 : 32896; // STM_LL_GPIO_PIN(pin);
  uint32_t ll_mode = 0;
  GPIO_TypeDef *gpio = set_GPIO_Port_Clock(port);
  ll_mode = mode == STM_PIN_INPUT ? LL_GPIO_MODE_INPUT : LL_GPIO_MODE_OUTPUT;
  LL_GPIO_SetPinMode(gpio, ll_pin, ll_mode);
  LL_GPIO_SetPinOutputType(gpio, ll_pin, LL_GPIO_OUTPUT_PUSHPULL);
  if (function == INPUT) {
    LL_GPIO_SetPinMode(gpio, ll_pin, LL_GPIO_MODE_FLOATING);
  }
}

pin_function_fast(PB_6, 0);
...
pin_function_fast(PB_6, 1);
It's faster but still too slow. Is there any faster way?
dannyf
Posts: 447
Joined: Sat Jul 04, 2020 7:46 pm

Re: What is the fastest way to change pin mode from INPUT_PULLUP to OUTPUT and back

Post by dannyf »

The CNFx and MODEx bits do that. Check out the CRH...CRL registers.

A macro will be sufficient.
dannyf
Posts: 447
Joined: Sat Jul 04, 2020 7:46 pm

Re: What is the fastest way to change pin mode from INPUT_PULLUP to OUTPUT and back

Post by dannyf »

Code: Select all

#define PB13toPU()		do {REG_MOD(GPIOB->CRH, 0x08<<((13%8)*4), 0x0f<<((13%8)*4));} while (0)					//set PB13 to INPUT_PULLUP 0b1000, ODR bit set separately
#define PB13toPP()		do {REG_MOD(GPIOB->CRH, 0x01<<((13%8)*4), 0x0f<<((13%8)*4));} while (0)					//set PB13 to OUTPUT Pushpull 0b0001/0010/0011, ODR bit set separately
those two macros set PB13 to PU and PP, respectively.

A round trip takes 19 cycles. In comparison, my own implementation of pinMode() does the same in 310 cycles.
dusan82
Posts: 2
Joined: Wed Jan 18, 2023 4:38 pm

Re: What is the fastest way to change pin mode from INPUT_PULLUP to OUTPUT and back

Post by dusan82 »

Thanks it doubled the reading speed.
Post Reply

Return to “General discussion”