C++ 8-Bit Register Read-Modify-Write

C++ 8-Bit Register Read-Modify-Write


The following code snippet demonstrates how to set a particular bit in an 8-bit registerwithout squashing the values already there. The function allows you to write 1 bit whilemaintaining the other bits that are already set in this register.

The function would be called with something like this:

// Setup the chip for initial control

writeHdmiChipRegister("0x94",0b10000000,7); // Hot Plug Detect Interrupt Enable

writeHdmiChipRegister("0x94",0b01000000,6); // Monitor Sense Interrupt Enable

writeHdmiChipRegister("0x41",0b01000000,6); // Power down the chip

writeHdmiChipRegister("0x41",0b00000000,6); // Power up the chip

/**

* @brief InterruptHandler::writeHdmiChipRegister - Read-Modify-Write to a register

*

* @param register

* The register of the HDMI chip to read in hex

*

* @param value

* The value to write to the register

*

* @param bit

* The bit from the 'value' ( 0->8 ) to be set [ 0 is least signifiacant bit ]

*

*/

int InterruptHandler::writeHdmiChipRegister(QString registerAddress, quint8 value, quint8 bit) {

...

// Switch based on the bit we want to set

quint8 clearBits = 0b11111111;

switch( bit ) {

case 7:

clearBits = 0b01111111;

break;

case 6:

clearBits = 0b10111111;

break;

case 5:

clearBits = 0b11011111;

break;

case 4:

clearBits = 0b11101111;

break;

case 3:

clearBits = 0b11110111;

break;

case 2:

clearBits = 0b11111011;

break;

case 1:

clearBits = 0b11111101;

break;

case 0:

clearBits = 0b11111110;

break;

default:

clearBits = 0b11111111;

}

// Do Read-Modify-Write on register to preserve contents of bits we are not controlling

quint8 readByte = i2c_smbus_read_byte(privFd); // Read the 8 bits from the register

qDebug() << "The old register value is: " << QString::number(readByte, 2);

quint8 clearedBits = readByte & clearBits; // Clear out all bits except the one we want to set with AND operation

quint8 byteToWrite = clearedBits | value; // OR the value to be written with the cleared bit to be set

qDebug() << "The new register value is: " << QString::number(byteToWrite, 2);

res = i2c_smbus_write_byte(privFd, byteToWrite); // Write it to the register via i2c

...

}

Happy Coding!



ClassyBits 2016