cmd_gpio.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Control GPIO pins on the fly
  3. *
  4. * Copyright (c) 2008-2011 Analog Devices Inc.
  5. *
  6. * Licensed under the GPL-2 or later.
  7. */
  8. #include <common.h>
  9. #include <command.h>
  10. #include <asm/gpio.h>
  11. #ifndef name_to_gpio
  12. #define name_to_gpio(name) simple_strtoul(name, NULL, 10)
  13. #endif
  14. enum gpio_cmd {
  15. GPIO_INPUT,
  16. GPIO_SET,
  17. GPIO_CLEAR,
  18. GPIO_TOGGLE,
  19. };
  20. static int do_gpio(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
  21. {
  22. int gpio;
  23. enum gpio_cmd sub_cmd;
  24. ulong value;
  25. const char *str_cmd, *str_gpio;
  26. #ifdef gpio_status
  27. if (argc == 2 && !strcmp(argv[1], "status")) {
  28. gpio_status();
  29. return 0;
  30. }
  31. #endif
  32. if (argc != 3)
  33. show_usage:
  34. return CMD_RET_USAGE;
  35. str_cmd = argv[1];
  36. str_gpio = argv[2];
  37. /* parse the behavior */
  38. switch (*str_cmd) {
  39. case 'i': sub_cmd = GPIO_INPUT; break;
  40. case 's': sub_cmd = GPIO_SET; break;
  41. case 'c': sub_cmd = GPIO_CLEAR; break;
  42. case 't': sub_cmd = GPIO_TOGGLE; break;
  43. default: goto show_usage;
  44. }
  45. /* turn the gpio name into a gpio number */
  46. gpio = name_to_gpio(str_gpio);
  47. if (gpio < 0)
  48. goto show_usage;
  49. /* grab the pin before we tweak it */
  50. if (gpio_request(gpio, "cmd_gpio")) {
  51. printf("gpio: requesting pin %u failed\n", gpio);
  52. return -1;
  53. }
  54. /* finally, let's do it: set direction and exec command */
  55. if (sub_cmd == GPIO_INPUT) {
  56. gpio_direction_input(gpio);
  57. value = gpio_get_value(gpio);
  58. } else {
  59. switch (sub_cmd) {
  60. case GPIO_SET: value = 1; break;
  61. case GPIO_CLEAR: value = 0; break;
  62. case GPIO_TOGGLE: value = !gpio_get_value(gpio); break;
  63. default: goto show_usage;
  64. }
  65. gpio_direction_output(gpio, value);
  66. }
  67. printf("gpio: pin %s (gpio %i) value is %lu\n",
  68. str_gpio, gpio, value);
  69. gpio_free(gpio);
  70. return value;
  71. }
  72. U_BOOT_CMD(gpio, 3, 0, do_gpio,
  73. "input/set/clear/toggle gpio pins",
  74. "<input|set|clear|toggle> <pin>\n"
  75. " - input/set/clear/toggle the specified pin");