#!/usr/bin/env python
#
#from smbus import SMBus
import time
from struct import*
import ctypes
import array
import numpy as np
import matplotlib.pyplot as plt

from ADUCv2p0 import*


chip1 = ADUCv2p0(0x50,True)

chip1.set_channel(3) #ADC

chip1.set_auto_set_pga(1)
chip1.set_Vout(0,2500)  #DAC for offset
chip1.set_pga_state(0x08)
#chip1.set_pga_state(0x18) #G=2
#chip1.set_pga_state(0x28) #G=4
#chip1.set_pga_state(0x38) #G=8
#chip1.set_pga_state(0x48) #G=16
#chip1.set_pga_state(0x58) #G=32
#chip1.set_pga_state(0x68) #G=64
#chip1.set_pga_state(0x78)

chip1.set_Vlearn(3200)
chip1.set_start(20)
chip1.set_stop(100)
chip1.set_start_gnd(125)
chip1.set_stop_gnd(200)
chip1.set_wf_len(200)
chip1.set_enab_gnd(1)
chip1.set_N(1)
chip1.set_Gain(20)
chip1.set_remote_trigg(0)

chip1.set_Vout(2, 4000)
time.sleep(2) #Let auto_set_pga do its job
chip1.set_auto_set_pga(0) #Stop it while we scan
print(chip1.get_auto_set_pga())
print(chip1.get_Vout(0))
print(chip1.get_pga_state())
print('---')
time.sleep(2)




npt = chip1.get_wf_len()
start = chip1.get_start()
stop = chip1.get_stop()
start_gnd = chip1.get_start_gnd()
stop_gnd = chip1.get_stop_gnd()


data = chip1.read_data()
t = np.linspace(0,npt,npt)


measurements = []
for Vfine in range(2000, 4000, 100):
    chip1.set_Vout(2, Vfine)
    time.sleep(0.1)
    data = chip1.read_data()
    gnd = sum(data[start_gnd:stop_gnd])/(stop_gnd-start_gnd)
    signal = sum(data[start:stop])/(stop-start)
    print(chip1.get_Vout(2), signal-gnd)
    measurements.append([chip1.get_Vout(2), signal-gnd])
    
measurements = np.array(measurements)
p = np.polyfit(measurements[:,0], measurements[:,1], deg=1)
print('signal-gnd vs Vfine slope', p[0])
chip1.set_Gain(1/p[0]*.9)
print('Gain has been set to 90%*1/slope', 1/p[0]*.9)


