-1
public void setRegisterFlag(I2cDevice device, int address) throws IOException 
    // Read one register from slave
    byte value = device.readRegByte(address);
    // Set bit 6
    value |= 0x40;
    // Write the updated value back to slave
    device.writeRegByte(address, value);
}

I saw this code above from android things i2c guide: According to the table below the correct to set bit 6 is 0x20 and not 0x40. How to I set a single bit? What is the importance of setting specific bits and not all 8 bits When I will write in registers?

enter image description here

Onik
  • 19,396
  • 14
  • 68
  • 91
  • 1
    Why are you putting more faith in an answer with 2 downvotes than in working source code? It depends on whether you start counting at bit 1 or at bit 0 in any case - as programmers normally start counting at 0, bit 0 would be 0x01, bit 6 would be 0x40, and bit 7 would be 0x80. The answer you referenced starts counting at bit 1 but omits the 8th bit. – Erwin Bolwidt Jan 07 '18 at 03:16
  • this is my i2c sensor: http://www.mindsensors.com/rpi/76-smartdrive-high-current-motor-controller look in pdf in Documents sessions please –  Jan 07 '18 at 15:03

1 Answers1

4

"How to set a single bit?"

Use the | operator.

"Why I need use|= in my i2c project?"

Because that is a simple way to set bits. Seriously, you need to do some reading on bitwise operators in Java.

and so on.

"What is the importance of setting specific bits and not all 8 bits?"

It is determined by the specified behavior of the hardware device you are attempting to control. Read the device manual / documentation.

In fact, the code is will physically writing all 8 bits of the byte. It is just that only one of the bits will be changing.

"When I will write in registers?"

You typically write in registers when you need to make the device do something.

"According to the table below the correct to set bit 6 is 0x20 and not 0x40."

It depends on whether you number bits starting at zero or at one. That "table" (actually it is code) is numbering bits from one. That is NOT the normal convention for numbering bits, which partly explains why that answer got 2 downvotes. (Hint: people generally downvote answers because they are misleading or wrong. You should pay attention to this and be selective in what you read.)

If you take the time to read up on bitwise operators, you should be able to understand that code. You should always attempt to understand code for yourself rather than just blindly assuming that it is correct ... 'cos you found it on StackOverflow or something.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216