Skip to content

Commit 38c9b9b

Browse files
author
Qinghao Shi
authored
Merge pull request #93 from maciejbocianski/move_interrupt_in_examples
add InterruptIn examples
2 parents f48c864 + d405e0f commit 38c9b9b

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# InterruptIn example
2+
3+
This example shows how to use InterruptIn to trigger a function call when a certain event happens. The example demonstrates calling a function on the rising edge of a button press. You can observe this through the counter value changing when the button is pressed.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* Copyright (c) 2017-2020 Arm Limited and affiliates.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
#include "mbed.h"
7+
8+
class Counter {
9+
public:
10+
Counter(PinName pin) : _interrupt(pin) // create the InterruptIn on the pin specified to Counter
11+
{
12+
_interrupt.rise(callback(this, &Counter::increment)); // attach increment function of this counter instance
13+
}
14+
15+
void increment()
16+
{
17+
_count++;
18+
}
19+
20+
int read()
21+
{
22+
return _count;
23+
}
24+
25+
private:
26+
InterruptIn _interrupt;
27+
volatile int _count;
28+
};
29+
30+
Counter counter(SW2);
31+
32+
int main()
33+
{
34+
while (1) {
35+
printf("Count so far: %d\n", counter.read());
36+
ThisThread::sleep_for(2000);
37+
}
38+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# InterruptIn example
2+
3+
This example shows how to use InterruptIn to trigger a function call when a certain event happens. The example demonstrates calling a function on the rising edge of a button press. You can observe this through LED4 blinking as the program runs. LED1 only changes when the button is pressed.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Copyright (c) 2017-2020 Arm Limited and affiliates.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
#include "mbed.h"
7+
8+
InterruptIn button(SW2);
9+
DigitalOut led(LED1);
10+
DigitalOut flash(LED4);
11+
12+
void flip()
13+
{
14+
led = !led;
15+
}
16+
17+
int main()
18+
{
19+
button.rise(&flip); // attach the address of the flip function to the rising edge
20+
while (1) { // wait around, interrupts will interrupt this!
21+
flash = !flash;
22+
ThisThread::sleep_for(250);
23+
}
24+
}

0 commit comments

Comments
 (0)