write a python program which runs on a raspberry pi and controls a LED connected to the…
- User
write a python program which runs on a raspberry pi and controls a LED connected to the raspberry pi via gpio
- Assistant
To create a Python program that controls an LED connected to a Raspberry Pi via GPIO, you'll need to install the RPi.GPIO library if you haven't already. You can do this by running the following command in the terminal:
bashsudo apt-get update sudo apt-get install python3-rpi.gpioOnce you have the library installed, you can use the following Python code to control an LED connected to a GPIO pin:
pythonimport RPi.GPIO as GPIO import time # Set the GPIO numbering mode GPIO.setmode(GPIO.BCM) # Set up the GPIO channel LED_PIN = 18 # Replace with the GPIO pin number connected to the LED GPIO.setup(LED_PIN, GPIO.OUT) try: while True: # Turn the LED on GPIO.output(LED_PIN, GPIO.HIGH) print("LED is on") time.sleep(1) # Delay for 1 second # Turn the LED off GPIO.output(LED_PIN, GPIO.LOW) print("LED is off") time.sleep(1) # Delay for 1 second except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly print("Program ended") finally: # Clean up the GPIO settings GPIO.cleanup()Replace
LED_PINwith the GPIO pin number that your LED is connected to. The code will turn the LED on and off every second. Press CTRL+C to stop the program.Before running the code, ensure that your LED is properly connected to the Raspberry Pi. Connect the LED's longer leg (anode) to the GPIO pin and the shorter leg (cathode) to a ground (GND) pin on the Raspberry Pi. You may also need to add a resistor (220-1k Ohm) in series with the LED to limit the current.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.