Craig Evans / Mbed OS ELEC2645_TimeTriggeredInterrupt_2021
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* 
00002 
00003 2645_Ticker
00004 
00005 Sample code from ELEC2645
00006 
00007 Demonstrates how to use a ticker to generate a periodic timer interrupt
00008 
00009 (c) Craig A. Evans, University of Leeds, Jan 2016
00010 
00011 */ 
00012 
00013 #include "mbed.h"
00014 
00015 // Create objects for ticker and red LED
00016 Ticker ticker;
00017 DigitalOut led(LED1);
00018 
00019 // flag - must be volatile as changes within ISR
00020 // g_ prefix makes it easier to distinguish it as global
00021 volatile int g_timer_flag = 0;
00022 
00023 // function prototypes
00024 void timer_isr();
00025 
00026 int main()
00027 {
00028     // set-up the ticker so that the ISR it is called every 0.5 seconds
00029     ticker.attach(&timer_isr,0.5);
00030     
00031     while (1) {
00032 
00033         // check if flag is set i.e. interrupt has occured
00034         if (g_timer_flag) {
00035             g_timer_flag = 0;  // if it has, clear the flag
00036             printf("Tick \n");
00037             // DO TASK HERE
00038         }
00039 
00040         // put the MCU to sleep until an interrupt wakes it up
00041         sleep();
00042 
00043     }
00044 }
00045 
00046 // time-triggered interrupt
00047 void timer_isr()
00048 {
00049     g_timer_flag = 1;   // set flag in ISR
00050 }