bpi.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*Author: Sebastian Vendt, version 1.0 (2019)
  2. * compile with gcc -Wall -o bpi -lwirinigPi bpi.c
  3. * Usage: call ./bpi -p 10 in your bash script to wait for the event on pin 10
  4. * the command will terminate once the event occured
  5. */
  6. #include <unistd.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <getopt.h>
  10. #include <wiringPi.h>
  11. extern int optopt;
  12. void printUsage(char* command);
  13. void isr();
  14. int verbose = FALSE;
  15. int main(int argc, char* argv[]){
  16. if(argc < 2){
  17. fprintf(stderr, "%s requires at least option -p\n", argv[0]);
  18. printUsage(argv[0]);
  19. exit(EXIT_FAILURE);
  20. }
  21. int pin = -1;
  22. int opt;
  23. int edge = 1;
  24. wiringPiSetup();
  25. while((opt = getopt(argc, argv, ":p:ve:")) != -1){
  26. switch(opt){
  27. case 'p':
  28. pin = atoi(optarg);
  29. break;
  30. case 'v':
  31. verbose = TRUE;
  32. break;
  33. case 'e':
  34. edge = atoi(optarg);
  35. break;
  36. case '?':
  37. fprintf(stderr, "unknown option\n");
  38. printUsage(argv[0]);
  39. exit(EXIT_FAILURE);
  40. break;
  41. case ':':
  42. fprintf(stderr, "option %c needs a value\n", optopt);
  43. printUsage(argv[0]);
  44. exit(EXIT_FAILURE);
  45. break;
  46. }
  47. }
  48. if(pin == -1) {
  49. fprintf(stderr, "option -p requried\n");
  50. printUsage(argv[0]);
  51. exit(EXIT_FAILURE);
  52. }
  53. if(!(edge == 1 || edge == 2 || edge == 3)) {
  54. fprintf(stderr, "option -e only takes values 1, 2 or 3\n");
  55. printUsage(argv[0]);
  56. exit(EXIT_FAILURE);
  57. }
  58. if(verbose) printf("Registering interrupt for pin %d with edge %d\n", pin, edge);
  59. pinMode(pin, INPUT);
  60. if(wiringPiISR(pin, edge, &isr) < 0) {
  61. fprintf(stderr, "Failed registering interrupt for pin %d with edge %d\n", pin, edge);
  62. exit(EXIT_FAILURE);
  63. }
  64. pause();
  65. fprintf(stderr, "could not suspend execution\n");
  66. exit(EXIT_FAILURE);
  67. }
  68. void printUsage(char* command){
  69. fprintf(stderr, "Usage: %s -p [-v] [-e]\n", command);
  70. fprintf(stderr, "-p BCM pin number (required)\n");
  71. fprintf(stderr, "-v be verbose\n");
  72. fprintf(stderr, "-e interrupt mode 1:INT_EDGE_FALLING (default), 2:INT_EDGE_RISING, 3:INT_EDGE_BOTH\n");
  73. }
  74. void isr(){
  75. if(verbose) printf("Triggered!\n");
  76. exit(EXIT_SUCCESS);
  77. }