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)