Skip to content

Session 11: Subroutines

Exercise: Review Code

Look at the code and find repetitions.

void loop() {
    set_led_matrix_pixel(y, x, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y + 1, x, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y, x + 1, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y, x + 2, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y, x + 3, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y + 1, x + 3, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y - 1, x + 1, HIGH);
    show_led_matrix();
    delay(50);
    set_led_matrix_pixel(y - 1, x + 2, HIGH);
    show_led_matrix();
    delay(50);
}

Simplification

Simplified Code
void showAndDelay(){
    show_led_matrix();
    delay(50);
}

void loop() {
    set_led_matrix_pixel(y, x, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y + 1, x, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y, x + 1, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y, x + 2, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y, x + 3, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y + 1, x + 3, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y - 1, x + 1, HIGH);
    showAndDelay();
    set_led_matrix_pixel(y - 1, x + 2, HIGH);
    showAndDelay();
}

Semantic Functions

// ...

int command = BTN_0;
void getCommand(){ // input: IR remote
    if(check_ir_button_pressed()){
        command = get_ir_button();
    }
}

void showAnimation(){ // output: matrix
    clear_led_matrix();
    for(int x=0; x<8; x++){
        set_led_matrix_pixel(x, 5, HIGH);
        delay(100);
    }
    show_led_matrix();
}

void showLight(){ // output: RGB LEDs
    set_led_color(LED_1, command, 0, 0);
    delay(500);
    set_led_color(LED_1, 0, command, 0);
    delay(500);
    set_led_color(LED_1, 0, 0, command);
    delay(500);
}

void loop(){
    getCommand();
    showAnimation();
    showLight();
}

Exercise: Practical

  1. Separate your code into semantic functions.
  2. Add another functionality to your robot (e.g. LEDs, servos, ...)