import os     #importing os library so as to communicate with the system
import time   #importing time library to make Rpi wait because its too impatient
os.system ("sudo pigpiod") #Launching GPIO library
time.sleep(1) # As i said it is too impatient and so if this delay is removed you will get an error
import pigpio #importing GPIO library
import RPi.GPIO as GPIO
import datetime

speed = 1200

#stop = 0

GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)

ETATBOUT = 0
ETATBOUTPREC = 0
COMPTEUR = 0
t0 = time.mktime(time.gmtime())
hz = 10

fichier = open("/home/pi/speethondata.txt","a")

ESC=4  #Connect the ESC in this GPIO pin


pi = pigpio.pi();
pi.set_servo_pulsewidth(ESC, 1000)

max_value = 2000  #change this if your ESC's max value is different or leave it be
min_value = 1000  #change this if your ESC's min value is different or leav


while 1:
    time.sleep(0.05)
    pi.set_servo_pulsewidth(ESC, speed)

    t1 = time.mktime(time.gmtime())
    ETATBOUT=GPIO.input(23)
    tc = t1-t0

    if (tc < hz) and (ETATBOUT != ETATBOUTPREC and ETATBOUT == 0):
        time.sleep(0.005)
        COMPTEUR=(COMPTEUR + 1)
        ETATBOUTPREC=ETATBOUT

    else:
        ETATBOUTPREC=ETATBOUT

    if (9.99 < tc) and (tc < 10.01):

        if(COMPTEUR < 785):
            speed += 10

        if(COMPTEUR > 815):
            speed -= 10

        t0 = t0 + hz
        print (time.asctime())
        print (COMPTEUR)
        fichier.write(time.asctime() + " ")
        fichier.write(str(COMPTEUR) + "\n")
        COMPTEUR = 0


#    if inp == "stop":
#        stop = stop + 2
#        pi.set_servo_pulsewidth(ESC, 0)
