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.
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 );
}