5. INPUT OUTPUT DEVICE¶
Although i did all the required in week 4 because as an electronics engineer i have a good knowledge in using microcontrollers i am required to fill this part of the site
we focused on esp32 coding using thonny in micropython.
some examples :¶
Police lights using RGB-LED:¶
This basic example shows a system that receive and input and based on that input it gives you a specific output
from machine import Pin
import time
# Define the pins for the RGB LED and the fan
red_pin = Pin(13, Pin.OUT) # GPIO pin for the red color
green_pin = Pin(14, Pin.OUT) # GPIO pin for the green color
blue_pin = Pin(15, Pin.OUT) # GPIO pin for the blue color
button_pin = Pin(20, Pin.IN)
# Function to control the RGB LED colors
def set_colors(red_state, green_state, blue_state):
red_pin.value(red_state)
green_pin.value(green_state)
blue_pin.value(blue_state)
# Initial LED state
set_colors(0, 0, 0) # All LEDs off initially
# Loop to change colors when the button is pressed
while True:
if button_pin.value() == 0: # Button is pressed
for _ in range(8): # Iterate over the sequence
set_colors(1, 0, 0) # Red
time.sleep_ms(350)
set_colors(0, 0, 1) # Blue
time.sleep_ms(350)
time.sleep(0.1) # Small delay to avoid rapid checking of the button
The result:¶
Adjusting police light example¶
We can make a small adjustment where if you push the button it will start cycling through the rgb colors, this simple adjustment can open our mind to create systems that serve a purpose like using a sensor that when receiving a specific signal it give a specific output based on the condition and the pins you are using
from machine import Pin
import time
# Define the pins for the RGB LED and the button
red_pin = Pin(13, Pin.OUT) # GPIO pin for the red color
green_pin = Pin(14, Pin.OUT) # GPIO pin for the green color
blue_pin = Pin(15, Pin.OUT) # GPIO pin for the blue color
button_pin = Pin(20, Pin.IN) # GPIO pin for the button
# RGB color states
OFF = (0, 0, 0)
RED = (1, 0, 0)
GREEN = (0, 1, 0)
BLUE = (0, 0, 1)
YELLOW = (1, 1, 0)
CYAN = (0, 1, 1)
MAGENTA = (1, 0, 1)
WHITE = (1, 1, 1)
colors = [OFF, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, WHITE]
current_color = 0
button_press_count = 0
# Function to set the RGB LED color
def set_color(color):
red_pin.value(color[0])
green_pin.value(color[1])
blue_pin.value(color[2])
while True:
if button_pin.value() == 0: # Button press detected
button_press_count += 1
current_color += 1
if current_color >= len(colors):
current_color = 0
set_color(colors[current_color])
time.sleep(0.5) # Delay to debounce the button press
if button_press_count == 8:
set_color(OFF)
button_press_count = 0
time.sleep(0.1) # Small delay to avoid rapid checking of the button
The result :