Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change uint_8 to x times binary 1 MSB

Tags:

c++

hardware

I'm writing a Max72xx library for my school project and I have found a way to set columns using the registers that comes with the datasheet. Now, I also found a way to set their height. So I have created a function with two parameters: row, which basically sends the x-axis to the chip, and height which sets the y-axis.

What I did in this code is basically the following:

  • The user sets an x-axis between 1 and 8 (parameter const uint8_t& row)
  • The user sets an y-axis between 1 and 8 (parameter uint8_t height)

I wanted to achieve the following:

  • If the height is set to three: the following bit pattern should be created: 1110 000. Or, if the user uses 8, I want the function to create 1111 1111. Or if the user sets 5 as y-axis I want the fucntin to create a bit pattern of 1111 1000, etcetera.

The code I have provided is the following (this piece of code is within the function setColumn):

if (height >= 1 && height <= 8) { // if the height is between the matrix range
    uint8_t pattern = 0x00; // create a pattern to send to the chip
    uint8_t counter = 0; // counter for counting the zeros to shift left later on

    for (uint8_t i = 0; i < height - 1; i++) { // this loop is repeated height amount of times
        pattern |= 0x01; // create 1s in the pattern
        pattern <<= 0x01; // shift it 1 to the left
    }
    pattern |= 0x01; // OR the LSB bit of the pattern

    for (uint8_t i = 7; i > 0; i--) { // count the leading 0 bits to shift them to the MSB position
        if (!(pattern >> i) & 1)
            counter++;
        else break;
    }
    pattern <<= counter;

The MSB is the lowest pixel on the display, the LSB the highest pixel. Now this code works as I described earlier, but I think there is an easier and more efficient way to work this out. I'd like to know some suggestions. Thanks in advance.

like image 545
Marc Dirven Avatar asked Nov 26 '25 13:11

Marc Dirven


1 Answers

Just use this:

uint8_t pattern = (0xff00u >> height);

Or this:

uint8_t pattern = (0xffu << (8 - height));

Don't be afraid of overflows during bit shifting as long as the arguments are unsigned, the behavior is well-defined.

like image 76
rustyx Avatar answered Nov 28 '25 01:11

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!