How to make two LEDs flash alternately on the Raspberry Pi?
You can connect the electronic components on the breadboard without a T-Cobbler. But then you need a jumper wire of type female - male for the connection to the J6 header of the Raspberry Pi, i.e. female for the Raspberry Pi and male for the breadboard.
The program code (alternately blinking LED on the Raspberry Pi)
# From here the code can be copied directly into the Python software.
# Black, colored = code and gray = explanations
#We start with importing the program modules
import RPI.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) #We set the mode to BCM
GPIO.setup(23,GPIO.OUT) #Pin 23 is an output.
GPIO.setup(24,GPIO.OUT) #Pin 24 is an output.
# The loop starts here
try:
while True: #While loop so that the program runs continuously
GPIO.output(23,GPIO.HIGH) # Turns on the LED at pin 23.
GPIO.output(24,GPIO.LOW) # Turns off the LED at pin 24.
time.sleep(1) # Wait 1 second
GPIO.output(23,GPIO.LOW) # Turns off the LED on pin 23.
GPIO.output(24,GPIO.HIGH) # Turns on the LED on pin 24.
time.sleep(1)
# Here at the end the program jumps to the start of the loop part. So..
# ...switch on the LED at pin 23.
# ... etc... etc... etc..
except KeyboardInterrupt: # With CTRL+C we interrupt the program
print ("Finished")# Write "Finished" into the shell window
GPIO.cleanup() # Exit the program
In example no. 01 Blinking LED we had implemented the infinite loop with while True and indentation of the following code lines. If you aborted this infinite loop with the key combination Ctrl-C, you will have noticed that firstly you get an error message and secondly the LED may still be on. To prevent these two unwanted effects, some lines of code have been added to this example. Before the while True loop the line try: is inserted. The colon leads to the indentation of the whole loop. If an error occurs in this loop while the program is running, there is no error message, but the program is continued at except KeyboardInterrupt:. With the print command, the end of the program is output in the Python shell (lower window at Thonny), with GPIO.cleanup(), the GPIOs (i.e. our LEDs) are switched off and released for other purposes.
Example: Traffic light cycle on Raspberry Pi
Here is a proposed solution for a traffic light cycle using the module gpiozero: