LOGO

Raspberry Pi LED Indicator: Email, Weather & More

March 11, 2013
Raspberry Pi LED Indicator: Email, Weather & More

Utilizing the Raspberry Pi for Indicator Lights

The Raspberry Pi presents an ideal, small-form-factor platform for integrating an indicator light into a diverse range of projects. These projects can include weather alerts, notifications of new emails, and many other applications.

Connecting an LED Module

This guide details the process of connecting an LED module to your Raspberry Pi. We will also demonstrate how to configure fundamental notifications.

Successfully interfacing an LED module allows for visual signaling based on various events. This provides a convenient and easily observable status indicator.

Setting Up Basic Notifications

The following steps will enable you to establish basic notification functionality. This will allow the LED to illuminate or change state based on pre-defined conditions.

Configuration involves software setup on the Raspberry Pi to monitor for specific events and trigger the LED accordingly.

With a properly configured system, the LED will serve as a clear visual cue for important updates or changes in system status.

The Appeal of This Project

The primary motivation for undertaking this endeavor is enjoyment. Unlike many instructional guides that begin with a detailed explanation of the advantages a project offers, this one requires a brief introduction because the core benefit lies in the pleasure of creation.

The Raspberry Pi serves as an ideal platform for exploration, experimentation with electronic components, and the acquisition of programming skills. A device indicating ambient rainfall in the kitchen, while not essential, provides a rewarding challenge and a helpful cue to remember an umbrella during inclement weather.

A Platform for Learning

This project is an excellent opportunity to expand your knowledge. It allows for hands-on experience with both hardware and software.

The Raspberry Pi’s versatility makes it suitable for a wide range of projects, fostering a deeper understanding of technology.

The Joy of Creation

Sometimes, the value isn't in the utility of the final product. It's in the process of building something yourself.

Constructing a seemingly unnecessary device like a rain indicator can be incredibly satisfying and a testament to your ingenuity.

Essential Components for the Project

To effectively participate in this guide, certain prerequisites must be met. It is presumed that you have already completed our prior tutorial, "The HTG Guide to Getting Started with Raspberry Pi," and are therefore familiar with the fundamental steps, including the installation of Raspbian on your Raspberry Pi.

For those aiming to minimize project costs, it can be stated with assurance that the latest Raspberry Pi models possess capabilities exceeding the requirements of this undertaking. We suggest utilizing an older Raspberry Pi that may be available or acquiring a used unit from an online marketplace like eBay.

Beyond a functioning Raspberry Pi with Raspbian installed, the following items are necessary:

  • 1 LedBorg module (approximately $5.00 plus $4 for shipping from the UK to the US; compatible with all Raspberry Pi versions).
  • 1 Transparent Raspberry Pi Case, designed to fit your specific Pi model, such as this case for the Raspberry Pi 1 Model B.

It's important to note that the clear or frosted case is not strictly required. However, if you are currently employing an opaque case, the LED indicator will be obscured. You will need to either create an opening in your case to allow the light to be visible or employ a GPIO extension cable with a breakout kit—similar to this product from Adafruit Industries—to connect the LedBorg to your Raspberry Pi.

While the breakout cable increases the project's cost by roughly $8, it provides greater flexibility in customizing the final product, enabling easier placement of the LED within or beneath objects you wish to illuminate.

Installing the LedBorg

Creating a custom LED indicator from individual components is achievable, and numerous online resources demonstrate this process. However, Piborg offers a readily available, cost-effective, and compact LED module – the LedBorg – which served as the foundation for our Raspberry Pi LED indicator project.

Module Installation

The installation process is straightforward, as the module is engineered for direct connection to the Raspberry Pi’s GPIO pins. Begin by completely powering down your Pi and then opening its enclosure.

Correct orientation is crucial during installation. Ensure the LedBorg icon faces the RCA connector on the Raspberry Pi board. This alignment guarantees the LedBorg’s edge is flush with the Pi board’s edge, with the extended portion of the LedBorg extending over the board, not beyond it. Refer to the image above for visual guidance.

Addressing On-Board LEDs

With the Pi case open, consider covering the integrated LED indicators located near the USB ports. This is particularly important if you are utilizing a transparent case.

Prevent potential confusion by minimizing interference from the Pi’s power and network status lights when reading the LedBorg indicator.

We applied a layer of white electrical tape to our on-board LEDs. This reduced their brightness sufficiently, allowing for reference while ensuring they remained less prominent than the LedBorg’s illumination.

Finalizing Installation

After securely installing the LedBorg and, if desired, applying electrical tape to the Pi’s LEDs, reassemble the Pi’s case. Power on your Pi before proceeding to the subsequent steps of this guide.

Installing the LedBorg Software

PiBorg offers a comprehensive software suite for the LedBorg, encompassing both a graphical user interface (GUI) controller and command-line drivers for direct access.

