The first step with any new hardware is the 'hello world' of electronics - blinking an LED. This is very easy with CircuitPython and Raspberry Pi. We'll extend the example to also show how to wire up a button/switch and enable a pull-up resistor.
Even if you use a different library to create digital in/outs like GPIO Zero, there's a number of sensor libraries that use a digital pin for resetting, or for a chip-select. So it's good to have this part working!
Any old LED will work just fine as long as its not an IR LED (you can't see those) and a 470 to 2.2K resistor
Some tactile buttons or switches
We recommend using a breadboard and some female-male wires.
You can use a Cobbler to make this a little easier, the pins are then labeled!
Wiring
Connect the Raspberry Pi Ground pin to the blue ground rail on the breadboard.
- Connect one side of the tactile switch to Raspberry Pi GPIO #4
- Connect the other side of the tactile switch to the ground rail
- Connect the longer/positive pin of the LED to Raspberry Pi GPIO #18
- Connect the shorter/negative pin of the LED to a 470ohm to 2.2K resistor, the other side of the resistor goes to ground rail
Double-check you have the right wires connected to the right location, it can be tough to keep track of Pi pins as there are forty of them!
No additional libraries are needed so we can go straight on to the example code
However, we recommend running a pip3 update!
pip3 install --upgrade adafruit_blinka
Blinky Time!
The finish line is right up ahead, lets start with an example that blinks the LED on and off once a second (half a second on, half a second off):
import time import board import digitalio print("hello blinky!") led = digitalio.DigitalInOut(board.D18) led.direction = digitalio.Direction.OUTPUT while True: led.value = True time.sleep(0.5) led.value = False time.sleep(0.5)
Verify the LED is blinking. If not, check that it's wired to GPIO #18, the resistor is installed correctly, and you have a Ground wire to the Raspberry Pi.
Type Control-C to quit
Button It Up
Now that you have the LED working, lets add code so the LED turns on whenever the button is pressed
import time import board import digitalio print("press the button!") led = digitalio.DigitalInOut(board.D18) led.direction = digitalio.Direction.OUTPUT button = digitalio.DigitalInOut(board.D4) button.direction = digitalio.Direction.INPUT button.pull = digitalio.Pull.UP while True: led.value = not button.value # light when button is pressed!
Press the button - see that the LED lights up!
Type Control-C to quit
Text editor powered by tinymce.