import numpy as np
from scipy import linalg
digitalInput = 160
R = 1200
# resistor to resistor network for 8 bit Digital to Analog Coverter
# Create a Matrix with coefficients for system of 8 equations.
r2r = np.matrix([
[-5*R, 2*R, 0, 0, 0, 0, 0, 0],
[2*R, -5*R, 2*R, 0, 0, 0, 0, 0],
[0, 2*R, -5*R, 2*R, 0, 0, 0, 0],
[0, 0, 2*R, -5*R, 2*R, 0, 0, 0],
[0, 0, 0, 2*R, -5*R, 2*R, 0, 0],
[0, 0, 0, 0, 2*R, -5*R, 2*R, 0],
[0, 0, 0, 0, 0, 2*R, -5*R, 2*R],
[0, 0, 0, 0, 0, 0, 2*R, -4*R]
], dtype=np.float)
print(r2r)
binInput = bin(digitalInput)[2:].zfill(8)
print("---- Input ", digitalInput, " ----")
print("---- Binary ", binInput, " ----")
# Make List of voltages for each loop based on binary input
# v[0] = voltage drop, rise or no change from bit 6 to bit 7
# v[1] = voltage drop, rise or no change from bit 5 to bit 6
# repeat for v[2] .. v[6]
v = [] #List to contain voltages for each loop
vL = [0, -5, 5, 0]
v7 = 0
for b in range(7):
volt = vL[int(binInput[b]+binInput[b+1], 2)]
v7 += volt
v.append([volt])
# v[7] = voltage rise or no change from v=0 to bit 0
volt = vL[int(binInput[7]+"0", 2)] # Voltage on bit 0 input
v7 += volt
v.append([volt])
print("V: ", v, "\n")
V = np.matrix(v) # Make numPy Matrix from list of voltages
# print("V matrix: ", V)
print("-"*80, "\n")
schematic = [
" " * 6 + "".join([" V" + str(r) for r in range(7, -1, -1)]),
" " * 6 + "".join([(" " if Vn[0] >= 0 else " ") + str(Vn[0]) + "V" for Vn in v]),
"\t" + "o--||--" * 8,
"\t" + "| " * 8 + "|",
"\t" + "\ " * 8 + "|",
" " + "".join([" R" + str(r) + " /" for r in range(7, -1, -1)]) + " |",
"\t" + "\ " * 8 + "|",
"\t" + "/ " * 8 + "|",
"\t" + "| " * 8 + "|",
" o---" + "--===--" * 8 + "----|GND",
" " + (" " + str(R / 1000) + "K ") * 7 + " " + str(2 * R / 1000) + "K ",
" \n R7..R0 = " + str(2 * R / 1000) + "K\n"
]
IL = r2r.I @ V # Multiply r2r Inverse Matrix X Voltage Matrix
I7 = IL.tolist()[0][0] # Extract I7 Current from Current Matrix
print("\n\n")
for c in schematic:
print(c)
print(" Currents: \n", IL, "\n")
print("-"*80, "\n")
print("---- Input ", digitalInput, " ----\n")
print("---- Binary ", binInput, " ----\n")
print("R7 Current: ", I7)
print("\nV7 voltage: ", v7)
print("\nR7 Volts: ", I7 * 2 * R) # Calculate Voltage on R
print("\nVout: ", v7 + I7 * 2 * R, "\n\n") # Add signed voltage to V7