Igor Skochinsky
/
FastIO
Fast GPIO using C++ templates. Now with port I/O.
Diff: main.cpp
- Revision:
- 0:f1e54c45ccaf
- Child:
- 1:8064f8b8cf82
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Mar 12 10:12:32 2010 +0000 @@ -0,0 +1,68 @@ +#include "mbed.h" +// Super-fast DigitalOut-like class for mbed +// by Igor Skochinsky + +// usage: FastOut<LED2> led2; +// then use the same assignment operators as with DigitalOut +template <PinName pin> class FastOut +{ +// pin = LPC_GPIO0_BASE + port * 32 + bit +// port = (pin - LPC_GPIO0_BASE) / 32 +// bit = (pin - LPC_GPIO0_BASE) % 32 + + // helper function to calculate the GPIO port definition for the pin + // we rely on the fact that port structs are 0x20 bytes apart + inline LPC_GPIO_TypeDef* portdef() { return (LPC_GPIO_TypeDef*)(LPC_GPIO0_BASE + ((pin - P0_0)/32)*0x20); }; + + // helper function to calculate the mask for the pin's bit in the port + inline uint32_t mask() { return 1UL<<((pin - LPC_GPIO0_BASE) % 32); }; + +public: + FastOut() + { + // set FIODIR bit to 1 (output) + portdef()->FIODIR |= mask(); + } + void write(int value) + { + if ( value ) + portdef()->FIOSET = mask(); + else + portdef()->FIOCLR = mask(); + } + int read() + { + return (portdef()->FIOPIN) & mask() != 0; + } + FastOut& operator= (int value) { write(value); return *this; }; + FastOut& operator= (FastOut& rhs) { return write(rhs.read()); }; + operator int() { return read(); }; +}; + +DigitalOut led1(LED1); +FastOut<LED2> led2; + +Timer t; +#define LOOPS 100000000 +int main() { + int value = 0; + int count = LOOPS; + t.start(); + while ( count -- ) + { + led1.write(value); + value = 1-value; + } + t.stop(); + printf("DigitalOut: %f seconds (%d ns per iteration).\n", t.read(), t.read_us()/(LOOPS/1000)); + count = LOOPS; + t.reset(); + t.start(); + while ( count -- ) + { + led2 = value; + value = 1-value; + } + t.stop(); + printf("FastOut: %f seconds (%d ns per iteration).\n", t.read(), t.read_us()/(LOOPS/1000)); +}