2
0

pincontrol.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* Copyright 2016 Wez Furlong
  2. * 2017 Jack Humbert
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #pragma once
  18. // Some helpers for controlling gpio pins
  19. #if defined(PROTOCOL_CHIBIOS)
  20. #include "hal.h"
  21. #define PIN_VALUE(p) palReadPad(p & 0xFFFFFFF0, p & 0xF)
  22. #define DDR_OUTPUT(p) palSetPadMode(p & 0xFFFFFFF0, p & 0xF, PAL_MODE_OUTPUT_PUSHPULL)
  23. #define DDR_INPUT(p) palSetPadMode(p & 0xFFFFFFF0, p & 0xF, PAL_MODE_INPUT_PULLDOWN)
  24. #define PORT_HIGH(p) palSetPad(p & 0xFFFFFFF0, p & 0xF)
  25. #define PORT_LOW(p) palClearPad(p & 0xFFFFFFF0, p & 0xF)
  26. #endif
  27. #if defined(__AVR__)
  28. #include <avr/io.h>
  29. #define PIN_ADDRESS(p, offset) _SFR_IO8(ADDRESS_BASE + (p >> PORT_SHIFTER) + offset)
  30. #define PIN(p) PIN_ADDRESS(p, 0)
  31. #define PIN_VALUE(p) (PIN(p) & _BV(p & 0xF))
  32. #define DDR(p) PIN_ADDRESS(p, 1)
  33. #define DDR_OUTPUT(p) (DDR(p) |= _BV(p & 0xF))
  34. #define DDR_INPUT(p) (DDR(p) &= ~_BV(p & 0xF))
  35. #define PORT(p) PIN_ADDRESS(p, 2)
  36. #define PORT_HIGH(p) (PORT(p) |= _BV(p & 0xF))
  37. #define PORT_LOW(p) (PORT(p) &= ~_BV(p & 0xF))
  38. // Arduino shortcuts
  39. enum {
  40. PinDirectionInput = 0,
  41. PinDirectionOutput = 1,
  42. PinLevelHigh = 1,
  43. PinLevelLow = 0,
  44. };
  45. // ex: pinMode(B0, PinDirectionOutput);
  46. static inline void pinMode(uint8_t pin, int mode) {
  47. uint8_t bv = _BV(pin & 0xf);
  48. if (mode == PinDirectionOutput) {
  49. _SFR_IO8((pin >> 4) + 1) |= bv;
  50. } else {
  51. _SFR_IO8((pin >> 4) + 1) &= ~bv;
  52. _SFR_IO8((pin >> 4) + 2) &= ~bv;
  53. }
  54. }
  55. // ex: digitalWrite(B0, PinLevelHigh);
  56. static inline void digitalWrite(uint8_t pin, int mode) {
  57. uint8_t bv = _BV(pin & 0xf);
  58. if (mode == PinLevelHigh) {
  59. _SFR_IO8((pin >> 4) + 2) |= bv;
  60. } else {
  61. _SFR_IO8((pin >> 4) + 2) &= ~bv;
  62. }
  63. }
  64. // Return true if the pin is HIGH
  65. // digitalRead(B0)
  66. static inline bool digitalRead(uint8_t pin) {
  67. return _SFR_IO8(pin >> 4) & _BV(pin & 0xf);
  68. }
  69. #endif