Arduino event system
2019-07-01Some time ago, when I was coding hardware project for school, which was model of a garage with gate, I was thinking about an easy way to control 2 things at the same time. Of course it is easy to use for-loop to control servo motor useful for opening gates, but you can only open/close 2 things at once only if they are the same. Unfortunately condition was to open gate and then garage 2 seconds later.
for (int i = 0; i <= 180; i++) {
servo.write(i);
}
Later that day, I thought about having a boolean variable which would have a state if a garage/gate is open or not. But still I had to thought about asynchronous opening of two things at once.
Then I realized that "void loop()" is similar to having a while loop so I removed for-loop and here we are. For each servo there is a state if it's closed or open and also it's current position which can be used for manipulating the final states.
void loop() {
if (!openedGate) {
servo.write(++i);
if (i > 180) {
openedGate = true;
}
}
if (!openedGarage) {
servo2.write(++j);
if (j > 180) {
openedGarage = true;
}
}
}
A small change in style and code can look really nice. Even C.
void loop() {
if (event == GATE_OPENING) {
if (!openedGate) {
servo.write(++i);
if (i > 180) {
openedGate = true;
} else if (i == 1) {
openingGateTime = millis();
}
}
if (!openedGarage && millis() - openingGateTime > 2000) {
servo2.write(++j);
if (j > 180) {
openedGarage = true;
}
}
}
}
Problem with this technique is that Arduino and it's MCU (ATMega328p) is pretty slow and only 8-bit (also it is underclocked for convinience sake of Arduino community), which is for most cases okay, but printing on LCD at the same time opening 2 gates can be pretty tough for this little boy (Can be achieved by heavy optimalization and little mind push).
Source code of this project is available here.