ADC prescaler and conversion time

Hello,
I want to use ADC in program and before that i wanted to test how fast will it work (i know it can be calculated, but for exercise i wanted to check it) . I wrote code that should check how fast is the conversion done:

void setup() {                

	//set prescaller
	ADCSRA |= 1<<ADPS2;
	ADCSRA |= 1<<ADPS1;

	//left adjust result (i want to read 8 bits)
	ADMUX |= 1<<ADLAR;

	//ADC interrupt enable
	ADCSRA |= 1<<ADIE;
	
	//ADC enable
	ADCSRA |= 1<<ADEN;
	
	//enable global interrputs
	sei();
	
	//start conversion
	ADCSRA |= 1<<ADSC;
	
	Serial.begin(9600);
	Serial.println("Started");
}

volatile unsigned long completions=0;
unsigned long lastPrint = 0;

ISR(ADC_vect) {
	completions++;
	ADCSRA |= 1<<ADSC;
}


void loop() {
	if ((millis()-lastPrint)>1000) {
		lastPrint = millis();
		Serial.print("ADC results/sec: ");
		Serial.println(completions/(millis()/1000));
	}
}

The problem is that no matter what i put in prescaler register i get similar result - about 9k conversions per second:

ADC results/sec: 8942

What am i doing wrong?

You're assuming ADPS0-2 are in their default power up state of 000b. It's likely that the Arduino core initializes those bits. So add a statement to clear them before you set them. E.G.

ADCSRA &= ~(bit(ADPS2) | bit(ADPS1) | bit(ADPS0));

I don't know if it is the cause of your problem but your code in loop() is not reading completions properly. It should something like this

void loop() {
 if ((millis()-lastPrint)>1000) {
 lastPrint = millis();
 noInterrupts();
 unsigned long tempCompletions = completions;
 interrupts();
 Serial.print("ADC results/sec: ");
 Serial.println(tempCompletions/(millis()/1000));
 }
}

The completions variable consists of 4 bytes and they could change while you are reading the value if you don't briefly turn off the interrupts.

...R

jboyton:
You're assuming ADPS0-2 are in their default power up state of 000b. It's likely that the Arduino core initializes those bits. So add a statement to clear them before you set them. E.G.

ADCSRA &= ~(bit(ADPS2) | bit(ADPS1) | bit(ADPS0));

It was the cause, thanks :slight_smile:

Robin2:
I don't know if it is the cause of your problem but your code in loop() is not reading completions properly

Thanks for your remark :slight_smile: