Bit operations

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
trav
Posts: 2
Joined: Wed Jan 03, 2018 8:35 am

Bit operations

Post by trav » Wed Jan 03, 2018 8:49 am

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!

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Bit operations

Post by dhylands » Wed Jan 03, 2018 2:39 pm

Your code looks right to me, and I tested it and it seems to work:

Code: Select all

>>> a = 0xff
>>> a &= ~(0b00000111 << 4);
>>> a |= (3 << 4);
>>> print('{:b}'.format(a))
10111111
That was using the unix port of micropython under OSX.

trav
Posts: 2
Joined: Wed Jan 03, 2018 8:35 am

Re: Bit operations

Post by trav » Wed Jan 03, 2018 3:41 pm

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.

Post Reply