NSWI170 Computer Systems
5th practicals
Your next assignment: Stopwatch
- Show all digits on display simultaneously - multiplexing (switch fast between individual positions)
- Think about how to use the millis function correctly
void loop() {
if (millis() - lastTime >= TIME_STEP) {
// extensive computation that
// takes a few miliseconds
lastTime = millis();
}
}
Reminder: Do not depend on global variables if not necessary
- Pass values as arguments - your functions will be more robust and reusable
displayNumber();
displayNumber(counter);
Encapsulation
See https://www.ksi.mff.cuni.cz/teaching/nswi170-web/pages/labs/coding/5-encapsulation
Logical parts of the application must be grouped together (e.g., using structures). Communication between parts must be conducted solely through a well-defined interface (functions/methods).
I. Encapsulate Input/output units
- Button - debounce, long press, double-click
- Display - show the number
- Led strip - binary representation
- Serial communication - wrapper to easily send data
- Buzzer - play a specific sound
- Multiple button control - both pressed action
- Keyboard - handle typing of sequences
Example use
void setup() {
incrementButton.setup();
display.setup();
}
void loop() {
incrementButton.handle();
display.handle();
if (incrementButton.wasPressed()) {
coutnter++;
display.updateValue(counter);
}
}
You don't know how button or display works. You don't care. There is an easy interface to check whether the button was pressed (whatever that means) and to display a specific number.
II. Encapsulate program logic
- Counter - increment counter, handle overflow, handle I/O units
- Stopwatch - measure time, handle I/O units
- Game controller - controls the game flow
Example use
void setup() {
musicPlayer.setup();
counter.setup();
}
void loop() {
// Plays sound
musicPlayer.handle();
// Handles buttons and the counter
counter.handle();
}
musicPlayer and counter are completely independent of each other. You only choose what will be executed. counter.handle() handles the button and the display internally.
Alternative example
void setup() {
musicPlayer.setup();
counter.setup();
incrementButton.setup();
display.setup();
}
void loop() {
// Plays sound
musicPlayer.handle();
// Handles buttons and the counter
incrementButton.handle();
display.handle();
if (incrementButton.wasPressed()) {
counter.incrementValue();
display.updateValue(counter.getValue());
}
}
counter class only handles the counting, the rest is done externally
Music player example
NSWI170 - 5th practicals
By Štěpán Stenchlák
NSWI170 - 5th practicals
- 386