All of these peripherals are connected to programmable logic. This means controllers must be implemented in an overlay before these peripherals can be used. The base overlay contains controllers for all of these peripherals.
Note that there are additional push-buttons and LEDs on the board (e.g. power LED, reset button). They are not user accessible, and are not highlighted in the figure.
Using the base overlay, each of the highlighted devices can be controlled using their corresponding pynq classes.
To demonstrate this, we will first download the base overlay to ensure it is loaded, and then import the LED, RGBLED, Switch and Button classes from the module pynq.board
.
In [1]:
from pynq import Overlay
from pynq.board import LED
from pynq.board import RGBLED
from pynq.board import Switch
from pynq.board import Button
Overlay("base.bit").download()
In [2]:
led0 = LED(0)
In [3]:
led0.on()
Check the board and confirm the LD0 is ON
In [4]:
led0.off()
Let’s then toggle led0 using the sleep() method to see the LED flashing.
In [5]:
import time
from pynq.board import LED
from pynq.board import Button
led0 = LED(0)
for i in range(20):
led0.toggle()
time.sleep(.1)
In [6]:
MAX_LEDS = 4
MAX_SWITCHES = 2
MAX_BUTTONS = 4
leds = [0] * MAX_LEDS
switches = [0] * MAX_SWITCHES
buttons = [0] * MAX_BUTTONS
for i in range(MAX_LEDS):
leds[i] = LED(i)
for i in range(MAX_SWITCHES):
switches[i] = Switch(i)
for i in range(MAX_BUTTONS):
buttons[i] = Button(i)
It will be useful to be able to turn off selected LEDs so we will create a helper function to do that. It either clears the LEDs whose numbers we list in the parameter, or by default clears LD3-LD0.
In [7]:
# Helper function to clear LEDs
def clear_LEDs(LED_nos=list(range(MAX_LEDS))):
"""Clear LEDS LD3-0 or the LEDs whose numbers appear in the list"""
for i in LED_nos:
leds[i].off()
clear_LEDs()
First, all LEDs are set to off. Then each switch is read, and if in the on position, the corresponding led is turned on. You can execute this cell a few times, changing the position of the switches on the board.
In [8]:
clear_LEDs()
for i in range(MAX_LEDS):
if switches[i%2].read():
leds[i].on()
else:
leds[i].off()
The last example toggles an led (on or off) if its corresponding push button is pressed for so long as SW0 is switched on.
To end the program, slide SW0 to the off position.
In [9]:
import time
clear_LEDs()
while switches[0].read():
for i in range(MAX_LEDS):
if buttons[i].read():
leds[i].toggle()
time.sleep(.1)
clear_LEDs()