I am programming for the Arduino Due, which is based on a 32-bits micro controller. I want to read an ADC result register (it has width 32 bits if I am right, but it has a true maximum width of 12 bits, which is the resolution of the ADC), and write it at a given location in an array of integers with width 16 bits.
This works:
volatile uint16_t Buf[nchannels];
[... some code...]
void ADC_Handler() {
for (int i = 0; i < nchannels; i++)
{
Buf[i] = (volatile uint16_t) * (ADC->ADC_CDR + channels[i]); // my modification
}
FlagConversion = true;
}
But using instead a more "explicit" cast does not work:
Buf[i] = dynamic_cast<volatile uint16_t *>(ADC->ADC_CDR + channels[i]);
Produces:
"error: cannot dynamic_cast '(((RoReg*)1074528336) + ((sizetype)(((unsigned int)channels[i]) * 4)))' (of type 'RoReg* {aka volatile long unsigned int*}') to type 'volatile uint16_t* {aka volatile short unsigned int*}' (target is not pointer or reference to class)"
and similar unclear errors with static and reinterpret casts:
"error: cannot dynamic_cast '(((RoReg*)1074528336) + ((sizetype)(((unsigned int)channels[i]) * 4)))' (of type 'RoReg* {aka volatile long unsigned int*}') to type 'volatile uint16_t* {aka volatile short unsigned int*}' (target is not pointer or reference to class)"
and
"error: invalid conversion from 'volatile uint16_t* {aka volatile short unsigned int*}' to 'uint16_t {aka short unsigned int}"
A 'safe' way to do the cast is to first dereference the pointer to the 32-bit data, then mask out the upper 16 bits of that data item, then static_cast
the result to your 16-bit destination data:
Buf[i] = static_cast<volatile uint16_t>( *(ADC->ADC_CDR + channels[i]) & 0x0FFFF );
It is always best to use the 'simplest' form of cast, and to avoid both C-style casts and reinterpret_cast
whenever possible. In this case, it makes little sense to cast the pointer, and it is much safer and simpler to convert/cast the data itself.
Actually, the masking with 0x0FFFF
is, strictly speaking, entirely unnecessary and superfluous. However, it makes it clear to any future reader of your code that you do, indeed, know what you're doing!