#!/usr/bin/env python3


def calc_output(v_c1, v_c2):
    vref = 3.3 / 2 # [V]
    rref = 1/(1/10e3 + 1/10e3) # [Ohm]

    vpos = vref + (v_c1 - vref) * rref / (rref + 220e3)

    # vneg = vdiff + (v_c2 - vdiff) * 10e3 / (220e3 + 10e3)
    # vneg =!= vpos
    k1 = rref / (rref + 220e3)
    k2 = 10e3 / (220e3 + 10e3)
    # vdiff + (v_c2 - vdiff) * k2 = vref + (v_c1 - vref) * k1
    # vdiff + v_c2*k2 - vdiff*k2 = vref + (v_c1 - vref) * k1
    # vdiff * (1-k2) = vref + (v_c1 - vref)*k1 - v_c2*k2
    vdiff = (vref + (v_c1 - vref)*k1 - v_c2*k2) / (1-k2)
    adc_counts = vdiff / 3.3 * 0xffff
    print(f'{vdiff:.3f} V ^= {round(adc_counts)} counts')
    return adc_counts

print('Results for 18 V')
a = calc_output(18, 0)
b = calc_output(0, 18)
print(f'middle = {round((b+a)/2)} counts')

print()
print('Results for 24 V')
a = calc_output(24, 0)
b = calc_output(0, 24)
print(f'middle = {round((b+a)/2)} counts')

for v in range(11, 25):
    print()
    print(f'Results for {v} V with 0.7 V diode drop on GND')
    a = calc_output(v-0.7, -0.7)
    b = calc_output(-0.7, v-0.7)
    print(f'middle = {round((b+a)/2)} counts')
