Table of Contents

Lab 02

Exercise Objectives

WOKWI

Traffic lights

You can begin from the scratch of inspire yourself from some existing project.

Tasks


Code to control three LEDs

from machine import Pin
import time
 
# create object to control the pin
led1 = Pin(0, Pin.OUT)
led2 = Pin(1, Pin.OUT)
led3 = Pin(2, Pin.OUT)
 
leds = [led1, led2, led3]
 
while True:
  for i in leds:
    i.toggle()
    time.sleep_ms(1000)

Code using state machine and timer

from machine import Pin, Timer
import time
# objects to control GPIO pins
led1 = Pin(0, Pin.OUT)
led2 = Pin(1, Pin.OUT)
led3 = Pin(2, Pin.OUT)
# global variable to keep status of machine
status = 0
# object to control Timer
timer = Timer()
 
def state(X):
  if X == 0:
    led1.on(); led2.off(); led3.off()
  elif X == 1:
    led1.on(); led2.on(); led3.off()
  elif X == 2:
    led1.off(); led2.off(); led3.on()
  elif X == 3:
    led1.off(); led2.on(); led3.off()
 
def next_state(timer):
  global status
  state(status % 4)
  status = status + 1
 
timer.init(freq=1, mode=Timer.PERIODIC, callback=next_state)

Debouncing a pin input

A pin used as input from a switch or other mechanical device can have a lot of noise on it, rapidly changing from low to high when the switch is first pressed or released. This noise can be eliminated using a capacitor (a debouncing circuit). It can also be eliminated using a simple function that makes sure the value on the pin is stable.

The following function does just this. It gets the current value of the given pin, and then waits for the value to change. The new pin value must be stable for a continuous 20ms for it to register the change. You can adjust this time (to say 50ms) if you still have noise.

from machine import Pin, Timer
 
def on_pressed(timer):
    print('pressed')
 
def debounce(pin):
    # Start or replace a timer for 50ms, and trigger on_pressed.
    timer.init(mode=Timer.ONE_SHOT, period=50, callback=on_pressed)
 
# Register a new hardware timer.
timer = Timer(0)
 
# Setup the button input pin with a pull-up resistor.
button = Pin(0, Pin.IN, Pin.PULL_UP)
 
# Register an interrupt on rising button input.
button.irq(debounce, Pin.IRQ_RISING)

Matrix keyboard (4x4)