Stem X

Getting Started with Electronics

As well as being a fully functional computer, the Raspberry Pi is a great tool to introduce yourself to the world of electronics. Through the use of the General Purpose Input/Output (GPIO) port of the Raspberry Pi, you can connect to the external world and create electronic projects very easily.

GPIO Reference

First things first, knowledge about the GPIO (General Purpose Input Output) reference is crucial for anyone working with electronic devices or microcontrollers. GPIO pins allow these devices to interact with the external world by providing the ability to receive input signals or transmit output signals. Understanding the GPIO reference, which specifies the configuration, functionality, and electrical characteristics of each GPIO pin, enables developers and engineers to correctly interface with the hardware. Without this knowledge, the risk of making errors in hardware connections or misusing GPIO pins increases, potentially leading to malfunctioning circuits or damage to the components. Hence, familiarity with the GPIO reference is vital for successful hardware integration and smooth project development.

Lesson's Overviews and Functionalities

blinking_LED.py

import RPi.GPIO as GPIOimport time
#GPIO.setwarning(False)GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.OUT)
while True: GPIO.output(18, True) time.sleep(1) GPIO.output(18, False) time.sleep(3)

To write to GPIO pins using Python, you'll first need to install the RPi.GPIO library. This library allows you to control the GPIO pins on a Raspberry Pi.

LED_button.py

import RPi.GPIO as GPIOimport time
#GPIO.setwarning(False)GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.OUT)GPIO.setup(25, GPIO.IN)
while True:    if GPIO.input(25):        GPIO.output(18, True)    else:        GPIO.output(18, False)

To write to GPIO pins using Python, you'll first need to install the RPi.GPIO library. This library allows you to control the GPIO pins on a Raspberry Pi.

stoplight.py

import time
class StopLight:    def __init__(self):        self.current_state = 'green'        self.next_transition_time = time.time() + 10 # Start with 10 seconds of green light        print("Yellow light - Prepare to stop!")            def set_state(self, state):        self.current_state = state
    def get_state(self):        return self.current_state
    def transition(self):        if self.current_state == 'green':            self.set_state('yellow')            self.next_transition_time = time.time() + 2 # 2 seconds of yellow light            print("Yellow light - Prepare to stop!")        elif self.current_state == 'yellow':            self.set_state('red')            self.next_transition_time = time.time() + 10 # 10 seconds of red light            print("Red light - Stop!")        elif self.current_state == 'red':            self.set_state('green')            self.next_transition_time = time.time() + 10 # 10 seconds of green light            print("Green light - Go!")
    def run(self):        while True:            if time.time() >= self.next_transition_time:                self.transition()
stop_light = StopLight()stop_light.run()

screen_detection.py

from PIL import Imageimport pyautoguiimport RPi.GPIO as GPIOimport time
while True:    # Load the image to be detected    image_to_detect = Image.open('/home/pi/Desktop/dog')
    # Get the screen size    screen_size = pyautogui.size()
    # Search for the image on the screen    location = pyautogui.locateOnScreen(image_to_detect, confidence=0.9)
    # Check if the image was found    if location is not None:        # Print the location of the image on the screen
        #GPIO.setwarning(False)        GPIO.setmode(GPIO.BCM)        GPIO.setup(18, GPIO.OUT)
        while True:            GPIO.output(18, True)            time.sleep(1)            GPIO.output(18, False)            time.sleep(1)
                # Get the center of the image location        center = pyautogui.center(location)                # Move the mouse cursor to the center of the image location        pyautogui.moveTo(center)    else:        # Print a message indicating that the image was not found        print("Image not found on screen")

To write this code using Python, you'll first need to install the library (at the moment it is only accesible in the StemX kits used to complete this task)

loops.py

# While loopi = 1while i <= 10:    print(i)    i += 1
# For loopfruits = ["apple", "banana", "cherry"]for fruit in fruits:    print(fruit)

variables.py

