You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.4KB

  1. #pragma once
  2. #include "math.hpp"
  3. namespace rack {
  4. /** Turns high when value reaches the high threshold, turns low when value reaches the low threshold */
  5. struct SchmittTrigger {
  6. // UNKNOWN is used to represent a stable state when the previous state is not yet set
  7. enum {UNKNOWN, LOW, HIGH} state = UNKNOWN;
  8. float low = 0.0;
  9. float high = 1.0;
  10. void setThresholds(float low, float high) {
  11. this->low = low;
  12. this->high = high;
  13. }
  14. /** Returns true if triggered */
  15. bool process(float in) {
  16. switch (state) {
  17. case LOW:
  18. if (in >= high) {
  19. state = HIGH;
  20. return true;
  21. }
  22. break;
  23. case HIGH:
  24. if (in <= low) {
  25. state = LOW;
  26. }
  27. break;
  28. default:
  29. if (in >= high) {
  30. state = HIGH;
  31. }
  32. else if (in <= low) {
  33. state = LOW;
  34. }
  35. break;
  36. }
  37. return false;
  38. }
  39. bool isHigh() {
  40. return state == HIGH;
  41. }
  42. void reset() {
  43. state = UNKNOWN;
  44. }
  45. };
  46. /** When triggered, holds a high value for a specified time before going low again */
  47. struct PulseGenerator {
  48. float time = 0.0;
  49. float pulseTime = 0.0;
  50. bool process(float deltaTime) {
  51. time += deltaTime;
  52. return time < pulseTime;
  53. }
  54. void trigger(float pulseTime) {
  55. // Keep the previous pulseTime if the existing pulse would be held longer than the currently requested one.
  56. if (time + pulseTime >= this->pulseTime) {
  57. time = 0.0;
  58. this->pulseTime = pulseTime;
  59. }
  60. }
  61. };
  62. } // namespace rack