This is a fundamental question - very new (1st post) and trying to learn. I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1. In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range. Where should I be looking to understand this behavior?
You should keep it uint16_t
.
See: analogRead.
It shows the return value is a 10 bit number, which means a value of 0 to 1023.
If you use uint8_t
, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.
With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the analogRead
function.
Example
Assume the value is 1000, which is in binary:
11 1110 1000
Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:
0000 0011 1110 1000
However, if you try to store this in 8 bits (using uint8_t) you get:
(removed) 1110 1000
Which is the value 232 instead of 1000.
Some guidelines:
- Always use a type that fits the value you want to store (in worst case).
- If you know for sure your value will be non-negative, use an unsigned type (e.g.
uint8_t
). - If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use
uint32_t
).