# Importations des librairies et définition des fonctions

from PyFirmataDef import *
from ConnectToArduino import *
import time


# Déclaration des constantes et variables

PinLED = 11
PinButton = 12
PinSensor = 5
ValSensor = 0
ValButton = 0
OldValButton = 0
State = 0


# Connexion à l'Arduino

PortComArduino = SelectPortCOM()
board = OpenPortCom(PortComArduino)


# Connexion à l'Arduino réussie - Déclaration des entrées et sorties

ArduinoIterator = Iterateur(board)
PinDigitalInput = DigitalInput(board, PinButton)
PinAnalogInput = AnalogInput(board, PinSensor)
PinAnalogOutput = AnalogOutput(board, PinLED)
time.sleep (0.5)

print("Connexion à l'arduino établie - Appuyez sur Ctrl-C pour quitter")


# Boucle principale du programme

while True:
    try:
        ValButton = PinDigitalInput.read()
        ValSensor = PinAnalogInput.read()
        time.sleep(.01)
            
        if ValButton == 1 and OldValButton == 0:
            State = 1 - State        

        OldValButton = ValButton

        if State == 1:
            PinAnalogOutput.write(1 - ValSensor)
        else:
            PinAnalogOutput.write(0)

    except KeyboardInterrupt:
        PinAnalogOutput.write(0)
        board.exit()
        sys.exit(0)
        
