Hello
I did it again in C++. Missing the part to read and to work on buttons. But I think these actions can be simple added to this given frame work by yourself. And if not don´t hesitate to ask.
// BLOCK COMMENT
// ATTENTION: This Sketch contains elements of C++.
// https://www.learncpp.com/cpp-tutorial/
// https://forum.arduino.cc/t/2-buttons-and-8-relays-or-more/906777
#define ProjectName "2 buttons and 8 relays(or more)"
// CONSTANT DEFINITION
// you may need to change these constants to your hardware and needs.
constexpr byte Input_[] {A0, A1}; // portPin o---|button|---GND
constexpr byte Output_[] {2, 3, 4, 5, 6, 7, 8, 9}; // portPin o---|220|---|LED|---GND
// VARIABLE DECLARATION AND DEFINTION
enum {One, Two, Three, Four, Five, Six, Seven, Eight};
unsigned long currentTime;
struct TIMER {
unsigned long duration;
bool repeat_;
bool control_;
unsigned long stamp;
};
struct BLOCK {
byte name_;
byte pin;
TIMER time_;
} blocks [] = {
{One, Output_[One], 1000, false, true, 0},
{Two, Output_[Two], 1000, false, false, 0},
{Three, Output_[Three], 1000, false, false, 0},
{Four, Output_[Four], 1000, false, false, 0},
{Five, Output_[Five], 1000, true, false, 0},
{Six, Output_[Six], 1000, true, false, 0},
{Seven, Output_[Seven], 1000, true, false, 0},
{Eight, Output_[Eight], 1000, true, false, 0},
};
// FUNCTIONS
bool checkTimer(TIMER & time_) { // generic time handler using TIME struct
if (currentTime - time_.stamp >= time_.duration && time_.control_) {
if (time_.repeat_) time_.stamp = currentTime;
else time_.control_ = false;
return true;
} else return false;
}
void setup() {
Serial.begin(9600);
Serial.println(F("."));
Serial.print(F("File : ")), Serial.println(__FILE__);
Serial.print(F("Date : ")), Serial.println(__DATE__);
Serial.print(F("Project: ")), Serial.println(ProjectName);
pinMode (LED_BUILTIN, OUTPUT);
for (auto Input : Input_) pinMode(Input, INPUT_PULLUP);
for (auto Output : Output_) pinMode(Output, OUTPUT);
// check outputs
for (auto Output : Output_) digitalWrite(Output, HIGH);
delay(1000);
for (auto Output : Output_) digitalWrite(Output, LOW);
}
void loop () {
currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
for (auto &block : blocks) {
if (checkTimer(block.time_))
switch (block.name_) {
case One ... Three:
block.time_.control_ = false;
digitalWrite(block.pin, HIGH);
blocks[block.name_ + 1].time_.control_ = true;
blocks[block.name_ + 1].time_.stamp = currentTime;
break;
case Four:
for (unsigned int n = Five; n < (sizeof(blocks) / sizeof(blocks[0])); n++) {
blocks[n].time_.control_ = true;
blocks[n].time_.stamp = currentTime;
blocks[n].time_.duration = random(200, 1000);
}
block.time_.control_ = false;
digitalWrite(block.pin, HIGH);
break;
case Five ... Eight:
block.time_.duration = random(200, 1000);
digitalWrite(block.pin, !digitalRead(block.pin));
break;
}
}
}
Have a nice day and enjoy coding in C++.