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

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* 
00002 
00003 2645_InterruptIn
00004 
00005 Sample code from ELEC2645 
00006 
00007 Demonstrates how to use InterruptIn to generate an event-triggered interrupt
00008 
00009 (c) Craig A. Evans, University of Leeds, Dec 2020
00010 
00011 */ 
00012 
00013 #include "mbed.h"
00014 
00015 // Create objects for button A and LED1
00016 InterruptIn buttonA(p29);
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_buttonA_flag = 0;
00022 
00023 // function prototypes
00024 void buttonA_isr();
00025 
00026 int main()
00027 {
00028     // Button A has a pull-down resistor, so the pin will be at 0 V by default
00029     // and rise to 3.3 V when pressed. We therefore need to look for a rising edge
00030     // on the pin to fire the interrupt
00031     buttonA.rise(&buttonA_isr);
00032     // since Button A has an external pull-down, we should disable to internal pull-down
00033     // resistor that is enabled by default using InterruptIn
00034     buttonA.mode(PullNone);
00035 
00036     while (1) {
00037 
00038         // check if flag i.e. interrupt has occured
00039         if (g_buttonA_flag) {
00040             g_buttonA_flag = 0;  // if it has, clear the flag
00041 
00042             // send message over serial port - can observe in CoolTerm etc.
00043             printf("Execute task \n");
00044             // DO TASK HERE
00045         }
00046 
00047         // put the MCU to sleep until an interrupt wakes it up
00048         sleep();
00049 
00050     }
00051 }
00052 
00053 // Button A event-triggered interrupt
00054 void buttonA_isr()
00055 {
00056     g_buttonA_flag = 1;   // set flag in ISR
00057 }