# Importations des librairies et définition de fonctions

from PymataExpressDef import *
from ConnectToArduino import *
import time

def decharge(board, pinalim, pinU):
    Digital_Write(board, pinalim, 0);
    print("Décharge du condensateur.")
    while Analog_Read(board, pinU) > 0:   
        time.sleep(0.2)  
    print("Condensateur déchargé.")


# Déclaration des constantes et variables

PinUC = 0
PinButton = 12
PinAlimC = 2

ValPinUC = 0
UC = 0.0
t0 = 0
dt = 0

ValButton = 0
OldValButton = 0
State = 0
OldState = 0


# Connexion à l'Arduino

print("\nConnexion à l'Arduino en cours...")
             
PortComArduino = SelectPortCOM()
board = OpenPortCom(PortComArduino)

Set_AnalogInput_Pin(board, PinUC)
Set_DigitalInput_Pin(board, PinButton)
Set_DigitalOutput_Pin(board, PinAlimC)

print("Connexion à l'Arduino établie - Appuyez sur Ctrl-C pour quitter.\n")

decharge(board, PinAlimC, PinUC)

print("\nAppuyez sur le bouton poussoir pour commencer les mesures.\n")
    

# Boucle principale du programme

while True:
    try:
        ValButton = Digital_Read(board, PinButton)
        time.sleep(0.01)
        if ValButton == 1 and OldValButton == 0:
            State=1-State
  
        OldValButton = ValButton;

        if State==1:  
            if OldState == 0:
               print("\nCharge du condensateur en cours.\n")
               print("Temps (S); Uc (V):")
               t0 = time.time()
               Digital_Write(board, PinAlimC, 1)
               OldState=1
        
            ValPinUC = Analog_Read(board, PinUC)
            UC = (ValPinUC/1023)*5.0
            dt = time.time()-t0
            print(round(dt,2),";",round(UC,2))

            time.sleep(0.1)

        else:
            if OldState == 1:
                print("\nFin des mesures.\n")
                decharge(board, PinAlimC, PinUC)
                print("\nAppuyez sur le bouton poussoir pour commencer les mesures.\n")
                OldState = 0 
                       
    except KeyboardInterrupt:
        print("\nFin du programme.\n")
        decharge(board, PinAlimC, PinUC)
        Arduino_Exit(board)
        sys.exit(0)

