I'm having trouble wrapping my head around bit operations with MicroPython even after reading searches for quite a while now.
I want to write a module to support the CCS811 sensor and the datasheet tells me to set a drive mode for the chip writing 1, 2 or 3 to the bits 4-6 in the MEAS-Mode register 0x01 (Datasheet page 17, Figure 13).
Reading the register is ok, but I wanted to just set those bits with a masking operator like I would in C, it doesn't work.
Here my example C code - https://pastebin.com/NJaaA8UX - especially:
a &= ~(0b00000111 << 4); // clearing bits 4-6
a |= (3 << 4); // writing 3 to bits 4-6
I tried to use the same syntax with MicroPython but when I look at the bits individually, I see that all bits get overwritten.
What am I doing wrong here? Any help would be appreciated!
Bit operations
Re: Bit operations
Your code looks right to me, and I tested it and it seems to work: That was using the unix port of micropython under OSX.
Code: Select all
>>> a = 0xff
>>> a &= ~(0b00000111 << 4);
>>> a |= (3 << 4);
>>> print('{:b}'.format(a))
10111111
Re: Bit operations
Thank you, I didn't know about the format print option. I'm not at my board right now but I will test it out again in a bit.