Trying to store and read individual bits into an integer. So close. What am I doing wrong?

For my project, I am saving thousands of values to EEPROM memory. In order to fit all of the values into the EEPROM's capacity, I have to crunch all of my smaller values (anything from true/false to 1 – 8) into larger data types.

Storing bits into a bit field has been successful, however I have decided to attempt to fit individual bits inside of a single integer, since I it would be incredibly laborious to write out all of the individual names of the values inside of the struct to be assigned to each switch. Not only are there dozens of switches, but each switch represents a different 'page' of the controller all with their own values.

Right now I'm starting with true/false bits only. I'm trying to write the value to the integer "bitsInFRAM" and print it to binary to see that the values match up. When the integer "bitsInFRAM" prints binary, it is shifted one bit over. I've tried omitting the final shift, but it does not work.

Strangely, when reading the numbers back using a decrementing for loop, it actually works, all except for the first true/false statement. Here is the code followed by what appears in the Serial monitor. Any help is greatly appreciated, thanks!

uint16_t bitsInFRAM = 0; bool oneBitValuesToBeStored[] = { 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1 }; uint16_t bitMask[] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536}; void setup() { Serial.begin(9600); while (!Serial); for (int i = 0; i < 16; i++) { bitsInFRAM = (bitsInFRAM + oneBitValuesToBeStored[i]) << 1; Serial.print(oneBitValuesToBeStored[i]); Serial.print("\t"); Serial.println(bitsInFRAM); } Serial.println(); Serial.println(bitsInFRAM, BIN); Serial.println(); for (int i = 16; i > 0; i--) { bool readFromSRAM[16]; readFromSRAM[i] = (bitsInFRAM & bitMask[i]); Serial.println(readFromSRAM[i]); } } void loop() { } 

Serial monitor:

0 0 0 0 1 2 1 6 0 12 1 26 0 52 0 104 1 210 1 422 0 844 0 1688 1 3378 1 6758 1 13518 1 27038 110100110011110 0 0 1 1 0 1 0 0 1 1 0 0 1 1 1 1 

Touch here for the full post on the Arduino Apprentices tumblr

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s