Search code examples
c++cc-preprocessorpreprocessoratmega32

Check number range in Preprocessor macro


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.


Solution

  • 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