Skip to content

Instantly share code, notes, and snippets.

@cousteaulecommandant
Forked from Jartza/avr_common_macros.h
Last active March 8, 2017 12:56
Show Gist options
  • Save cousteaulecommandant/baf5732fb801d6a8adcea61392948ee5 to your computer and use it in GitHub Desktop.
Save cousteaulecommandant/baf5732fb801d6a8adcea61392948ee5 to your computer and use it in GitHub Desktop.
/*
* Struct to handle bits in registers
*/
typedef struct {
uint8_t b0:1;
uint8_t b1:1;
uint8_t b2:1;
uint8_t b3:1;
uint8_t b4:1;
uint8_t b5:1;
uint8_t b6:1;
uint8_t b7:1;
} bitmask_s;
/*
* Helper macros for bit pointer macro
*/
#define BNAME(x) BSTR(x)
#define BSTR(x) b##x
/*
* Common defines
*/
#define OUT 1
#define IN 0
#define ON 1
#define OFF 0
/*
* Bit-Shift-Or macros for 1-8 parameters
*/
#define BSO_(a,b,c,d,e,f,g,h,...) (0xFF & (1<<(h) | 1<<(g) | 1<<(f) | 1<<(e) | 1<<(d) | 1<<(c) | 1<<(b) | 1<<(a)))
#define BSO(...) BSO_(__VA_ARGS__, 8,8,8,8,8,8,8,8)
/*
* Examples:
*
* #define LED_DIR BITP(DDRB, PB4); // LED_DIR is "variable" pointing to single bit (PB4) in DDRB
* #define LED_STATE BITP(PORTB, PB4); // LED_STATE points to single bit (PB4) in PORTB
* LED_DIR = OUT; // Set pin as output
* LED_STATE = ON; // Switch LED on
*
* BITS_SET(DDRB, PB3, PB5, PB7); // Set bits PB3, PB5 and PB7 in DDRB, leave other bits untouched.
* BITS_SET_EX(DDRB, PB7); // Sets only PB7 in DDRB, other bits are zeroed (set exclusive).
* BITS_CLEAR(PORTB, PB4); // Clear bit PB4 in PORTB, leave other bits untouched.
*/
/*
* Bit pointer macro which can be used to make individual
* bit variables
*/
#define BITP(var, bit) (((volatile bitmask_s*)&var)->BNAME(bit))
/*
* Macros to set and clear multiple bits in registers
*/
#define BITS_SET(x, ...) (x |= BSO(__VA_ARGS__))
#define BITS_CLEAR(x, ...) (x &= ~BSO(__VA_ARGS__))
#define BITS_SET_EX(x, ...) (x = BSO(__VA_ARGS__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment