// http://arduino.cc/forum/index.php/topic,56396.0.html
// and
// http://arduino.cc/forum/index.php/topic,74895.0.html
/*
Sketch to demonstrate how to decrease time of analog read.
it shortens the delay by manipulating registers and reducing the prescale
timer value from 128 to 16;
Note Serial Speed! Change to suit yourself!
Sample Sketch From Arduino Cookbook by Margolis (O'Reilly Press)
Modified by Willr March24, 2011
Tested on Mega2560 Arduino board with an MA7361 Z output hooked to
Sensor 5
*/
// CHANGE Sensor Pin to suit yourself...
const int sensorPin = 5;
// Change number of entries to a value divisible by 100 only
const int numberOfEntries = 100;
unsigned long microseconds;
unsigned long duration1;
unsigned long duration2;
int results[numberOfEntries];
void setup()
{
Serial.begin(9600); ///CHANGED
Serial.flush();
// standard analog read performance -- prescale == 128
microseconds = micros();
for (int i=0; i < numberOfEntries; i++)
{
results[i] = analogRead(sensorPin);
}
duration1 = micros() - microseconds;
Serial.print(numberOfEntries);
Serial.print(" readings took ");
Serial.println(duration1);
// This double loop just prints a neat table..
for( int j=0; j < numberOfEntries; j=j+20)
{
for (int i=0; i < 20; i++)
{
Serial.print(results[j+i]);
Serial.print(", ");
} //end loop i
Serial.println();
} //end loop j
Serial.println();
// prescale clock to 16
bitClear(ADCSRA,ADPS0);
bitClear(ADCSRA,ADPS1);
bitSet(ADCSRA,ADPS2);
// Performance with Changeed Prescale...
microseconds = micros();
for (int i=0; i < numberOfEntries; i++)
{
results[i] = analogRead(sensorPin);
}
duration2 = micros() - microseconds;
Serial.print(numberOfEntries);
Serial.print(" readings took ");
Serial.println(duration2);
for( int j=0; j < numberOfEntries; j=j+20)
{
for (int i=0; i < 20; i++)
{
Serial.print(results[j+i]);
Serial.print(", ");
} //end loop i
Serial.println();
} //end loop j
Serial.println();
Serial.print("Ratio of read times is : ");
Serial.println((float)duration1/duration2);
Serial.println("********************");
}
void loop()
{
// empty main loop is deliberate...
}
There are also optimizations known if the pin number is hard coded at compile time - could not find and example though -