Exmaple programs

# Powering on an LED

import RPi.GPIO as gpio
import time
led_pin = 17 # setting the GPIO number we used on the board
gpio.setmode(gpio.BCM) # setting the right numeration of the GPIO's
gpio.setup(led_pin, gpio.OUT) # gpio.OUT / gpio.IN (setting a certain GPIO to output / input)

for x in range(10):
    gpio.output(led_pin, gpio.HIGH) # HIGH means powering on the LED
    time.sleep(1)
    gpio.output(led_pin, gpio.LOW) # LOW means powering off the LED
    time.sleep(1)

gpio.cleanup() # resetting the GPIO settings to prevent damage                                        
                                    

# Powering on an LED when a button is pressed

import RPi.GPIO as gpio
import time
led_pin = 17
button_pin = 26
gpio.setmode(gpio.BCM)
gpio.setup(led_pin, gpio.OUT)
gpio.setup(button_pin, gpio.IN)

while True:
    print(gpio.input(button_pin))
    if gpio.input(button_pin): # checking if button is pressed
        gpio.output(led_pin, gpio.HIGH)
    else:
        gpio.output(led_pin, gpio.LOW)
    time.sleep(0.01) # reducing CPU usage

gpio.cleanup()                                        
                                    

# Powering on one LED after another when a button is pressed (and turning off the previous one) - three LEDs

import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
pins = [17, 27, 22] # three LEDs
for x in pins:
gpio.setup(x, gpio.OUT)
gpio.output(x, gpio.LOW)

button_pin = 26
gpio.setup(button_pin, gpio.IN)
previous_state_button = gpio.input(button_pin)
led_index = 0

while True:
    time.sleep(0.1)
    button_state = gpio.input(button_pin)
    if button_state != previous_state_button: # checking if button state changed
        previous_state_button = button_state
        if button_state:
            for x in pins:
                if pins.index(x) == led_index:
                    gpio.output(x, gpio.HIGH)
                else:
                    gpio.output(x, gpio.LOW)
            led_index += 1
            if led_index >= len(pins):
                led_index = 0

gpio.cleanup()                                        
                                    

# Using the camera

from picamera import PiCamera
import time

camera = PiCamera()
camera.resolution = (1280, 720)
camera.rotation = 180
time.sleep(2) # allowing the camera time to calibrate

file_name = "/home/pi/camera/image.jpg" # an absolute path for image
camera.capture(file_name)
print("The image is done.")

file_name_2 = "/home/pi/camera/vid.h264" # an absolute path for video
camera.start_recording(file_name_2)
camera.wait_recording(5) # recording for 5 seconds
camera.stop_recording()
print("The video is done.")                                     
                                    

# Sending emails

import yagmail

with open("/home/pi/.local/share/.email_password", "r") as file:
    password = file.read().strip() # this ensures no extra spaces

yag = yagmail.SMTP("cpucademy.sender@gmail.com", password)
yag.send(to = "youremail@gmail.com", subject = "Raspberry Pi Email", contents = "Hello World!", attachments = "/home/pi/file.txt")
print("Email sent")                                        
                                    

*To use this, create an email address, enable 2-step verification, and search for app passwords. Generate one for the Raspberry Pi and copy it. Create a hidden file with the name and the path, like in the example above, and paste the password inside it. Now, everything will work.


# Creating a local server

from flask import Flask
import RPi.GPIO as gpio

button_pin = 26
gpio.setmode(gpio.BCM)
gpio.setup(button_pin, gpio.IN)

# 0.0.0.0:8500 - 0.0.0.0 is the local IP address and 8500 is the port (you can use a different port number).
# We can open this website in a browser of a device connected to the same network like this: [pi_public_IP_address]:[the_port_number].

app = Flask(__name__) # initializing

@app.route("/") # homepage route
def index():
    return "Hello World!"

@app.route("/push-button") # button status route (a subpage)
def push_button(): # the name of the function doesn't have to be the same as the route
    if gpio.input(button_pin) == gpio.HIGH:
        return "Button is pressed."
    return "Button is not pressed."

try:
    app.run(host = "0.0.0.0", port = 8500) # running the server on port 8500
finally:
    gpio.cleanup()                                        
                                    

# Turning the LEDs on and off based on the website subpage opened

from flask import Flask
import RPi.GPIO as gpio

led_pins = [17, 22, 27]
gpio.setmode(gpio.BCM)

for x in led_pins:
    gpio.setup(x, gpio.OUT)
for x in led_pins:
    gpio.output(x, gpio.LOW)

app = Flask(__name__)
@app.route("/")
def index():
    return "LEDs"

@app.route("/led/<int:led_pin>/state/<int:led_state>") # URL format for controlling LEDs
def trigger_led(led_pin, led_state):
    if led_pin not in led_pins:
        return "Wrong GPIO number"
    if led_state == 1:
        gpio.output(led_pin, gpio.HIGH)
    elif led_state == 0:
        gpio.output(led_pin, gpio.LOW)
    else:
        return "State must be 0 or 1"
    return f"{led_pin} LED is {'on' if led_state == 1 else 'off'}"

app.run(host = "0.0.0.0") # running the server
gpio.cleanup()                                        
                                    

We should always place the code in the try block and the gpio.cleanup() method in the main and the except block. This way, we will prevent not executing this method by killing the program.