About : Series of Device Drivers for micro:bit

Testing 2-Input Logic Gate IC's

Download as zip file

'''
Tester for 2-input logic gates.
Identify/test the following gate types:
AND, NAND, OR
NOR, XOR, XNOR

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

from microbit import *

LG_Dict = {'AND':'0001', 'NAND':'1110',
           'OR':'0111', 'NOR':'1000',
           'XOR':'0110', 'XNOR':'1001'}

class LGT():
    def __init__(self, PINin1 = pin0,
                       PINin2 = pin1,
                       PINout = pin2):
        self.PINin1 = PINin1
        self.PINin2 = PINin2
        self.PINout = PINout

    @staticmethod
    def get_key(value):
        # Given a value, find the first
        # matching key in the dictionary.
        for key in LG_Dict:
            if LG_Dict[key] == value:
                return key
        return None

    def GetTruthTable(self):
        # Returns a truth table as
        # a list of lists.
        truth = list()
        for i1 in range(2):
            for i2 in range(2):
                self.PINin1.write_digital(i1)
                self.PINin2.write_digital(i2)
                out = self.PINout.read_digital()
                l = [i1, i2, out]
                truth.append(l)
        return truth

    def PrintTruthTable(self):
        # Get the raw truth table
        truth = self.GetTruthTable()
        print('TRUTH TABLE')
        print('In1', 'In2', 'Out')
        # print each line of truth table
        for x in range(4):
            print(' ', truth[x][0], '   ', truth[x][1],
                  '   ', truth[x][2], sep='')


    def LogicGate(self):
        # This method gets the truth table
        # then builds a string of all the outputs.
        # The string is checked against a dictionary
        # of outputs for all gate types. If a
        # match is found that is returned as
        # logic gate type.
        truth = self.GetTruthTable()
        output = ''
        for x in range(4):
            output += str((truth[x][2]))
        Gate = LGT.get_key(output)
        if Gate != None:
            return Gate
        else:
            return 'Unknown gate'

    def Report(self):
        # prints a formatted report of the truth table
        # and the logic gate type found.
        print('\n')
        self.PrintTruthTable()
        print('\nLogic Gate:', self.LogicGate(), '\n')