diff --git a/src/stm32/internal.h b/src/stm32/internal.h index 05a222d0..1a7b1e74 100644 --- a/src/stm32/internal.h +++ b/src/stm32/internal.h @@ -18,6 +18,7 @@ extern GPIO_TypeDef * const digital_regs[]; #define GPIO_INPUT 0 #define GPIO_OUTPUT 1 +#define GPIO_OPEN_DRAIN 0x100 #define GPIO_FUNCTION(fn) (2 | ((fn) << 4)) #define GPIO_ANALOG 3 diff --git a/src/stm32/stm32f1.c b/src/stm32/stm32f1.c index 927ee1db..e5defd96 100644 --- a/src/stm32/stm32f1.c +++ b/src/stm32/stm32f1.c @@ -75,10 +75,15 @@ gpio_peripheral(uint32_t gpio, uint32_t mode, int pullup) cfg = pullup ? 0x8 : 0x4; } else if (mode == GPIO_OUTPUT) { cfg = 0x1; + } else if (mode == (GPIO_OUTPUT | GPIO_OPEN_DRAIN)) { + cfg = 0x5; } else if (mode == GPIO_ANALOG) { cfg = 0x0; } else { - if (pullup > 0) + if (mode & GPIO_OPEN_DRAIN) + // Alternate function with open-drain mode + cfg = 0xd; + else if (pullup > 0) // Alternate function input pins use GPIO_INPUT mode on the stm32f1 cfg = 0x8; else diff --git a/src/stm32/stm32f4.c b/src/stm32/stm32f4.c index 5a09f2d6..9d40f34c 100644 --- a/src/stm32/stm32f4.c +++ b/src/stm32/stm32f4.c @@ -72,7 +72,7 @@ gpio_peripheral(uint32_t gpio, uint32_t mode, int pullup) gpio_clock_enable(regs); // Configure GPIO - uint32_t mode_bits = mode & 0x0f, func = mode >> 4; + uint32_t mode_bits = mode & 0xf, func = (mode >> 4) & 0xf, od = mode >> 8; uint32_t pup = pullup ? (pullup > 0 ? 1 : 2) : 0; uint32_t pos = gpio % 16, af_reg = pos / 8; uint32_t af_shift = (pos % 8) * 4, af_msk = 0x0f << af_shift; @@ -81,6 +81,7 @@ gpio_peripheral(uint32_t gpio, uint32_t mode, int pullup) regs->AFR[af_reg] = (regs->AFR[af_reg] & ~af_msk) | (func << af_shift); regs->MODER = (regs->MODER & ~m_msk) | (mode_bits << m_shift); regs->PUPDR = (regs->PUPDR & ~m_msk) | (pup << m_shift); + regs->OTYPER = (regs->OTYPER & ~(1 << pos)) | (od << pos); regs->OSPEEDR = (regs->OSPEEDR & ~m_msk) | (0x02 << m_shift); }