Prerequisites

Before proceeding, ensure you download the correct package tailored to your Rasbian version and the revision number of your Raspberry Pi board.

Raspberry Pi Revision 1 boards lack mounting holes. Revision 2 boards feature mounting holes positioned near the USB ports and between the power and HDMI connectors.

To determine your kernel version, open a terminal and execute this command:

uname -r

With both the Revision number and kernel version identified, visit the Packages section to locate the appropriate download link.

For instance, if you have a Revision 1 board running kernel 3.6.11, you would select the raspbian-2013-02-09-rev1.zip file.

Installation Process

The installation requires accessing the Raspberry Pi's terminal. Input the following commands to install the LedBorg package.

Important: Replace the URL in the third command with the correct link for your specific board and kernel combination.

mkdir ~/ledborg-setup

cd ~/ledborg-setup

wget -O setup.zip http://www.piborg.org/downloads/ledborg/raspbian-2013-02-09-rev1.zip

unzip setup.zip

chmod +x install.sh

./install.sh

Upon completion, both the GUI wrapper and the underlying drivers will be installed on your system.

Launching the GUI

An icon for the GUI wrapper will appear on your Raspbian desktop.

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-3.jpg

Clicking this icon launches the color picker interface.

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-4.jpg

Initial Testing

Verify the module's functionality by selecting a color – any color except black – to test its operation.

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-5.jpg

The LED should illuminate brightly, with the frosted case providing moderate diffusion.

Explore further by clicking "Demo Mode."

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-6.jpg

Demo Mode Features

Demo mode allows you to cycle through all available colors at adjustable speeds. You can also test the high and low output settings.

Within Demo Mode, you can configure the LedBorg as an indicator. Selecting "CPU" in the Colours section will cause the LED to change from green to yellow to red, reflecting the Raspberry Pi's processor load.

Setting the Speed to "Slow" is recommended for a more easily interpretable CPU indicator.

Command-Line Control

Beyond the GUI, you can control the LED's color directly from the terminal using RGB values.

To turn the LED off, enter the following command:

echo "000" > /dev/ledborg

The LedBorg interprets RGB values as follows: 0 represents off, 1 represents half power, and 2 represents full power.

For example, 001 sets the Red and Green channels to 0% and the Blue channel to 50%.

Using 002 results in a full-brightness blue output. Combining full power Red and Blue (202) creates a magenta color.

Next Steps

Having learned to manipulate the LED manually, the next step is to explore scripting to transform it into a dynamic indicator.

Configuring Your LedBorg as a Rain Indicator

This section details how to configure your LedBorg LED module to function as a rain indicator, utilizing weather forecast data for your specified location. A Python script will be employed to query a weather API, retrieve the probability of precipitation, and subsequently illuminate the LED in bright blue when rain is predicted.

Obtaining a Weather Underground API Key

Initially, an API access key from Weather Underground is required. The API is available for free for personal use and small-scale development projects. You can register for an API key by visiting the Weather API sign-up page.

Identifying Your City’s Weather Underground URL

After acquiring your API key, navigate to the Weather Underground website and search for the city you wish to monitor. As an example, we will use San Francisco, CA. The corresponding forecast page URL is:

http://www.wunderground.com/US/CA/San_Francisco.html

The relevant portion of this URL for our purposes is /CA/San_Francisco.html. This segment will be used to construct the API request URL.

Constructing the API Request URL

The base URL for the Weather Underground API is:

http://api.wunderground.com/api/YOUR API KEY/forecast/q/STATE/CITY.json

To generate a forecast for any US city, substitute your API key, the two-letter state code, and the city name (extracted from the Weather Underground search result URL) into this base URL.

The Python Script

With the API URL prepared, create a new text document on your Raspberry Pi using Leafpad. Paste the following Python code into the document:

from urllib2 import urlopen
import json
req = urlopen('http://api.wunderground.com/api/YOUR API KEY/forecast/q/STATE/CITY.json')
parsed_json = json.load(req)
pop = int(parsed_json['forecast']['txt_forecast']['forecastday'][0]['pop'])

# The following is a debugging value.

# Remove the hash and modify

# the integer to test

# the LED response.

# pop = 0

print 'Current chance of precipitation is {}.'.format(pop)
# The default setting activates the LED# for any rain probability exceeding 20%. You can adjust# this threshold in "if pop > 20:" as needed.
if pop > 20:
 LedBorg = open('/dev/ledborg', 'w')
 LedBorg.write('002')
 del LedBorg
 print ('Rain!')
else:
 LedBorg = open('/dev/ledborg', 'w')
 LedBorg.write('000')
 del LedBorg
 print ('No rain!')

Save the file as wunderground.py in the /home/pi/ directory.

Running the Script

Open the terminal and execute the following command:

python wunderground.py

If your API key and state/city codes are entered correctly, the script should output a response similar to this:

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-8.jpg

