2 years, 8 months ago.

How read_u16 works? How is the calculation?

Let's say I put in value of 2V for signals in the code below what will be the outcome?

  1. include “mbed.h” AnalogIn Ain(p20); int main(){ int x=Ain.read_u16(); }

1 Answer

2 years, 8 months ago.

It depends on the board.

If the ADC is 16 bits then read_u16 is the output of the ADC without any changes.

If the ADC is less than 16 bits then it is the ADC output left shifted by (16-n) bits where n is the number of ADC bits. This will then leave the low (16-n) bits as zero which is non-ideal. Most boards seem to fill these low bits with a copy of the most significant bits which gives a simple way to fill the full range.

e.g. On the LPC1768 which has a 12 bit ADC read_u16() does return (value << 4) | ((value >> 8) & 0x000F);

The Ain.read() function on the other hand does return (float)value * (1.0f / (float)0x0FFF); to return a value between 0 and 1.

When possible use read_u16 and keep things as integers, it's a lot faster.

Mapping of ADC results to 16-bit range is also known as 'normalisation'. See also https://os.mbed.com/questions/76057/STM32L4-12-to-16-bit-ADC-conversion/.

posted by Zoltan Hudak 30 Mar 2019