-1

To set the clock prescaler on the Atmega32u4, you have to set TCCR0B according to this table: table

If you want the prescaler to be 64, you would write this:

TCCR0B |= BV(CS01) | BV(CS00);

btw, here is BV():

#define BV(x) (1<<x)

I want to do this using a macro, this is what I have so far:

#define CLK_SEL(n) ((n == 256 || n == 1024) ? BV(CS02) : 0) | \
                       ((n == 8 || n == 64) ? BV(CS01) : 0) | \
          ((n == 1 || n == 64 || n == 1024) ? BV(CS00) : 0)

I now want to check if N is equal to 1, 8, 64, 256, or 1024. How would I accomplish this? I tried it using #if and #error, but I haven't come up with a solution that compiles, unfortunately.

sj95126
  • 6,520
  • 2
  • 15
  • 34

1 Answers1

1

Tail wagging the dog; trying to convert some arbitrary bit pattern to one from a selected. limited range...

int main() {
    enum { ePreScl_1 = 1, ePreScl_8, ePreScl_64, ePreScl_256, ePreScl_1024 };

    printf( "%X\n", ePreScl_1 );
    printf( "%X\n", ePreScl_8 );
    printf( "%X\n", ePreScl_64 );
    printf( "%X\n", ePreScl_256 );
    printf( "%X\n", ePreScl_1024 );

    return 0;
}
1 // 001
2 // 010
3 // 011
4 // 100
5 // 101
Fe2O3
  • 6,077
  • 2
  • 4
  • 20
  • 2
    According to this way, always set `TCCR0B` to `0`, then use only logical operator eg: `TCCR0B |= ePreScl_1`, because `TCCR0B` uses `WGM02`, `FOC0B` and `FOC0A` too. You will probably use **`WGM02`** later to set your **PWM operating mode** ... Also, be careful with this because the **Atmega32u4** uses an hi freq **Timer4**, which needs **4 bits** (not 3) through its register **`TCCR4B`** (ie `CS40`, `CS41`, `CS42`, `CS43`). – Valery S. Oct 01 '22 at 13:15