2. The GPIO.cleanup() was not solving the problem. The keyboard interrup was not solving the problem by itself.
3. At the first iteration of the script everything was working correctly, but after the led is lighted one time at the second iteration, the GPIO.setup(38, GPIO.OUT) was lighting the led.
4. The problem was not specific to a GPIO pin but it was the same with all.
5. The problem appeared suddenly with no identified reason.
The only solutions that was working was:
1. Rebooting the pi. But again it works only for the first iteration of the script.
2. Adding the following two lines in the keaboard interrupt solved the problem definitely. Those two lines reset each pin to 0 or GPIO.LOW.
GPIO.setup(38, GPIO.OUT, initial=0) # Solved the problem
GPIO.setup(22, GPIO.OUT, initial=0) # Solved the problem
Hardware and software are:
- Raspberry pi 4.
- Raspbian version: Raspbian GNU/Linux 10 (buster).
- All update and upgrade completed.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Code: Select all
# This code activate a pin at a specific time of the day and deactivate the pin at a different time of the day
from datetime import datetime
import time as t
import RPi.GPIO as GPIO
t2 = t.time()
def setup():
# GPIO.setwarnings(False) Keyboard interrup is a better way to manage these errors
GPIO.setmode(GPIO.BOARD)
GPIO.setup(38, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
setup()
try:
while True:
elapsed_time = t.time() - t2
if elapsed_time > 10:
t2 = t.time()
if str(datetime.now())[11:16] == str("23:00"): # Pins activation 23:00
GPIO.output(38,GPIO.HIGH)
GPIO.output(22,GPIO.HIGH)
print("ledpin on")
if str(datetime.now())[11:16] == "06:00": # Pins deactivation at 06:00
GPIO.output(38,GPIO.LOW)
GPIO.output(22,GPIO.LOW)
print("ledpin off")
except KeyboardInterrupt:
GPIO.setup(38, GPIO.OUT, initial=0) # Solved the problem
GPIO.setup(22, GPIO.OUT, initial=0) # Solved the problem
GPIO.cleanup()
print("KeyboardInterrupt has been caught.")