Last active
March 8, 2019 12:33
-
-
Save qpleple/d1d337ad4426721bbf113b1a63598d75 to your computer and use it in GitHub Desktop.
GBR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
import time | |
import requests | |
# -------------- Config -------------- | |
pin_button = 21 | |
pin_led = 20 | |
time_previous_blink = time.time() | |
blinking_state = False # True for LED on, False for LED off | |
blink_on = 0.3 # duration of the LED being on while blinking (in sec) | |
blink_off = 0.5 # duration of the LED being off while blinking (in sec) | |
cooldown = 5 # Cooldown of doing nothing after button is pressed and requests sent to server (in sec) | |
# url = "https://postb.in/VQ8OjDyK" | |
url = "https://short-edition.com/" | |
# -------------- Functions -------------- | |
def setup(): | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(pin_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) | |
GPIO.setup(pin_led, GPIO.OUT) | |
def led_on(): | |
global time_previous_blink, blinking_state | |
print("on") | |
GPIO.output(pin_led, True) | |
blinking_state = True | |
time_previous_blink = time.time() | |
def led_off(): | |
global time_previous_blink, blinking_state | |
print("off") | |
GPIO.output(pin_led, False) | |
blinking_state = False | |
time_previous_blink = time.time() | |
def main_loop(): | |
button_state = GPIO.input(pin_button) | |
# The sate goes to False when the button is pressed | |
if button_state == False: | |
on_button_pressed() | |
return | |
# If LED is on and it's time to switch off | |
if blinking_state and time_previous_blink + blink_on < time.time(): | |
led_off() | |
# If LED is off and it's time to switch on | |
elif not blinking_state and time_previous_blink + blink_off < time.time(): | |
led_on() | |
def on_button_pressed(): | |
print("Button pressed") | |
led_on() | |
t = time.time() | |
r = requests.get(url) | |
print("Status code {} in {:.0f} ms".format(r.status_code, 1000 * (time.time() - t))) | |
time.sleep(cooldown) | |
# -------------- Main -------------- | |
setup() | |
while True: | |
main_loop() | |
time.sleep(0.05) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment