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

  1. Button - debounce, long press, double-click
  2. Display - show the number
  3. Led strip - binary representation
  4. Serial communication - wrapper to easily send data
  5. Buzzer - play a specific sound
  6. Multiple button control - both pressed action
  7. 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

  1. Counter - increment counter, handle overflow, handle I/O units
  2. Stopwatch - measure time, handle I/O units
  3. 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

Made with Slides.com