Search Code
About FastIO

First published 12 Mar 2010, with 5 revisions since.
Last update: 12 Mar 2010.
View history

Last change message: N/A

Import this program

FastIO

Published 12 Mar 2010, by   user Igor Skochinsky   tag digitalOut, GPIO
Embed: (wiki syntax)

« Back to documentation index

You are viewing an out of date revision of FastIO! View latest revision

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 // Super-fast DigitalOut-like class for mbed
00003 //   by Igor Skochinsky
00004 
00005 // usage: FastOut<LED2> led2;
00006 // then use the same assignment operators as with DigitalOut
00007 template <PinName pin> class FastOut
00008 {
00009 // pin = LPC_GPIO0_BASE + port * 32 + bit
00010 // port = (pin - LPC_GPIO0_BASE) / 32
00011 // bit  = (pin - LPC_GPIO0_BASE) % 32
00012     
00013     // helper function to calculate the GPIO port definition for the pin
00014     // we rely on the fact that port structs are 0x20 bytes apart
00015     inline LPC_GPIO_TypeDef* portdef() { return (LPC_GPIO_TypeDef*)(LPC_GPIO0_BASE + ((pin - P0_0)/32)*0x20); };
00016 
00017     // helper function to calculate the mask for the pin's bit in the port
00018     inline uint32_t mask() { return 1UL<<((pin - LPC_GPIO0_BASE) % 32); };
00019 
00020 public:
00021     FastOut()
00022     {
00023         // set FIODIR bit to 1 (output)
00024         portdef()->FIODIR |= mask();
00025     }
00026     void write(int value)
00027     { 
00028         if ( value )
00029             portdef()->FIOSET = mask();
00030         else
00031             portdef()->FIOCLR = mask();
00032     } 
00033     int read()
00034     {
00035         return (portdef()->FIOPIN) & mask() != 0;
00036     }
00037     FastOut& operator= (int value) { write(value); return *this; };
00038     FastOut& operator= (FastOut& rhs) { return write(rhs.read()); };
00039     operator int() { return read(); };
00040 };
00041 
00042 DigitalOut led1(LED1);
00043 FastOut<LED2> led2;
00044 
00045 Timer t;
00046 #define LOOPS 100000000
00047 int main() {
00048     int value = 0;
00049     int count = LOOPS;
00050     t.start();
00051     while ( count -- )
00052     {
00053         led1.write(value);
00054         value = 1-value;
00055     }
00056     t.stop();
00057     printf("DigitalOut: %f seconds (%d ns per iteration).\n", t.read(), t.read_us()/(LOOPS/1000));
00058     count = LOOPS;
00059     t.reset();
00060     t.start();
00061     while ( count -- )
00062     {
00063         led2 = value;
00064         value = 1-value;
00065     }
00066     t.stop();
00067     printf("FastOut: %f seconds (%d ns per iteration).\n", t.read(), t.read_us()/(LOOPS/1000));
00068 }