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)
    


  • @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)
    


  • @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 so this should work?

    self.i2c.writeto_mem(self.address, address, [ ((data & 0xFF00) >> 8), (data & 0x00FF)], addrsize=8 )
    


  • @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.


Log in to reply
 

Pycom on Twitter