Guest User

refactor gpio

a guest
Jan 22nd, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.74 KB | Source Code | 0 0
  1. struct GPIODescriptor {
  2.   GPIO &gpio;
  3.   const GPIOHandler handler;
  4.   const char *name;
  5. };
  6.  
  7. const unsigned int number_of_gpios = 5;
  8. const GPIODescriptor gpio_descriptors[number_of_gpios] = {
  9.     GPIODescriptor{my_gpios[0], joy_down_irq_handler, "joy_down"},
  10.     GPIODescriptor{my_gpios[1], joy_left_irq_handler, "joy_left"},
  11.     GPIODescriptor{my_gpios[2], joy_up_irq_handler, "joy_up"},
  12.     GPIODescriptor{my_gpios[3], joy_button_irq_handler, "joy_button"},
  13.     GPIODescriptor{my_gpios[4], joy_right_irq_handler, "joy_right"},
  14. };
  15.  
  16. bool request_threaded_irq(const GPIODescriptor &gpio_descriptor) {
  17.   const auto irq = gpio_to_irq(gpio_descriptor.gpio);
  18.   const auto error_code = request_threaded_irq(
  19.       irq, gpio_descriptor.handler, NULL,
  20.       IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, gpio_descriptor.name, NULL);
  21.   const bool was_successful = error_code >= 0;
  22.   return was_successful;
  23. }
  24.  
  25. unsigned int try_to_initialize_gpios() {
  26.   unsigned int successfully_initialized_gpios = 0;
  27.   for (unsigned int index = 0; index < number_of_gpios; index++) {
  28.     const auto was_successful = request_threaded_irq(gpio_descriptors[index]);
  29.     if (not was_successful)
  30.       break;
  31.     else
  32.       successfully_initialized_gpios = index + 1;
  33.   }
  34.   return successfully_initialized_gpios;
  35. }
  36.  
  37. void free_gpios(unsigned int up_to_gpio) {
  38.   for (unsigned int index = 0; index < up_to_gpio; index++) {
  39.     const auto irq = gpio_to_irq(gpio_descriptors[index].gpio);
  40.     free_irq(irq, NULL);
  41.   }
  42. }
  43.  
  44. int initialize_gpios() {
  45.   auto successfully_initialized_gpios = try_to_initialize_gpios();
  46.   if (successfully_initialized_gpios != number_of_gpios) {
  47.     free_gpios(successfully_initialized_gpios);
  48.     irq_error();
  49.     return -1;
  50.   }
  51.   return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment