MicroPython Driver for TCA9548A

TCA9548A Driver Code for micro:bit

Download as zip file

'''
TCA9548A
I2C 8-channel multiplexer
MicroPython driver for micro:bit

AUTHOR: fredscave.com
DATE  : 2024/10
VERSION : 1.00
'''

from microbit import *

ADDR = 0x70

class TCA9548A():
    def __init__(self, addr=ADDR, reset_pin=None):
        self.addr = addr
        self.reset_pin = reset_pin
        if reset_pin != None:
            reset_pin.write_digital(1)
        self.CloseAllChannels()

    def getReg(self):
        buf = i2c.read(self.addr, 1)
        return buf[0]

    def setReg(self, mask):
        i2c.write(self.addr, bytearray([mask]))

    def OpenChannels(self, *channels):
        mask = 0
        ctrl_reg = self.getReg()
        for channel in channels:
            if channel in range(8):
                channel_bit = 1 << channel
                mask = mask | channel_bit
        self.setReg(ctrl_reg | mask)

    def CloseChannels(self, *channels):
        mask = 0b11111111
        ctrl_reg = self.getReg()
        for channel in channels:
            channel_bit = 1 << channel
            channel_bit = ~channel_bit & ((1 << 8) - 1)
            mask = mask & channel_bit
        self.setReg(ctrl_reg & mask)

    def CloseAllChannels(self):
        mask = 0
        self.setReg(mask)

    def IsOpen(self, channel):
        if channel not in range(8):
            return False
        mask = 1 << channel
        ctrl_reg = self.getReg()
        if (ctrl_reg & mask) == mask:
            return True
        else:
            return False

    def Reset(self):
        if self.reset_pin != None:
            self.reset_pin.write_digital(0)
            sleep(1)
            self.reset_pin.write_digital(1)