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


 

Hello World?

Pylife on Kickstarter - November 2018








Back Us On Kickstarter >

Pycom on Twitter