|
| 1 | +#define START_PIN 5 |
| 2 | +#define BUTTON_PIN 3 |
| 3 | +#define CLOCK_PIN 2 |
| 4 | +#define STEPS 8 |
| 5 | + |
| 6 | +bool send_tick = false; |
| 7 | +int mode = 0; // 0 – forward, 1 – reverse, 2 – alternate |
| 8 | +bool forward = true; |
| 9 | +bool last_button_state = false; |
| 10 | +int current_step = -1; |
| 11 | + |
| 12 | +void onPress() { |
| 13 | + mode += 1; |
| 14 | + if (mode > 2) mode = 0; |
| 15 | +} |
| 16 | + |
| 17 | +void checkButton() { |
| 18 | + bool button_state = digitalRead(BUTTON_PIN) == LOW; |
| 19 | + |
| 20 | + if (last_button_state == button_state) return; |
| 21 | + last_button_state = button_state; |
| 22 | + |
| 23 | + if (button_state) { |
| 24 | + onPress(); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +void updateOuts() { |
| 29 | + if (current_step >= 0) { |
| 30 | + digitalWrite(current_step + START_PIN, LOW); |
| 31 | + } |
| 32 | + |
| 33 | + if (mode == 0) { |
| 34 | + forward = true; |
| 35 | + } else if (mode == 1) { |
| 36 | + forward = false; |
| 37 | + } |
| 38 | + |
| 39 | + if (forward) { |
| 40 | + current_step += 1; |
| 41 | + } else { |
| 42 | + current_step -= 1; |
| 43 | + } |
| 44 | + |
| 45 | + if (current_step < 0) { |
| 46 | + if (mode == 2) { |
| 47 | + forward = true; |
| 48 | + current_step = 0; |
| 49 | + } else { |
| 50 | + current_step = STEPS - 1; |
| 51 | + } |
| 52 | + } else if (current_step >= STEPS) { |
| 53 | + if (mode == 2) { |
| 54 | + forward = false; |
| 55 | + current_step -= 1; |
| 56 | + } else { |
| 57 | + current_step = 0; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + digitalWrite(current_step + START_PIN, HIGH); |
| 62 | +} |
| 63 | + |
| 64 | +void onClock() { |
| 65 | + send_tick = true; |
| 66 | +} |
| 67 | + |
| 68 | +void blinkOuts() { |
| 69 | + for (int i = 0; i < STEPS; i++) { |
| 70 | + digitalWrite(i + START_PIN, HIGH); |
| 71 | + delay(100); |
| 72 | + digitalWrite(i + START_PIN, LOW); |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +void setup() { |
| 77 | + for (int i = 0; i < STEPS; i++) { |
| 78 | + pinMode(i + START_PIN, OUTPUT); |
| 79 | + } |
| 80 | + |
| 81 | + pinMode(CLOCK_PIN, INPUT); |
| 82 | + pinMode(BUTTON_PIN, INPUT_PULLUP); |
| 83 | + |
| 84 | + attachInterrupt(digitalPinToInterrupt(CLOCK_PIN), onClock, RISING); |
| 85 | + |
| 86 | + blinkOuts(); |
| 87 | +} |
| 88 | + |
| 89 | +void loop() { |
| 90 | + checkButton(); |
| 91 | + |
| 92 | + if (!send_tick) return; |
| 93 | + |
| 94 | + send_tick = false; |
| 95 | + |
| 96 | + updateOuts(); |
| 97 | +} |
0 commit comments