Sample code that demonstrates generating a periodic timer interrupt on the K64F

Dependencies:   mbed

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 red_led(LED_RED);
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     // the on-board RGB LED is a common anode - writing a 1 to the pin will turn the LED OFF
00031     red_led = 1;
00032 
00033     while (1) {
00034 
00035         // check if flag is set i.e. interrupt has occured
00036         if (g_timer_flag) {
00037             g_timer_flag = 0;  // if it has, clear the flag
00038 
00039             // send message over serial port - can observe in CoolTerm etc.
00040             printf("Tick \n");
00041             // DO TASK HERE
00042     
00043         }
00044 
00045         // put the MCU to sleep until an interrupt wakes it up
00046         sleep();
00047 
00048     }
00049 }
00050 
00051 // time-triggered interrupt
00052 void timer_isr()
00053 {
00054     g_timer_flag = 1;   // set flag in ISR
00055 }