Predefined constants, where documented

I’m working on interrupts and I find an example with the following code:

// nothing prior to this line
void setup() {
// …
// Set CS21 bit for 8 prescaler
TCCR2B |= (1 << CS21);
// …

This line verifies without error, so “CS21” must be defined somewhere in the IDE. Is there an accessible list of all these constants?

Also, what is the advantage of the construct “(1 << CS21)” ? Why not “B00000010” or “0x02”?

Further, doesn’t “OR-ing” create a potential error if bits 0 and 2 are unknown? Seems the foolproof code would be

TCCR2B = TCCR2B & B11111000 ; // clear bits 0, 1, 2
TCCR2B = TCCR2B | B00000010 ; // set bit 1 = 1

The whole idea with Or'ing is that you are leaving those bits the same.

Keith, understand totally. But to get a prescale of 8, bits 0 and 2 have to be "0". OR-ing bit 1 to a "1" doesn't guarantee the correct prescale value.

These are registers of the Atmel chip on the Arduino, so documentation can be found in the datasheet provided by Atmel. For example, the datasheet of the ATmega328P chip found on most Arduino Uno's:


Since you've only posted a small snippet, are the CS20 and CS22 bits cleared on another line somewhere?

Saximus, I don't know if the other two bits are cleared elsewhere. I'm assuming they must be, or the programmer is assuming that since this line is in "setup()" that there has been a reset and the bits are always "0" after a reset.

I was only asking that as a general rule you can't rely on a bitwise OR to set multiple bits to a known state.

Thanks for the pointer to Atmel datasheet. I've been reading the clock/timer interrupt section and I see the bit names used therein, but I hadn't seen any Arduino documentation that explicitly said the IDE used the same names and values as the datasheet.

The relevant defines are in iom328.h (or the appropriate part specific one) - there’s one such file for each supported part and it gets included by the compiler via a series of #ifdefs. That’s compiler stuff, not arduino stuff.

The bit names are #defined to the position of that bit within the relevant register.

DrAzzy, thanks for the pointout to file. I haven’t dived into the IDE that deep, but I guess it’s time to start doing so.