Electronic – arduino – Register Syntax question

arduinoatmegaatmelmicrocontrollerregister

I was reading some code to use an on an arduino ATMEGA328P and I can't figure out what this line of code does.

ASSR &= ~(_BV(EXCLK) | _BV(AS2));

I know that ASSR is the Asynchronous status register and that EXCLK are AS2 are bits in that register. I'm pretty sure that _BV() is used to set that bit, correct me if I'm wrong. What I don't know is what this code actually does? It seems like that this code uses bitwise operations to compare the register ASSR to a single bit (~(_BV(EXCLK) | _BV(AS2))) and then sets that register to a single bit, one or zero. This doesn't make any sense to me since this register is 7 bits large and can't be compared to a single bit. Any help is appreciated, thanks.

Relevant documentation:

ATMEGA 328P datasheet

AVR Libc page

Best Answer

I have little experience in Arduino but it looks like that line it's clearing the bits EXCLK and AS2.

From the context BV() should give you the bit weight.

AS2 is bit 5 (counting from the right starting from 0) on the register, then _BV(AS2) should return 32 (\$2^{5} = 64\$). By the same logic _BV(EXCLK) should return 64 since EXCLK is bit 6.

so in binary we have

_BV(AS2) = 00100000 and _BV(EXCLK) = 01000000

When we or these values we get 01100000

the ~ inverts the values so we get 10011111

Then the &= keeps all the bits that are 1 on the previous result unchanged and sets the remaining bits (5 and 6) to 0.