# Sampling rate of analog read

I have a simple following analog reading code:

``````void setup()
{
// initialize serial comms
Serial.begin(9600);
}

void loop()
{
// read A0
int val0 = analogRead(0);
int val1 = analogRead(1);
int val2 = analogRead(2);
// print to serial
Serial.print(val0);
Serial.print(" ");
Serial.print(val1);
Serial.print(" ");
Serial.print(val2);
Serial.print("\n");
// wait
delay(50);
}
``````

How do I determine the sampling rate? I understand for the serial print, it's 3*4 bytes (for val0,1,2) + 2 bytes for space and 1 bytes for \n, which is 15/9600.

How much time is spent on analogRead?

## 1 Answer

The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to about 64 Hz (1 sec / (15/960 lines/sec).

The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.

Update:

So I could just use 50ms + 15.6 for the sampling rate, ignoring analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.

How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.

If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.

It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data, you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.

• Thanks! So I could just use 50ms + 15.6 for the sampling rate, ignoring analogRead? Jul 13, 2016 at 18:18
• A single call to `analogRead()` typically takes anywhere between 106.4 and 114.5 µs depending on the phase of the ADC clock prescaler at the time of the call. It can take up to 120.4 µs if it gets interrupted by the timer 0 overflow ISR. Jul 13, 2016 at 20:26