Can someone translate?

Can someone tell me what this bit of code is doing?

TCCR2A &= ~((1<<WGM21) | (1<<WGM20));  
TCCR2B &= ~(1<<WGM22);

It’s code I found online for setting up Timer 2 of the ATmega328, and I just want to try and figure out what it is doing.



TCCR2A &= ~((1<<WGM21) | (1<<WGM20));

Is resetting bits WGM21 and WGM20 in the TCCR2A register.

The first line clears two bits in the register called 'TCCR2A. It does this by making a byte with two bits set to ‘1’ and then using bitwise AND and bitwise NOT to clear those bits. the constants WGM21 and WGM20 are small integers that specify which bit (0-7) is to be set in the byte. So, (1<<WGM21) is a byte with just one bit set to ‘1’. Look up bitwise operators on C for more information.

I suggest you read up from

1.2 - Working with Binary Numbers
1.5 - Working With AVR Registers

linked from the following page. Sign in - Google Accounts

That might clarify what AWOL is saying and allow you to understand what is going on.

Basically thereis a bunch of shifting bits to and fro to set specific bits, negating it and using the result as a mask to clear the given bits in the register.

The C programming language can be pretty ‘low level’ in that it gives one access to very fundamental bit manipulation operators. However newcomers can have difficulty in ‘decoding’ these operations and how to use them till they climb higher on the ‘learning curve’. The Arduino platform has added more ‘high level’ functions to use if you wish to use them, but of course the might bring on the graybeards for using such ‘beginners’ methods. :wink:

So this code:

TCCR2A &= ~((1<<WGM21) | (1<<WGM20));  
TCCR2B &= ~(1<<WGM22);

Could be replaced with this:

bitClear(TCCR2A, WGM20);  //clear bit WGM20 in TCC2A

bitClear(TCCR2A, WGM21); //clear bit WGM21 in TCC2A

bitClear(TCCR2B, WGM22); //clear bit WGM23 in TCC2B



Thanks for the replies, I will look over the relavent sections.

As for 'beginners methods', at the minute, of they get the job done, I am fine with that. 8)