write word with I2C
-
Is there a more elegant way to do this:
def writeByte(self,addess,data): self.i2c.writeto_mem(self.address, address, data) def writeWord(self,address,data): msb = ((data & 0xFF00) >> 8) lsb = (data & 0x00FF) self.writeByte(address,msb) self.writeByte(address+1,lsb) -
@cmisztur Instead of creating the symbols msb and lsb, you can to that calculation directly in the calls to writeByte(). That saves a little bit of memory & time, even if it makes the intention less clear.
-
@robert-hh so this should work?
self.i2c.writeto_mem(self.address, address, [ ((data & 0xFF00) >> 8), (data & 0x00FF)], addrsize=8 ) -
@cmisztur If you just want a single call, then you could also use struct:
self.i2c.writeto_mem(self.address, address, struct.pack(">H", data), addrsize=8 )But no, I just was referring to a writeWord method:
def writeWord(self,address,data): self.writeByte(address, (data >> 8) & 0xFF) self.writeByte(address + 1, data & 0xFF)That avoids the creating of two symbols & objects.
-
@robert-hh Thanks for the tips. I ended up doing below, which does save 32bytes over struct.pack.
self.tempBuff = bytearray(3) def _writeWord(self,address,data): #self.i2c.writeto_mem(self.address, address, struct.pack(">H", data), addrsize=8 ) self.tempBuff[0] = address self.tempBuff[1] = data >> 8 self.tempBuff[2] = data & 0xff self.i2c.writeto(self.address, self.tempBuff)
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login