Basic help with bits bytes and nibbles!

Hello, I have a Rainbowduino LED matrix. Each colour pixel's brightness is represented by 4 bits, i.e. 16 levels of brightness.

One byte represents 2 pixels next to each other. E.g. B00001111 would represent the left pixel being off and the right being at full brightness.

I am trying to write a basic driver where I can set each pixel's level individually, but have got stuck with the bitwise operations...

Imagine the left and right LEDs are set to 2 different levels E.g. B10110011, and I want to change the left value to a new brightness, say 1111. How do I mask the right hand 4 bits so that they don't get affected by any bitwise operation I apply.

My current thinking is if I could mask the right 4 bits somehow, I could then OR the left 4 bits with 0000 to reset them to 0000 and then AND them with the new value to set them to that.

Am I along the right lines or is there an easier way? I would also need to apply the solution the other way round, i.e. masking the left 4 bits if I wanted to change the right hand ones.

Any guidance appreciated!

Nick

Try something like this:

unit8_t bothpixel = 0b10110011;

// Change upper nibble in bothpixels to newhigh via bitwise operations
uint8_t newhigh = 0b00001111;
bothpixles = (bothpixels & 0b00001111) | (newhigh << 4);

// Change lower nibble in bothpixels to newlow via bitwise operations
uint8_t newlow = 0b00001010;
bothpixles = (bothpixels & 0b11110000) | newlow;

There are also easier ways using library functions, but this should illustrate how to do it with bitwise operations.

Korman

Great that works a treat - I was half way there!

Thanks for taking the time to look at it

Nick