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.

digital.hpp 1.4KB

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