Warning
This page is located in archive.

Lab 02

Exercise Objectives

  • Introduce WOKWI environment
  • Program various program to control GPIO pins

WOKWI

Traffic lights

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

Tasks

  • Connect three (different colors) LEDs to some pins. Be aware, that some of pins are GND.
  • Create the object to control Pins
  • Write program to toggle all LEDs
  • Update program to simulate traffic lights using delays
  • Update program to simulate traffic lights using timer (and state machine)

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)

courses/be2m37mam/labs/02.txt · Last modified: 2023/11/08 12:16 by viteks