TVZ Mechatronics Team


Zagreb University of Applied Sciences, Professional Study in Mechatronics

You are viewing an older revision! See the latest version

Timers interrupts and tasks

In the following exercises you will learn to use Timer, Timeout, Ticker and InterruptIn classes from the standard mbed library. The program codes are from the following excellent book: Toulson, R. & Wilmshurst, T. (2012). Fast and Effective Embedded Systems Design - Applying the ARM mbed, Newnes, Oxford, ISBN: 9780080977683.

Exercise 1: Using the mbed Timer

Study the API documentation of the Timer class.

Examine the following code and try to figure out what will happen with the LEDs. Then test the program on an actual mbed and see if your predictions were correct.

#include "mbed.h"
Timer timer_fast;
Timer timer_slow;
DigitalOut ledA(LED1);
DigitalOut ledB(LED4);

void task_fast(void);
void task_slow(void);

int main() {
  timer_fast.start();
  timer_slow.start(); 
  while(true){
    if (timer_fast.read() > 0.2) {
      task_fast();
      timer_fast.reset();
    }
    if (timer_slow.read() > 1) {
      task_slow();
      timer_slow.reset();
    }
  }
}

void task_fast(void) {
  ledA = !ledA;
}
void task_slow(void) {
  ledB = !ledB;
}

Exercise 2: Using the mbed Timeout

Study the API documentation of the Timeout class.

Examine the following code and try to figure out what will happen with the LEDs. Then carefully test the program on the mbed and see if your predictions were correct.

#include "mbed.h"
Timeout response;
DigitalIn button (p14);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

void blink() {
  led2 = 1;
  wait(0.5);
  led2 = 0;
}

int main() {
  while(true) {
    if(button == 1){
      response.attach(&blink, 3.0);
      led3=1;
    } else {
      led3=0;
    }
    led1=!led1;     
    wait(0.2);
  }
}

Modify the above code by adding the second button, which will detach the blink() function from the response object if pressed.

Exercise 3: Using the mbed Ticker

Study the API documentation of the Ticker class.

Examine the following code and try to figure out what will happen with the LED. Test the program on the mbed and see if your predictions were correct.

#include "mbed.h"
void led_switch(void);
Ticker time_up;
DigitalOut myled(LED1);

void led_switch() {
    myled=!myled;       
}

int main(){
    time_up.attach(&led_switch, 0.2);
    while(true) {
        wait(1);
    }
}

Exercise 4: Using the mbed InterruptIn

Exercise 5: Switch debouncing

Exercise 6: Measuring distance with ultrasonic sensor HC-SR04


All wikipages