solenoid.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright 2018 mtdjr - modified by ishtob
  2. * Driver for solenoid written for QMK
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "timer.h"
  18. #include "solenoid.h"
  19. #include "haptic.h"
  20. bool solenoid_on = false;
  21. bool solenoid_buzzing = false;
  22. uint16_t solenoid_start = 0;
  23. uint8_t solenoid_dwell = SOLENOID_DEFAULT_DWELL;
  24. extern haptic_config_t haptic_config;
  25. void solenoid_buzz_on(void) { haptic_set_buzz(1); }
  26. void solenoid_buzz_off(void) { haptic_set_buzz(0); }
  27. void solenoid_set_buzz(int buzz) { haptic_set_buzz(buzz); }
  28. void solenoid_set_dwell(uint8_t dwell) { solenoid_dwell = dwell; }
  29. void solenoid_stop(void) {
  30. writePinLow(SOLENOID_PIN);
  31. solenoid_on = false;
  32. solenoid_buzzing = false;
  33. }
  34. void solenoid_fire(void) {
  35. if (!haptic_config.buzz && solenoid_on) return;
  36. if (haptic_config.buzz && solenoid_buzzing) return;
  37. solenoid_on = true;
  38. solenoid_buzzing = true;
  39. solenoid_start = timer_read();
  40. writePinHigh(SOLENOID_PIN);
  41. }
  42. void solenoid_check(void) {
  43. uint16_t elapsed = 0;
  44. if (!solenoid_on) return;
  45. elapsed = timer_elapsed(solenoid_start);
  46. // Check if it's time to finish this solenoid click cycle
  47. if (elapsed > solenoid_dwell) {
  48. solenoid_stop();
  49. return;
  50. }
  51. // Check whether to buzz the solenoid on and off
  52. if (haptic_config.buzz) {
  53. if ((elapsed % (SOLENOID_BUZZ_ACTUATED + SOLENOID_BUZZ_NONACTUATED)) < SOLENOID_BUZZ_ACTUATED) {
  54. if (!solenoid_buzzing) {
  55. solenoid_buzzing = true;
  56. writePinHigh(SOLENOID_PIN);
  57. }
  58. } else {
  59. if (solenoid_buzzing) {
  60. solenoid_buzzing = false;
  61. writePinLow(SOLENOID_PIN);
  62. }
  63. }
  64. }
  65. }
  66. void solenoid_setup(void) {
  67. setPinOutput(SOLENOID_PIN);
  68. solenoid_fire();
  69. }
  70. void solenoid_shutdown(void) { writePinLow(SOLENOID_PIN); }