From 97a5b39aab9bb61aaf2181760886033a569626f7 Mon Sep 17 00:00:00 2001 From: Kevin O'Connor Date: Thu, 25 Aug 2022 17:19:36 -0400 Subject: [PATCH] stm32: Add a gpio_valid() helper function Add a function to validate that a gpio pin is valid on the chip. Signed-off-by: Kevin O'Connor --- src/stm32/gpio.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/stm32/gpio.c b/src/stm32/gpio.c index 4b7649dc..d19437cb 100644 --- a/src/stm32/gpio.c +++ b/src/stm32/gpio.c @@ -66,20 +66,24 @@ regs_to_pin(GPIO_TypeDef *regs, uint32_t bit) return 0; } +// Verify that a gpio is a valid pin +static int +gpio_valid(uint32_t pin) +{ + uint32_t port = GPIO2PORT(pin); + return port < ARRAY_SIZE(digital_regs) && digital_regs[port]; +} + struct gpio_out gpio_out_setup(uint32_t pin, uint32_t val) { - if (GPIO2PORT(pin) >= ARRAY_SIZE(digital_regs)) - goto fail; + if (!gpio_valid(pin)) + shutdown("Not an output pin"); GPIO_TypeDef *regs = digital_regs[GPIO2PORT(pin)]; - if (! regs) - goto fail; gpio_clock_enable(regs); struct gpio_out g = { .regs=regs, .bit=GPIO2BIT(pin) }; gpio_out_reset(g, val); return g; -fail: - shutdown("Not an output pin"); } void @@ -125,16 +129,12 @@ gpio_out_write(struct gpio_out g, uint32_t val) struct gpio_in gpio_in_setup(uint32_t pin, int32_t pull_up) { - if (GPIO2PORT(pin) >= ARRAY_SIZE(digital_regs)) - goto fail; + if (!gpio_valid(pin)) + shutdown("Not a valid input pin"); GPIO_TypeDef *regs = digital_regs[GPIO2PORT(pin)]; - if (! regs) - goto fail; struct gpio_in g = { .regs=regs, .bit=GPIO2BIT(pin) }; gpio_in_reset(g, pull_up); return g; -fail: - shutdown("Not a valid input pin"); } void