Skip to content

Instantly share code, notes, and snippets.

@xueliu
Last active November 7, 2020 19:16
Show Gist options
  • Save xueliu/1d65fdbb1d03e4c280311ecf7de09b6f to your computer and use it in GitHub Desktop.
Save xueliu/1d65fdbb1d03e4c280311ecf7de09b6f to your computer and use it in GitHub Desktop.
#include <cstdint>
// normal device class e.g., i2c, spi
class Device {
public:
Device() {}
bool write8(uint8_t page, uint8_t addr, uint8_t v)
{
return true;
}
bool write16(uint8_t page, uint8_t addr, uint16_t v)
{
return true;
}
};
// common register structure
struct Registers {
// one specific register called control
union Control {
// how to locate the register
enum { PAGE = 0x16, ADDRESS = 0x17 };
// value options for one section of this register
struct OPM {
enum { NO_CHANGE = 0, AS_STANDBY = 1 };
};
// bitfield
struct Bits {
uint16_t OPM : 2;
uint16_t CTRL_BR1 : 2;
uint16_t CTRL_BR2 : 2;
} bits;
// raw value
uint16_t raw;
// union constructor
Control(uint16_t v = 0x00) : raw(v) {}
};
};
int main() {
Registers::Control r;
r.bits.OPM = Registers::Control::OPM::AS_STANDBY;
Device device;
device.write16(Registers::Control::PAGE, Registers::Control::ADDRESS,
r.raw);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment