Raspberry Pi - LED - Blink Without Delay

Let us envision that Raspberry Pi is required to accomplish two tasks: blinking an LED and monitoring the state of a button which can be pressed at any time. If we utilize the time.sleep() function (as discussed in a previous tutorial), Raspberry Pi may not detect some of the button presses. In other words, Raspberry Pi is unable to completely carry out the second task.

This tutorial instructs you how Raspberry Pi can blink an LED and monitor the state of a button without missing any pressing events.

We will go over three examples and compare the distinctions between them:

This method is not only limited to blinking LED and checking the button's state. It allows Raspberry Pi to carry out multiple tasks simultaneously without interfering with each other.

Hardware Preparation

1×Raspberry Pi 4 Model B
1×LED
1×220 ohm resistor
1×Breadboard-mount Button with Cap
1×Breadboard-mount Button Kit
1×Panel-mount Push Button
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case for Raspberry Pi 4B

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of LED and Button

If you are unfamiliar with LED and button (including pinout, functionality, and programming), the following tutorials can provide guidance:

Wiring Diagram

The wiring diagram between Raspberry Pi and LED

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code - With Delay

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file led_blink_with_delay.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-led-blink-without-delay """ import RPi.GPIO as GPIO import time # Constants won't change: LED_PIN = 18 # the number of the LED pin BUTTON_PIN = 16 # the number of the button pin BLINK_INTERVAL = 1 # interval at which to blink LED (seconds) # Variables will change: led_state = False # led_state used to set the LED prev_button_state = False # will store last time button was updated GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) try: while True: # if the LED is off turn it on and vice-versa: led_state = not led_state # set the LED with the led_state of the variable: GPIO.output(LED_PIN, led_state) time.sleep(BLINK_INTERVAL) # If button is pressed during this time, Raspberry Pi CANNOT detect button_state = GPIO.input(BUTTON_PIN) if button_state != prev_button_state: # print out the state of the button: print(button_state) # save the last state of the button prev_button_state = button_state # DO OTHER WORKS HERE except KeyboardInterrupt: GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 led_blink_with_delay.py
  • Press the button four times.
  • Check out the LED; it will alternate between being on and off every second.
  • Look at the output in the Terminal.
PuTTY - Raspberry Pi
1 0
  • On the terminal, some pressing times were not recorded. This is due to the fact that Raspberry Pi is unable to do anything during delay time, thus it is not able to detect the pressing event.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Raspberry Pi Code - Without Delay

Detailed Instructions

  • Create a Python script file led_blink_without_delay.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-led-blink-without-delay """ import RPi.GPIO as GPIO import time # Constants won't change LED_PIN = 18 # The GPIO number of the LED pin BUTTON_PIN = 16 # The GPIO number of the button pin BLINK_INTERVAL_MS = 500 # Interval at which to blink LED (milliseconds) - 500 milliseconds # Variables will change led_state = GPIO.LOW # led_state used to set the LED prev_button_state = GPIO.LOW # Will store the last time button was updated # Function to get the current time in milliseconds def millis(): return time.perf_counter_ns() // 1000000 # Get the initial time in milliseconds previousTime = millis() # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) try: while True: # Check if it's time to blink the LED currentTime = millis() if currentTime - previousTime >= BLINK_INTERVAL_MS: # If the LED is off, turn it on, and vice-versa led_state = not led_state # Set the LED with the led_state variable GPIO.output(LED_PIN, led_state) # Save the last time you blinked the LED previousTime = currentTime # Check button state's change button_state = GPIO.input(BUTTON_PIN) if button_state != prev_button_state: # Print out the state of the button print(button_state) # Save the last state of the button prev_button_state = button_state # DO OTHER WORKS HERE (IF NEEDED) except KeyboardInterrupt: # Clean up GPIO on keyboard interrupt GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 led_blink_without_delay.py
  • Press the button 4 times.
  • Check out the LED, which will alternate between ON and OFF every second.
  • Check the output in the Terminal.
PuTTY - Raspberry Pi
1 0 1 0 1 0 1 0
  • All pressed events were identified while the led was blinking.

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Video Tutorial

Extendability

This method allows Raspberry Pi to carry out multiple tasks concurrently without interfering with each other. For instance, sending a request to the Internet and waiting for the response, while at the same time blinking some LED indicators and checking the cancel button.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!