// https://forum.arduino.cc/t/relays-stay-on-clicking-on-and-off/1389456/
byte button[] = {2, 3, 4, 5}; // reel spin buttons
#define SPIN 3 // spin button array element
byte relay[] = {8, 9, 10}; // relay pins, ON = spin, OFF = stop
bool readyToSpin, waitingForButton; // spin button activity
int pulsewidth = 100; // pulse width tells reels to spin
int reeldelay = 500, reelShort = 500, reelLong = 1500, waitShort = 1000, waitLong = 3000;
unsigned long startTime[3], stopTime[3]; // reel start and stop times
void setup() {
Serial.begin(115200);
randomSeed(analogRead(A0)); // increase pseudorandomness
for (int i = 0; i < 4; i++)
pinMode(button[i], INPUT_PULLUP); // configure button pins
for (int i = 0; i < 3; i++) {
pinMode(relay[i], OUTPUT); // configure relay pins
digitalWrite(relay[i], LOW); // reset relay pins
}
readyToSpin = true;
waitingForButton = true;
}
void loop() {
if (readyToSpin == true && waitingForButton == true) { // ask for spin button
waitingForButton = false; // reset flag
Serial.print("\nPress SPIN");
}
digitalRead(button[SPIN]); // read spin button
if ((readyToSpin == true) && (digitalRead(button[SPIN]) == LOW)) { // spin is ready, button is pressed
readyToSpin = false; // spin in progress, clear flag
startReels();
delay(random(waitShort, waitLong)); // time between spin and stop
stopReels();
timeDiff(); // show spin time difference
readyToSpin = true; // set flags
waitingForButton = true;
}
}
void reelControl(byte reel) { // send pulse to relays to start spin
digitalWrite(relay[reel], HIGH);
delay(pulsewidth);
digitalWrite(relay[reel], LOW);
}
void timeDiff() {
Serial.print(" TIME DIFF:");
for (int i = 0; i < 3; i++) {
padTime(stopTime[i] - startTime[i]);
Serial.print(stopTime[i] - startTime[i]);
}
Serial.println();
}
unsigned long padTime(unsigned long value) {
for (unsigned long i = 1000000; i > 0; i /= 10) {
if (value < i) Serial.print(" ");
}
}
void stopReels() {
Serial.print("\n STOP SPIN:");
for (int i = 0; i < 3; i++) {
delay(random(reelShort, reelLong)); // stagger reel stop
reelControl(i); // stop the reel
stopTime[i] = millis(); // store reel stop time
padTime(stopTime[i]);
Serial.print(stopTime[i]);
}
Serial.println();
}
void startReels() {
Serial.print("\nSTART SPIN:");
for (int i = 0; i < 3; i++) {
delay(reeldelay); // stagger reel start
reelControl(i); // pulse to start a reel
startTime[i] = millis(); // store reel start time
padTime(startTime[i]);
Serial.print(startTime[i]);
}
}STOP1
STOP2
STOP3
SPIN
REEL1
REEL2
REEL3
STOP
SPIN