Using the keyboard to put ON or OFF a LED

___________________________

Introduction

LED stands for Light-Emitting Doide and is a special type of doide which shines only if it is connected in forward bias. That is, the long pin of LED is connected to the positive terminal of the power supply and the short pin is connected to negative terminal of the power supply. To prevent the LED from being damaged as a result of excess current, a resistor should be connected in series to the LED in the circuit. Resistors restrict the flow of electricity and the level of restriction depends on the value of the resistor.

The Raspberry pi just like any computer can execute instructions with incredible amount of speed. We can use this ability to switch on and off devices like the LED.


Materials

  1. Raspberry Pi 3
  2. GPIO Extension Board
  3. GPIO Ribbon Cable
  4. 470Ω resistor
  5. Two Jumper wires
  6. LED
  7. Breadboard
  8. Keyboard

Procedure

■ Connect the GPIO Extension board to the raspberry pi using the GPIO Ribbon Cable

■ Plug GPIO Extension board fully into breadboard.

■ Connect the resistor and the LED on the breadboard in series as seen on the picture below

■ Use a jumper wire to connect GPIO 18 to one end of the resistor

■ Use a jumper wire to connect the ground (GND) to the negative short pin of the LED. Note that the negative pin of the LED is its shorter pin and the positive pin of the LED is its longer pin




Code

■ Install python keyboard module using the command pip3 install keyboard

■ Create a new file in Thonny Python IDE, and call it ledkeyboard.py or whatever you want.

■ Type in the following code and run it as admin:


from gpiozero import LED
import time
import keyboard

led = LED(18)
while True:
    try:
        if keyboard.read_key()=="h":
            led.on()
        elif keyboard.read_key()=="l":
            led.off()
    except:
        print('invalid key')
        break 

■ If the circuit is wired correctly the LED will light up when h is pressed and will go off when l is pressed.



Explaining the code

■ The following code imports the gpiozero, time and keyboard libraries.


from gpiozero import LED
import time
import keyboard

■ The following code define GPIO 18 as our LED


led = LED(18)

■ The code below within the while loop repeatly listens to key pressed events and put on the LED when h is pressed and put the LED off when l is pressed.

     
while True:
    try:
        if keyboard.read_key()=="h":
            led.on()
        elif keyboard.read_key()=="l":
            led.off()
    except:
        print('invalid key')
        break 

The video below will show you how to carry out this project