The input parameters / configuration is:
// Program parameters
constexpr int animationDurationMs = 300;
constexpr int ledsPins = {led1_pin, led2_pin, led3_pin, led4_pin};
The rest is calculated:
// Leds count
constexpr int ledsCount = sizeof(ledsPins) / sizeof(ledsPins[0])
// Last LED
ledsPins[ledsCount - 1]
// Total animation duration
(ledsCount * 2 - 2) * animationDurationMs
The program should not break if we change or add new values.
The size should not be hard-coded.
Example scenario: Extend 2nd homework with playing twinkle twinkle little star on speaker
void setup() {
setupLedAnimation();
setupMusicPlayer();
}
void loop() {
updateLedAnimation();
updateMusicPlayer();
}
unsigned long animationDelayMs = 300;
unsigned long lastTimestamp = 0;
void setup() {
lastTimestamp = millis();
}
void loop() {
auto currentTimestamp = millis();
if (currentTimestamp >= lastTimestamp + animationDelayMs) {
// Do something
lastTimestamp = currentTimestamp;
}
}
Write a function that takes an integer and changes the LED states according to its lower 4 bits.
Create a clock that increments every second. Do not use delay().
#include "funshield.h"
void setup() {
pinMode(button1_pin, INPUT);
}
void loop() {
bool isPressed = !digitalRead(button1_pin);
...
}
Increment if the button is pressed.
What does it mean to press the button?
What if you hold it?
Increment as soon as the button is pressed and then in regular intervals.
Instead of repeating, use:
Repeated code is hard to maintain because you must fix all its copies. It is difficult to read.
See the ASCII Table example for inspiration.
File > Examples > 04. Communication
Find out how many times per second the loop function is called. Then try to insert some computationally demanding code and recheck the loops per second.
class Button {
private:
bool down;
int pin;
public:
bool isDown() {
return down;
}
Button(int _pin) {
pin = _pin;
}
};
Button button(10);
button.isDown()