beep.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #include "gpio.h"
  2. #include "timer.h"
  3. #include "elog.h"
  4. #include "beep.h"
  5. #include <stdio.h>
  6. #include <sys/time.h>
  7. #if 1
  8. #define LOGD log_d
  9. #define LOGE log_e
  10. #else
  11. #define LOGD printf
  12. #define LOGE printf
  13. #endif
  14. #define BEEP_GPIO 103 //PD7=96+7
  15. #define BEEP_ON_LEVEL 1
  16. #define BEEP_OFF_LEVEL 0
  17. static beep_para_t beep_para[BEEP_MODE_MAX]={
  18. {1000, 1000, 5}, //BEEP_MODE_WARN
  19. {500, 500, 10}, //BEEP_MODE_ERROR
  20. {200, 200, 25}, //BEEP_MODE_FAULT
  21. {50, 50, -1}, //BEEP_MODE_FATAL
  22. };
  23. typedef struct {
  24. int io;
  25. int tmr;
  26. uint32_t cnt;
  27. beep_para_t para;
  28. int stop_level;
  29. }beep_handle_t;
  30. static beep_handle_t bpHandle={0};
  31. static void beep_handler(void *arg, int last)
  32. {
  33. beep_handle_t *h=(beep_handle_t*)arg;
  34. if(h->para.on_ms>0 && h->para.off_ms>0) {
  35. h->cnt++;
  36. if(h->cnt%2) {
  37. gpio_set(h->io, BEEP_OFF_LEVEL);
  38. }
  39. else {
  40. gpio_set(h->io, BEEP_ON_LEVEL);
  41. }
  42. }
  43. if(last) {
  44. timer_stop(h->tmr);
  45. gpio_set(h->io, BEEP_OFF_LEVEL);
  46. }
  47. }
  48. /////////////////////////////////////////////
  49. int beep_init(void)
  50. {
  51. beep_handle_t *h=&bpHandle;
  52. h->io = gpio_init(BEEP_GPIO, GPIO_OUT);
  53. h->tmr = timer_init();
  54. gpio_set(h->io, BEEP_OFF_LEVEL);
  55. h->tmr = -1;
  56. //beep_set(BEEP_MODE_FATAL);
  57. return 0;
  58. }
  59. int beep_deinit(void)
  60. {
  61. beep_handle_t *h=&bpHandle;
  62. gpio_deinit(h->io);
  63. timer_deinit(h->tmr);
  64. h->io = -1;
  65. h->tmr = -1;
  66. return 0;
  67. }
  68. int beep_set(int mode)
  69. {
  70. beep_handle_t *h=&bpHandle;
  71. return beep_set_ex(&beep_para[mode]);
  72. }
  73. int beep_set_ex(beep_para_t *para)
  74. {
  75. int r = 0;
  76. beep_handle_t *h=&bpHandle;
  77. if(!para || (para->on_ms<=0 && para->off_ms<=0) || para->times==0) {
  78. return -1;
  79. }
  80. h->cnt = 0;
  81. h->para = *para;
  82. if(h->para.on_ms>0) {
  83. gpio_set(h->io, BEEP_ON_LEVEL);
  84. if(h->para.off_ms>0) {
  85. h->para.times *= 2;
  86. }
  87. else {
  88. h->para.on_ms *= h->para.times;
  89. h->para.times = 1;
  90. }
  91. r = timer_start(h->tmr, h->para.on_ms, h->para.times, beep_handler, h);
  92. }
  93. else {
  94. gpio_set(h->io, BEEP_OFF_LEVEL);
  95. if(h->para.off_ms>0) {
  96. h->para.off_ms *= h->para.times;
  97. h->para.times = 1;
  98. r = timer_start(h->tmr, h->para.off_ms, h->para.times, beep_handler, h);
  99. }
  100. }
  101. return r;
  102. }