from time import sleep
sleep(0.1) # Wait for USB to become ready
from arrays import OutArray
from machine import Pin
# pins for values A & V
B_list = [2, 3, 4, 5]
A_list = [6, 7, 8, 9]
# create carry in input
btn = Pin(10, Pin.IN, Pin.PULL_UP)
cin = Pin(11, Pin.OUT, value=0)
cin.value(btn.value())
# create output arrays of GPIO pins
A = OutArray(A_list)
B = OutArray(B_list)
print("Welcome to 4 bit Adder/Subtractor")
while True:
try:
# get values of A & B
x = input('Value of A: ')
numA = int(x) # convert to integer
while numA > 15: # check a valid value
print("Error: A must be a value less than 16")
x = input('Value of A: ')
numA = int(x)
x = input('Value of B: ')
numB = int(x) # convert to integer
while numB > 15: # check a valid value
print("Error: B must be a value less than 16")
x = input('Value of B: ')
numB = int(x)
cin.value(btn.value())
A.write(numA)
B.write(numB)
if btn.value():
print(f"A - B: {numA} - {numB} = {numA - numB}")
else:
print(f"A + B: {numA} + {numB} = {numA + numB}")
sleep(0.1)
except KeyboardInterrupt:
break
# clear all leds at end
A.write(0)
B.write(0)
cin.value(0)
print(f'\nfinished')
Operation
Answer
In addition Blue LED is overflow - bit 4 (2^4 = 16)
In subtraction (green LED on) Blue LED indicates negative answer
in 2's complement form