Digital Output
Let's blink a LED!
Here's the bread board layout. The resistor can be something around 1kOhm. We don't need to make the LED super bright.
First, let's do things interactively so you can see how it all works one line at a time. Start by launching Python:
python3
Then, at the Python >>> prompt, enter the following to import the needed modules:
import board import digitalio
Next we'll create our LED digital pin and set the mode to output:
led = digitalio.DigitalInOut(board.C0) led.direction = digitalio.Direction.OUTPUT
And that should be it. You should be able to turn ON the LED with:
led.value = True
And turn it OFF with:
led.value = False
And here's a complete blink program you can run to make the LED blink forever.
import time import board import digitalio led = digitalio.DigitalInOut(board.C0) led.direction = digitalio.Direction.OUTPUT while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5)
Save it as something like blink.py and then you can run it with:
python3 blink.py
Digital Input
Let's read a button!
Here's the bread board layout. Use something like a 10kOhm resistor.
We'll do this interactively also. So launch python:
python3
Then, at the Python >>> prompt, enter the following to import the needed modules:
import board import digitalio
And now we create our button digital pin and set it to input.
button = digitalio.DigitalInOut(board.C0) button.direction = digitalio.Direction.INPUT
And that's it. To read the current state of the button use:
button.value
This will return False when the button is not pressed and True when it is pressed.
Digtal Input and Output
Ok, let's put those two together and make the button turn on the LED. So we'll use two digital pins - one will be an input (button) and one will be an output (LED).
Here's the bread board layout.
And here's the code.
import board import digitalio led = digitalio.DigitalInOut(board.C0) led.direction = digitalio.Direction.OUTPUT button = digitalio.DigitalInOut(board.C1) button.direction = digitalio.Direction.INPUT while True: led.value = button.value
Save that to a file with a name like button_and_led.py and then you can run it with:
python3 button_and_led.py
and the button should turn on the LED when pressed.
Text editor powered by tinymce.