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.

69 lines
1.3KB

  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. void reset() {
  40. state = UNKNOWN;
  41. }
  42. };
  43. /** When triggered, holds a high value for a specified time before going low again */
  44. struct PulseGenerator {
  45. float time = 0.0;
  46. float pulseTime = 0.0;
  47. bool process(float deltaTime) {
  48. time += deltaTime;
  49. return time < pulseTime;
  50. }
  51. void trigger(float pulseTime) {
  52. // Keep the previous pulseTime if the existing pulse would be held longer than the currently requested one.
  53. if (time + pulseTime >= this->pulseTime) {
  54. time = 0.0;
  55. this->pulseTime = pulseTime;
  56. }
  57. }
  58. };
  59. } // namespace rack