# Assigning values to variablesname = input("What is your name?")age = int(input("How old are you?"))  # Convert age to an integeris_student = True
# Printing out the variablesprint("Name:", name)print("Age:", age)print("Is Student:", is_student)
# Modifying the variablesname = "Jane"age += 1is_student = False
# Printing out the modified variablesprint("Name:", name)print("Age:", age)print("Is Student:", is_student)

api.py

import requests
city = input("Enter a City:")
# Make an API request to the OpenWeatherMap APIresponse = requests.get('https://api.openweathermap.org/data/2.5/weather?q=' + city +', &appid=APIKey_insert_here')def kelvin_to_fahrenheit (k):    f = (k -273.15) * 1.8 +32    return f
# Check if the request was successfulif response.status_code == 200:    # Print the response content (which contains the weather data)    data = response.json()    print(data)    temp = data["main"]["temp"]    print(temp)    print("In", city, "it is currently",int(kelvin_to_fahrenheit(temp)), "degrees fahrenheit")else:    # Print an error message    print('Error: Unable to fetch weather data.')

To write this code using Python, you'll first need to install the library (at the moment it is only accesible in the StemX kits used to complete this task). 

api_flights.py

import requests
# GET request exampleresponse = requests.get("https://flightapi.com/flights?source=NYC&destination=LAX&date=2022-04-15")print(response.json())
# POST request exampledata = {    "source": "JFK",    "destination": "LHR",    "date": "2022-07-01",    "passengers": 2,    "class": "business"}headers = {    "Authorization": "Bearer YOUR_API_KEY"}response = requests.post("https://flightapi.com/bookings", json=data, headers=headers)

print(response.json())

To write this code using Python, you'll first need to install the library (at the moment it is only accesible in the StemX kits used to complete this task). 

conditional_statements.py

# If statementx = 10if x > 0:    print("x is positive")
# If-else statementy = -5if y > 0:    print("y is positive")else:    print("y is not positive")
# If-elif-else statementz = 0if z > 0:    print("z is positive")elif z < 0:    print("z is negative")else:    print("z is zero")

StemX Final Project: dump1090_interactive_flights.py

To write this code using Python, you'll first need to install the library (at the moment it is only accesible in the StemX kits used to complete this task).

import urllib.request, json#import telepotfrom time import sleepimport timeimport RPi.GPIO as GPIO
#GPIO.setwarning(False)GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.OUT)
dumpur1 = "http://localhost:8081/data.json"#the goal is to blink light if plane is over 7000
with urllib.request.urlopen(dumpur1) as url:    aircraft_json = json.loads(url.read().decode())    print(len(aircraft_json), "planes in the air")        altitudes = []    plane_num = 1    for airplane in aircraft_json:        altitudes.append(airplane["altitude"])        question = print("Plane #", plane_num,": ", airplane["hex"])        plane_num += 1    p = int(input('Enter wanted plane number or 0 to end: '))        while p > 0:                print("Plane #", p, "has an altitude of", altitudes[p - 1], "ft")        if altitudes[p - 1] <= 800:            while True:                GPIO.output(18, True)                time.sleep(0.125)                GPIO.output(18, False)                time. sleep(0.125)        elif altitudes [p - 1] <= 2500:            while True:                GPIO.output(18, True)                time.sleep(1)                GPIO.output(18, False)                time.sleep(1)        elif altitudes[p - 1] <= 7500:            while True:                GPIO.output(18, True)                time.sleep(3)                GPIO.output(18, False)                time.sleep(3)        elif altitudes[p - 1] <= 30000:            while True:                GPIO.output(18, True)                time.sleep(6)                GPIO.output(18, False)                time.sleep(6)        else:            GPIO.output(18, True)        p = int(input('Enter wanted plane number or type "END" to end: '))
dump1090_pt2.mp4
StemX Final Pres.

Program Feedback Forms

Gmail - Miami EdTech Curriculum Feedback - Stemx1.pdf
Gmail - Miami EdTech Curriculum Feedback - Stemx2.pdf
Gmail - Miami EdTech Curriculum Feedback - Stemx3.pdf