solenoid.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #include "gpio.h"
  21. bool solenoid_on = false;
  22. bool solenoid_buzzing = false;
  23. uint16_t solenoid_start = 0;
  24. uint8_t solenoid_dwell = SOLENOID_DEFAULT_DWELL;
  25. extern haptic_config_t haptic_config;
  26. void solenoid_buzz_on(void) { haptic_set_buzz(1); }
  27. void solenoid_buzz_off(void) { haptic_set_buzz(0); }
  28. void solenoid_set_buzz(int buzz) { haptic_set_buzz(buzz); }
  29. void solenoid_set_dwell(uint8_t dwell) { solenoid_dwell = dwell; }
  30. void solenoid_stop(void) {
  31. writePinLow(SOLENOID_PIN);
  32. solenoid_on = false;
  33. solenoid_buzzing = false;
  34. }
  35. void solenoid_fire(void) {
  36. if (!haptic_config.buzz && solenoid_on) return;
  37. if (haptic_config.buzz && solenoid_buzzing) return;
  38. solenoid_on = true;
  39. solenoid_buzzing = true;
  40. solenoid_start = timer_read();
  41. writePinHigh(SOLENOID_PIN);
  42. }
  43. void solenoid_check(void) {
  44. uint16_t elapsed = 0;
  45. if (!solenoid_on) return;
  46. elapsed = timer_elapsed(solenoid_start);
  47. // Check if it's time to finish this solenoid click cycle
  48. if (elapsed > solenoid_dwell) {
  49. solenoid_stop();
  50. return;
  51. }
  52. // Check whether to buzz the solenoid on and off
  53. if (haptic_config.buzz) {
  54. if ((elapsed % (SOLENOID_BUZZ_ACTUATED + SOLENOID_BUZZ_NONACTUATED)) < SOLENOID_BUZZ_ACTUATED) {
  55. if (!solenoid_buzzing) {
  56. solenoid_buzzing = true;
  57. writePinHigh(SOLENOID_PIN);
  58. }
  59. } else {
  60. if (solenoid_buzzing) {
  61. solenoid_buzzing = false;
  62. writePinLow(SOLENOID_PIN);
  63. }
  64. }
  65. }
  66. }
  67. void solenoid_setup(void) {
  68. setPinOutput(SOLENOID_PIN);
  69. solenoid_fire();
  70. }
  71. void solenoid_shutdown(void) { writePinLow(SOLENOID_PIN); }