Q*bert
03-31-2009, 05:09 AM
I have been writing some stuff in Imagecraft C lately and found myself fumbling around when
doing all the bit fiddling required when programming a microcontroller.
I remembered some macros I had found when i was doing AVR C programming, so I blew the
dust off of them and here they are!
// macros for bit fiddling in C (from AVR tech notes and AVRfreaks.com forum discussions)
#define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT))
#define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT))
#define FLIPBIT(ADDRESS,BIT) (ADDRESS ^= (1<<BIT))
#define CHECKBIT(ADDRESS,BIT) (ADDRESS & (1<<BIT))
#define SETBITMASK(x,y) (x |= (y))
#define CLEARBITMASK(x,y) (x &= (~y))
#define FLIPBITMASK(x,y) (x ^= (y))
#define CHECKBITMASK(x,y) (x & (y))
#define VARFROMCOMB(x, y) x
#define BITFROMCOMB(x, y) y
#define C_SETBIT(comb) SETBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CLEARBIT(comb) CLEARBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_FLIPBIT(comb) FLIPBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CHECKBIT(comb) CHECKBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
These can be really handy as you don't need to recall the bit logic over and over again.
The last four macros deserve an example to show how they can be used:
/******* C_ macros usage example *********/
#define Status_LED OUTA, 3
C_SETBIT(Status_LED);
C_CLEARBIT(Status_LED);
I hope these help someone simplify their C programming. I know my aging mind appreciates
the help!
BTW, I am really enjoying the Imagecraft compiler. Watch for some new libraries soon!
doing all the bit fiddling required when programming a microcontroller.
I remembered some macros I had found when i was doing AVR C programming, so I blew the
dust off of them and here they are!
// macros for bit fiddling in C (from AVR tech notes and AVRfreaks.com forum discussions)
#define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT))
#define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT))
#define FLIPBIT(ADDRESS,BIT) (ADDRESS ^= (1<<BIT))
#define CHECKBIT(ADDRESS,BIT) (ADDRESS & (1<<BIT))
#define SETBITMASK(x,y) (x |= (y))
#define CLEARBITMASK(x,y) (x &= (~y))
#define FLIPBITMASK(x,y) (x ^= (y))
#define CHECKBITMASK(x,y) (x & (y))
#define VARFROMCOMB(x, y) x
#define BITFROMCOMB(x, y) y
#define C_SETBIT(comb) SETBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CLEARBIT(comb) CLEARBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_FLIPBIT(comb) FLIPBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
#define C_CHECKBIT(comb) CHECKBIT(VARFROMCOMB(comb), BITFROMCOMB(comb))
These can be really handy as you don't need to recall the bit logic over and over again.
The last four macros deserve an example to show how they can be used:
/******* C_ macros usage example *********/
#define Status_LED OUTA, 3
C_SETBIT(Status_LED);
C_CLEARBIT(Status_LED);
I hope these help someone simplify their C programming. I know my aging mind appreciates
the help!
BTW, I am really enjoying the Imagecraft compiler. Watch for some new libraries soon!