Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.5 KiB

  1. /*
  2. GPIO MODULE
  3. Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "gpio.h"
  6. #include <bitset>
  7. // We need to explicitly call the constructor, because we need to set the const `pin`:
  8. // https://isocpp.org/wiki/faq/multiple-inheritance#virtual-inheritance-ctors
  9. GpioPin::GpioPin(unsigned char pin) :
  10. BasePin(pin)
  11. {}
  12. inline void GpioPin::pinMode(int8_t mode) {
  13. ::pinMode(this->pin, mode);
  14. }
  15. inline void GpioPin::digitalWrite(int8_t val) {
  16. ::digitalWrite(this->pin, val);
  17. }
  18. inline int GpioPin::digitalRead() {
  19. return ::digitalRead(this->pin);
  20. }
  21. // --------------------------------------------------------------------------
  22. constexpr const size_t GPIO_PINS = 17;
  23. std::bitset<GPIO_PINS> _gpio_locked;
  24. std::bitset<GPIO_PINS> _gpio_available;
  25. bool gpioValid(unsigned char gpio) {
  26. if (gpio >= GPIO_PINS) return false;
  27. return _gpio_available.test(gpio);
  28. }
  29. bool gpioGetLock(unsigned char gpio) {
  30. if (gpioValid(gpio)) {
  31. if (!_gpio_locked.test(gpio)) {
  32. _gpio_locked.set(gpio);
  33. DEBUG_MSG_P(PSTR("[GPIO] GPIO%u locked\n"), gpio);
  34. return true;
  35. }
  36. }
  37. DEBUG_MSG_P(PSTR("[GPIO] Failed getting lock for GPIO%u\n"), gpio);
  38. return false;
  39. }
  40. bool gpioReleaseLock(unsigned char gpio) {
  41. if (gpioValid(gpio)) {
  42. _gpio_locked.reset(gpio);
  43. DEBUG_MSG_P(PSTR("[GPIO] GPIO%u lock released\n"), gpio);
  44. return true;
  45. }
  46. DEBUG_MSG_P(PSTR("[GPIO] Failed releasing lock for GPIO%u\n"), gpio);
  47. return false;
  48. }
  49. void gpioSetup() {
  50. // https://github.com/espressif/esptool/blob/f04d34bcab29ace798d2d3800ba87020cccbbfdd/esptool.py#L1060-L1070
  51. // "One or the other efuse bit is set for ESP8285"
  52. // https://github.com/espressif/ESP8266_RTOS_SDK/blob/3c055779e9793e5f082afff63a011d6615e73639/components/esp8266/include/esp8266/efuse_register.h#L20-L21
  53. // "define EFUSE_IS_ESP8285 (1 << 4)"
  54. const uint32_t efuse_blocks[4] {
  55. READ_PERI_REG(0x3ff00050),
  56. READ_PERI_REG(0x3ff00054),
  57. READ_PERI_REG(0x3ff00058),
  58. READ_PERI_REG(0x3ff0005c)
  59. };
  60. const bool esp8285 = (
  61. (efuse_blocks[0] & (1 << 4))
  62. || (efuse_blocks[2] & (1 << 16))
  63. );
  64. // TODO: GPIO16 is only for basic I/O, gpioGetLock before attachInterrupt should check for that
  65. for (unsigned char pin=0; pin < GPIO_PINS; ++pin) {
  66. if (pin <= 5) _gpio_available.set(pin);
  67. if (((pin == 9) || (pin == 10)) && (esp8285)) _gpio_available.set(pin);
  68. if (12 <= pin && pin <= 16) _gpio_available.set(pin);
  69. }
  70. }