Confused about left-shift format for setting/clearing bits

On this site:

they show code like this:

//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR0A register to 0
  TCCR0B = 0;// same for TCCR0B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);   
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

When I try to use the (1 << whatever) format, I get an error that says:

"expression cannot be used as a function"

I don't understand why it works for them, but not for me.

Also, why is the shifting necessary? Is WGM01, for example, a bit position (1), or is it a bit value(2)? Seems like it would be a bit value to be of any use, in which case

TCCR0A |= WGM01

should work to set that bit.

And while I'm asking, if I set the timer prescaler to 256, should I set the compare register to 250 or 249 to get a 4ms rate? I'm guessing 250.

Sorry. I'm just completely new to this. Thanks for any help.

Edit: Ok, I found that WGM01 is a bit position, which is why it needs to be shifted. But that still leaves the question of why that format doesn't work in my sketch.

the code extract you gave does not throw any error if I just put that in my setup... it's syntactically correct.

you might have a missing ( or something before in your code that throws the compiler off

the expression to the right of the |= in  TCCR0A |= (1 << WGM01);is handled by the pre-processor and not calculated at run time, so it's efficient. This notation makes it super easy to understand what they do. They set the bit which is named WGM01 to 1. You don't have to worry about knowing the value of WGM01 that will just work and do the right thing. -->easy to read, easy to debug, easy to maintain.

You were right. I was missing a semicolon.

But, would this work just as well, or is the << better for some reason:

TCCR0A |= bit(WGM01);

If you look up the definition of the bit() macro, you'll find:

#define bit(b) (1UL << (b))

I haven't found where those definitions are. Anyway, I assume you would tell me that:

bitSet(TCCR0A,WGM01)

would also work, but would also end up in << form.

ShermanP:
I haven't found where those definitions are. Anyway, I assume you would tell me that:
bitSet(TCCR0A,WGM01)
would also work, but would also end up in << form.

Have a look here :slight_smile:

ShermanP:
And while I'm asking, if I set the timer prescaler to 256, should I set the compare register to 250 or 249 to get a 4ms rate? I'm guessing 250.

It turns out the correct value is 249.