InterruptIn

Use the InterruptIn class to trigger an event when a digital input pin changes.

API

Public Member Functions

 InterruptIn (PinName pin)
int read ()
 operator int ()
void rise (Callback< void()> func)
template<typename T , typename M >
void rise (T *obj, M method)
void fall (Callback< void()> func)
template<typename T , typename M >
void fall (T *obj, M method)
void mode (PinMode pull)
void enable_irq ()
void disable_irq ()

Additional Inherited Members

- Protected Member Functions inherited from mbed::NonCopyable< InterruptIn >
 NonCopyable ()
 ~NonCopyable ()

Warnings:

  • No blocking code in ISR: avoid any call to wait, infinite while loop or blocking calls in general.

  • No printf, malloc or new in ISR: avoid any call to bulky library functions. In particular, certain library functions (such as printf, malloc and new) are non re-entrant, and their behavior could be corrupted when called from an ISR.

Hello World!

 


/* mbed Example Program
 * Copyright (c) 2006-2014 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "mbed.h"
 
InterruptIn button(SW2);
DigitalOut led(LED1);
DigitalOut flash(LED4);
 
void flip() {
    led = !led;
}
 
int main() {
    button.rise(&flip);  // attach the address of the flip function to the rising edge
    while(1) {           // wait around, interrupts will interrupt this!
        flash = !flash;
        wait(0.25);
    }
}

Example

Try the following example to count rising edges on a pin.

 


#include "mbed.h"

class Counter {
public:
    Counter(PinName pin) : _interrupt(pin) {        // create the InterruptIn on the pin specified to Counter
        _interrupt.rise(callback(this, &Counter::increment)); // attach increment function of this counter instance
    }

    void increment() {
        _count++;
    }

    int read() {
        return _count;
    }

private:
    InterruptIn _interrupt;
    volatile int _count;
};

Counter counter(SW2);

int main() {
    while(1) {
        printf("Count so far: %d\n", counter.read());
        wait(2);
    }
}

To read an input, see DigitalIn.

For timer-based interrupts, see Ticker (repeating interrupt) and Timeout (one-time interrupt).