# 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
ValButton = 0
OldValButton = 0
State = 0
Brightness = 0
StartTime = 0
Deltatime = 0


# Connexion à l'Arduino

PortComArduino = SelectPortCOM()
board = OpenPortCom(PortComArduino)


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

PinDigitalInput = DigitalInput(board, PinButton)
PinAnalogOutput = AnalogOutput(board, PinLED)
ArduinoIterator = Iterateur(board)
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()
        time.sleep(.01)
        if ValButton == 1 and OldValButton == 0:
            StartTime = time.time()
            State = 1 - State
        if ValButton == 1 and OldValButton == 1:
            Deltatime = time.time() - StartTime
            if Deltatime > 0.5:
                if Brightness < 100:
                    Brightness=Brightness+1
                else:
                    Brightness=0
                time.sleep(.005)
        OldValButton = ValButton
        if State == 1:
            PinAnalogOutput.write(float(Brightness/100))
        else:
            PinAnalogOutput.write(0)
                
    except KeyboardInterrupt:
            PinAnalogOutput.write(0)
            board.exit()
            sys.exit(0)

