So i want to create a system in Raspberry Pi using Python to tell through telegram notification and LED if the switch button has been "ON" for 5 seconds, but I stuck in make the program for counting 5 second if the switch button has been on. My Python code so far is:
import RPi.GPIO as io
from telethon import TelegramClient
api_id = ******
api_hash = "*********************"
client = TelegramClient('anon', api_id, api_hash)
io.setmode(io.BCM)
io.setwarnings(False)
io.setup(4, io.IN, pull_up_down=io.PUD_UP)
io.setup(24, io.OUT)
while True:
if io.input(4) == 1:
if time.time(5):
io.output(24, 1)
me = client.get_me()
client.send_message('test', 'The switch button has been ON for 5 seconds')
else:
pass
else:
pass
How to modify the program to if the switch has been ON for 5 second, it will turn on the LED and send a notification?
2
Answers
time.time()
simply returns the number of seconds since epoch time. So to know whether or not 5 seconds has passed, you need to save the time when the button is pressed, then keep checking against it to see if 5 seconds has passed.This can be done either by polling or event detection. Here is how to do it by event detection, which is the more reliable method:
More info on polling and event detection: https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/
time.time() does not accept any arguments. When called, it returns
You need to count 5 seconds of elapsed time from the moment the switch is turned ON.
You need to add three variables to achieve this:
The final code would look like this (focused on logic, I am not familiar with python on Raspberry Pi):