Sample code on how to pass an optional function pointer to a library and set a single pin to either InterruptIn or DigitalOut.

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers DemoClass.cpp Source File

DemoClass.cpp

00001 #include "DemoClass.h"
00002 
00003 InterruptIn *_irqpin;
00004 DigitalOut *_syncpin;
00005 
00006 // Depending on how the ctor is called, irqsync is either set to none, InterruptIn or DigitalOut
00007 DemoClass::DemoClass(PinName sda, PinName scl, PinName irqsync, void (*fptr)(void)) : _i2c(sda, scl)
00008 {
00009     // When both irqsync and fptr are nonzero, we use InterruptIn: irqsync pin is interrupt input and Attach ISR.
00010     if((irqsync != NC) && (fptr != NULL))
00011     {
00012         _irqpin = new InterruptIn(irqsync);             // Create InterruptIn pin
00013         _irqpin->fall(this, &DemoClass::_sensorISR);    // Attach falling interrupt to local ISR
00014         _fptr.attach(fptr);                             // Attach function pointer to user function
00015     }
00016     
00017     // When fptr is not defined, we use DigitalOut: irqsync pin is digital output.
00018     if((irqsync != NC) && (fptr == NULL))
00019     {
00020         _syncpin = new DigitalOut(irqsync);             // Create DigitalOut pin
00021         _syncpin->write(0);                             // Set pin to 0
00022     }
00023 }
00024 
00025 bool DemoClass::Status(void)
00026 {
00027     return (1);
00028 }
00029 
00030 void DemoClass::_sensorISR(void)
00031 {
00032    uint8_t statret = Status();        // Read a status register (eg : to clear an interrupt flag).
00033    _fptr.call();                      // Call the user-ISR
00034 }