When precipitation is forecast for your location, the LedBorg will display the following:

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-9.jpg

Testing the Script

Rather than waiting for a rainy day, you can test the script by modifying the wunderground.py file. Replace the line pop = pop with a value greater than 20, such as 60. Remember to revert this change to pop = pop once testing is complete.

Automating with Cron

The final step involves setting up a cron job to automatically run the script at regular intervals, ensuring the LED indicator remains current. Because this task is also relevant to the email indicator, we will cover cron job setup after demonstrating the configuration of that script.

Utilizing Your LedBorg as a Gmail Notification System

The satisfaction of receiving a new email is a common experience. This section details how to configure your LedBorg to function as a visual indicator for new Gmail messages. Similar to the previous setup, we will integrate an external data source – an Atom feed in this instance – with a Python script to control the LED display.

Installing FeedParser

To enhance the capabilities of your Python environment, we need to install FeedParser. This tool facilitates the parsing of RSS and Atom feeds. Access the terminal and execute the following command:

sudo easy_install feedparser

Creating the Gmail Checking Script

With FeedParser installed, we can proceed to create the script that monitors your Gmail inbox. Open Leafpad and paste the following code into the editor. Ensure you replace the placeholder username and password with the credentials for the Gmail account you intend to monitor.

import feedparser
# Input your Gmail username and password here. Omit# the @gmail.com domain from your username.
username = "username"password = "password"
mail = int(feedparser.parse("https://" + username + ":" + password +"@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])

# This is a debugging variable.

# Remove the hash symbol and modify

# the integer to 0 or 1 to test

# the LED's behavior.

# mail = 0

if mail > 0 :LedBorg = open('/dev/ledborg', 'w')LedBorg.write('020')del LedBorgprint ('Mail!')else:LedBorg = open('/dev/ledborg', 'w')LedBorg.write('000')del LedBorgprint ('No mail!')

Save the script as gmailcheck.py. Then, in the terminal, run the following command:

python gmailcheck.py

Interpreting the Results

If unread emails are present in your Gmail inbox, the LED will illuminate in green, and a "Mail!" message will be displayed.

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-11.jpg

When new mail is detected, your LedBorg will appear as follows:

build-an-led-indicator-with-a-raspberry-pi-for-email-weather-or-anything-12.jpg

A debugging feature is included, mirroring the functionality of the rain-checking script. If you lack new emails, you can either send yourself a test email or temporarily modify the debugging line to mail = 1 (after removing the comment hash) to simulate a positive result. Remember to restore the original line after testing is complete.

Proceed to the next section of this tutorial to learn how to schedule your Gmail script for automated execution.

Automating Script Execution with Cron Jobs

Having developed two functional scripts, the next step involves configuring a cron job to ensure their continuous operation throughout the day, maintaining the LED indicator's accuracy.

Initial LED State Management

Prior to scheduling, it’s prudent to ensure the LED is initially switched off, should it have been left on from prior testing. This can be achieved via the terminal using the following command:

echo "000" > /dev/ledborg

For those unfamiliar with cron, a comprehensive guide to its usage is readily available and highly recommended before proceeding.

Accessing the Cron Editor

To access the cron editor from the command line, execute the following:

sudo crontab --e

This action will launch the Raspbian cron table within the Nano text editor. Utilize the arrow keys to navigate to the end of the file. This is where the scheduled tasks will be defined.

Scheduling the Rain Script

To automate the execution of the rain script, add the following line to the cron table:

*/5 * * * * python /home/pi/wunderground.py

Upon exiting Nano (CTRL+X), you will be prompted to save changes. Confirming will overwrite the existing cron table. This configuration instructs the script to run every five minutes indefinitely.

Scheduling the Gmail Notification Script

For more frequent updates, particularly regarding email notifications, a shorter interval is desirable. To run the Gmail check script every minute, incorporate this line into the cron table:

*/1 * * * * python /home/pi/gmailcheck.py

This ensures a rapid update cycle for email notifications.

Expanding Script Functionality

The principles demonstrated here can be applied to a wide range of Python scripts. By adapting the conditional statements within the existing scripts, and defining new variables, you can create ambient LED indicators for diverse data sources.

Any data accessible via an API – such as stock market averages, pollen counts, or Twitter mentions – can be transformed into a visually represented indicator.

Acknowledgements

The successful completion of this project was facilitated by numerous online resources. A decade of inactivity in programming necessitated a period of re-familiarization.

  • The community at /r/LearnPython provided invaluable assistance with parsing the Weather Underground API output.
  • Michael’s work at Mitch Tech simplified the parsing of the Gmail Atom feed for use with the LedBorg.
  • The Python learning modules available at Code Academy proved instrumental in refreshing my understanding of the language’s syntax and structure.
#raspberry pi#led indicator#diy electronics#python#email notification#weather notification