cancel
Showing results for 
Search instead for 
Did you mean: 

How do you specify GPIO ports and pins as function inputs?

LTork.1
Associate

I am new to STM32s programing in general and am trying to create some simple libraries, altough I have no idea how I would make it so that I can write it in a way, that needed ports and pins are given in function inputs. For example: int HCSR04_Distance(___, ___); HCSR04 is a distance sensor, how do I input the port and pin on the empty lines?

Thank you in advance and have a nice day

2 REPLIES 2

There are many ways to approach this, depending on what do you exactly want to achieve (execution speed, written code size and readability, etc.) For example:

int HCSR04_Distance(GPIO_TypeDef * pGPIO, uint32_t pin) {
  _Bool pinState;
  
  // if you need to read the pin
  pinState = (_Bool)(pGPIO->IDR & (1 << pin));
  
  // if you need to change the pin from digital input to digital output
  // beware if used in interrupts, this is non-atomic
  pGPIO->MODER = (pGPIO->MODER & ~(0b11 << (2 * pin))) | (0b01 << (2 * pin)); 
 
  // if you need to set the pin
  pGPIO->BSRR = 1 << pin;
  // if you need to clear the pin
  pGPIO->BSRR = 1 << (pin + 16);
    
  return pinState;
}
 
int main(void) {
  // usage, for example for PB4:
  previousPinState = HCSR04_Distance(GPIOB, 4);
}
 
 
// --- an alternative: define a structure for the pin
typedef struct {
  GPIO_TypeDef * pGPIO;
  uint32_t       pin;
} gpio_pin_t;
 
int HCSR04_Distance(gpio_pin_t p) { 
  _Bool pinState;
  
  // if you need to read the pin
  pinState = (_Bool)(p.GPIO->IDR & (1 << p.pin));
  return pinState;
}
 
const gpio_pin_t HCSR04_Pin = {.pGPIO = GPIOB, .pin = 4};
 
int main(void) {
  previousPinState = HCSR04_Distance(HCSR04_Pin);
}

JW

I see. This is perfect, thank you!