Teensy 3.2 digitalReadFast() Speed Test

Status
Not open for further replies.

Arctic_Eddie

Well-known member
On my sonar project using a Mega2560, I used direct port manipulation to create a gated burst generator for a 40KHz transmitter. For several reasons, I switched to Teensy 3.2 boards and now use digitalRead/WriteFast() instead of port manipulation, at least temporarily. I became curious this morning as to the time difference between the digitalRead() and digitalReadFast() functions. The code below shows the sketch and results of several different forms of reading a pin into a variable. Other clock speeds were tested for those not using the standard 72MHz speed.

Conclusions:
Since the digitalReadFast() function is considerably faster than the traditional digitalRead(), it can be used on all occasions without complicating the code with direct port reads.

Code:
// TeensyReadFastTest,ino  4/19/2016 by Arctic_Eddie
/* Results ******************************************************************************
 *  digitalRead() at 72MHz uses 250441 usec for 1e6 reads or about 0.25 usec per read
 *  digitalReadFast() at 72MHz uses 111321 usec for 1e6 reads or about 0.11 usec per read 
 *  digitalReadFast() at 96MHz uses 83455 usec for 1e6 reads or about 0.083 usec per read 
 *  digitalReadFast() at 96MHz(optimized) uses 62622 usec for 1e6 reads or about 0.063 usec per read 
*/  

#define     READ_PIN    6

uint32_t    startTime, stopTime;

void setup() 
{
    Serial.begin( 115200 );
    pinMode( READ_PIN, INPUT );
}

void loop() 
{
    uint8_t readval;
    startTime = micros();
    for( uint32_t i = 0; i < 1000000; i++ )
    {
        readval = digitalReadFast( READ_PIN );
    }
    stopTime = micros();
    Serial.println( stopTime - startTime );
}
 
As long as the argument you give to digitalRead/WriteFast is a constant you'll find it compiles to exactly the same sourcecode as if you were to use direct port manipulation
 
That's good to know. In my gated burst generator, I deal only with #defined pin names/numbers. Your comment will save me the time of converting to direct port manipulation with no speed improvement.

Thanks for the info.
 
Code:
Const uint32_t pinNumber = 4;
Works just as well. But yes Paul's done a good job to save us all the hassle of bitmasking
 
Status
Not open for further replies.
Back
Top