gpio.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Copyright 2018 Canaan Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #include "fpioa.h"
  16. #include "gpio.h"
  17. #include "sysctl.h"
  18. #include "utils.h"
  19. #define GPIO_MAX_PINNO 8
  20. volatile gpio_t *const gpio = (volatile gpio_t *)GPIO_BASE_ADDR;
  21. int gpio_init(void)
  22. {
  23. return sysctl_clock_enable(SYSCTL_CLOCK_GPIO);
  24. }
  25. void gpio_set_drive_mode(uint8_t pin, gpio_drive_mode_t mode)
  26. {
  27. configASSERT(pin < GPIO_MAX_PINNO);
  28. int io_number = fpioa_get_io_by_function(FUNC_GPIO0 + pin);
  29. configASSERT(io_number >= 0);
  30. fpioa_pull_t pull;
  31. uint32_t dir;
  32. switch(mode)
  33. {
  34. case GPIO_DM_INPUT:
  35. pull = FPIOA_PULL_NONE;
  36. dir = 0;
  37. break;
  38. case GPIO_DM_INPUT_PULL_DOWN:
  39. pull = FPIOA_PULL_DOWN;
  40. dir = 0;
  41. break;
  42. case GPIO_DM_INPUT_PULL_UP:
  43. pull = FPIOA_PULL_UP;
  44. dir = 0;
  45. break;
  46. case GPIO_DM_OUTPUT:
  47. pull = FPIOA_PULL_DOWN;
  48. dir = 1;
  49. break;
  50. default:
  51. configASSERT(!"GPIO drive mode is not supported.") break;
  52. }
  53. fpioa_set_io_pull(io_number, pull);
  54. set_gpio_bit(gpio->direction.u32, pin, dir);
  55. }
  56. gpio_pin_value_t gpio_get_pin(uint8_t pin)
  57. {
  58. configASSERT(pin < GPIO_MAX_PINNO);
  59. uint32_t dir = get_gpio_bit(gpio->direction.u32, pin);
  60. volatile uint32_t *reg = dir ? gpio->data_output.u32 : gpio->data_input.u32;
  61. return get_gpio_bit(reg, pin);
  62. }
  63. void gpio_set_pin(uint8_t pin, gpio_pin_value_t value)
  64. {
  65. configASSERT(pin < GPIO_MAX_PINNO);
  66. uint32_t dir = get_gpio_bit(gpio->direction.u32, pin);
  67. volatile uint32_t *reg = dir ? gpio->data_output.u32 : gpio->data_input.u32;
  68. configASSERT(dir == 1);
  69. set_gpio_bit(reg, pin, value);
  70. }