Change the resolution of analogRead in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

By default, the analogRead in Arduino follows a 10-bit resolution (this may be different for different boards). However, sometimes, you may not need such a high resolution. Often, people wish to set the resolution to 8-bits, to save on storage. This is because an 8-bit value will take just one byte of storage, whereas anything above that will take two bytes of storage.

Luckily, Arduino has an inbuilt function to change the resolution of the analog to digital conversion. The function is analogReadResolution() and it takes in the argument as the resolution in bits.

So, if you wish to set an 8-bit resolution, you can run analogReadResolution(8). An example implementation is given below −

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
}
void loop() {
   // put your main code here, to run repeatedly:
   analogReadResolution(8);
   Serial.println(analogRead(A0)); //Will perform ADC using 8-bit resolution
   analogReadResolution(10);
   Serial.println(analogRead(A0)); //Will perform ADC using 10-bit resolution
}

Note: In case you demand a higher resolution than what your board supports, then Arduino will just map the highest resolution available to what your board demands.

For example, say your board supports a maximum resolution of 10-bits (0-1024). Now, if you wish to get a 12-bit resolution, then Arduino will get the value in 10-bits, and then upscale it to 12 bits. If the value you would have gotten with 10-bit resolution was 512, Arduino will output 512*4096/1024 = 2048. More technically, Arduino will add padding 0s at the least significant position to match the resolution requested.

Similarly, if you select a resolution lower than the lowest resolution supported by your board, then Arduino will chop off the least significant bits. For example, if the board supports a minimum resolution of 10-bits, and you demand an 8-bit resolution, then the last two digits of the binary representation of the result will be chopped off to give you an 8-bit number. Say, your resultant number with 10-bit resolution was 491. In binary, it is represented as 0b111101011. In order to give you an 8-bit output, the last two digits will be chopped off, and the resultant number (0b1111010) will be returned, whose decimal value is 122. As you can see, some accuracy is lost (491/1023 is not the same as 122/255). But then, that is expected because you are lowering your resolution.

raja
Updated on 23-Mar-2021 11:48:47

Advertisements