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


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.

  • \$\begingroup\$ Thanks, this makes sense. I should have seen that _BV() returned a byte instead of a bit. \$\endgroup\$ – Cate Nov 2 '14 at 1:05
  • \$\begingroup\$ As Ignacio said _BV()can also be seen as a right shift (in fact that is the way it is defined). \$\endgroup\$ – Bruno Ferreira Nov 2 '14 at 1:12

_BV is a macro that performs a left shift. EXCLK and AS2 are bit positions within their register. So the code ORs the bit values together, inverts the whole thing (all 8 bits), and ANDs them with the register. In short, it clears those bits.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.