Project 11: 16×2 LCD Alarm Clock With Snooze Button

What you will need:

  • Raspberry Pi
  • Breadboard
  • 16 x 2 LCD Screen
  • 10kΩ Potentiometer
  • Active Buzzer
  • Pushbutton Switch
  • 10 Female to Male Jumper Wires
  • 9 Male to Male Jumper Wires

Instructions:

This project is designed to use the Raspberry Pi to simulate a simple alarm clock with a buzzer and a snooze button. Our project utilizes the same 16 x 2 LCD screen from our previous projects while incorporating the active piezo buzzer from Project 10. Additionally, we have inserted a pushbutton switch into our breadboard layout to act as a simple snooze button.

Because this experiment builds upon Project 9 on this website and requires the Adafruit Raspberry Pi Python Code Library, be sure to follow the instructions in our Previous Project outlining the installation procedures before you continue.

After you have populated your breadboard and cloned the Adafruit library mentioned above, use your favorite editor to create the Python script below.

#!/usr/bin/env python
#
#  alarm_clock_LCD.py
#
# A simple alarm clock using Adafruit_CharLCD module
# plus a buzzer and 16x2 LCD display. A button is connected
# to GPIO 27 to simulate a snooze function.
#
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
# The positive side of the two pin active buzzer is attached to pin 18
# and the other pin goes to ground
#
#  Copyright 2015  Ken Powers
# 

# Import the required libraries
from Adafruit_CharLCD import Adafruit_CharLCD
import time
import RPi.GPIO as GPIO

# Set some global constants
lcd = Adafruit_CharLCD()
buzzer_pin = 18
snooze_button = 27
alarm_sounding = False
RUNNING = True

# Set buzzer pin as a GPIO output and snooze button
# as an input with an internal pull-down resistor
GPIO.setup(buzzer_pin, GPIO.OUT)
GPIO.setup(snooze_button, GPIO.IN, GPIO.PUD_DOWN)

# Make the function to create a buzzing sound
# This function was originally written by Simon Monk
def buzz(pitch, duration):
	period = 1.0 / pitch
	delay = period / 2
	cycles = int(duration * pitch)
	for i in range(cycles):
		GPIO.output(buzzer_pin, True)
		time.sleep(delay)
		GPIO.output(buzzer_pin, False)
		time.sleep(delay)

# Define a function that returns a correct 24 hour result after
# snooze time has been added
def snooze(alarm):
	# Add 9 minutes to the alarm time for the snooze
	alarm += 9
	# Separate time into hours and minutes
	hours = int(alarm / 100)
	minutes = alarm - hours * 100

	# Make sure new alarm time fits 24 hour format
	if (minutes > 59):
		plushrs = int(minutes//60)
		minutes = minutes % 60
		hours = hours + plushrs
	if (hours > 23):
		hours = hours - 24

	# Reconstruct alarm time and return to main loop
	alarm = hours * 100 + minutes
	return alarm

try:
	# Get alarm time from user
	response = raw_input("Enter the alarm time in 24-Hour format HHMM: ")
	print("Alarm time has been set for %s hrs" % response)
	buzz(500,0.1)

	alarm = int(response)

	# Clear LCD screen
	lcd.clear()

	while RUNNING:
		# Continually get the time as an integer
		# Output time in 24-Hour format to the LCD
		curr_time = int(time.strftime("%H%M"))
		lcd.home()
		lcd.message("  Current Time\n")
		lcd.message(time.strftime("    %H:%M:%S\n"))

		# Trigger the buzzer function when the alarm time is reached
		# The buzzer will have two different tones just for fun
		if curr_time == alarm:
			lcd.clear()
			lcd.home()
			lcd.message("    Wake Up!")
			buzz(10,0.25)
			time.sleep(0.1)
			buzz(20,0.25)
			time.sleep(0.1)
			alarm_sounding = True

		# Check for snooze button press
		input_button = GPIO.input(snooze_button)
		if alarm_sounding == True and input_button == True:
			print('Snooze Pressed!')

			# Call function to add snooze time
			alarm = snooze(alarm)

			print('New Alarm Time Is: %s' % alarm)
			alarm_sounding = False

			# Wait until the button is released to move on
			while input_button == True:
				input_button = GPIO.input(snooze_button)
				# Let the system have a brief break
				time.sleep(0.01)

except KeyboardInterrupt:
	RUNNING = False
	print "\nQuitting"

# Clear LCD screen upon exit
# Don't forget to clean up after so we
# can use the GPIO next time
finally:
	lcd.clear()
	GPIO.cleanup()

Code Analysis:

Our Raspberry Pi Python script begins by telling the interpreter we are using the Python language. We also include some descriptive comments that help to let readers know what the script will accomplish as well as indicating what Raspberry Pi GPIO pins we are using.

#!/usr/bin/env python
#
#  alarm_clock_LCD.py
#
# A simple alarm clock using Adafruit_CharLCD module
# plus a buzzer and 16x2 LCD display. A button is connected
# to GPIO 27 to simulate a snooze function.
#
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
# The positive side of the two pin active buzzer is attached to pin 18
# and the other pin goes to ground
#
#  Copyright 2015  Ken Powers
#

Next, we import all the required function libraries, instantiate an LCD using the Adafruit library, and define some necessary constants.

# Import the required libraries
from Adafruit_CharLCD import Adafruit_CharLCD
import time
import RPi.GPIO as GPIO

# Set some global constants
lcd = Adafruit_CharLCD()
buzzer_pin = 18
snooze_button = 27
alarm_sounding = False
RUNNING = True

At this point in our script, we setup our GPIO so our buzzer pin is an OUTPUT and our snooze button is an INPUT that is utilizing an internal pull-down resistor.

# Set buzzer pin as a GPIO output and snooze button
# as an input with an internal pull-down resistor
GPIO.setup(buzzer_pin, GPIO.OUT)
GPIO.setup(snooze_button, GPIO.IN, GPIO.PUD_DOWN)

Our first function definition was written by Simon Monk and is designed to make a sound through our active buzzer.

# Make the function to create a buzzing sound
# This function was originally written by Simon Monk
def buzz(pitch, duration):
	period = 1.0 / pitch
	delay = period / 2
	cycles = int(duration * pitch)
	for i in range(cycles):
		GPIO.output(buzzer_pin, True)
		time.sleep(delay)
		GPIO.output(buzzer_pin, False)
		time.sleep(delay)

Our next function definition is used for our snooze button. If the alarm is sounding and the snooze button is depressed, this function is called.

Every alarm clock I have ever owned has had a snooze time of 9 minutes. I have no idea why 10 minutes isn’t used. This function sticks with that unusual convention and adds 9 minutes to the current alarm time.

Next, the time is broken into hours and minutes so we can ensure that the new alarm time fits standard 24-hour format conventions.

# Define a function that returns a correct 24 hour result after
# snooze time has been added
def snooze(alarm):
	# Add 9 minutes to the alarm time for the snooze
	alarm += 9
	# Separate time into hours and minutes
	hours = int(alarm / 100)
	minutes = alarm - hours * 100

	# Make sure new alarm time fits 24 hour format
	if (minutes > 59):
		plushrs = int(minutes//60)
		minutes = minutes % 60
		hours = hours + plushrs
	if (hours > 23):
		hours = hours - 24

	# Reconstruct alarm time and return to main loop
	alarm = hours * 100 + minutes
	return alarm

The main loop of our script prompts the user for their desired alarm time in 24-hour format. Our LCD screen is continually updated with the current time and the alarm buzzer is sounded if our alarm time is reached. While the alarm is sounding, a press of the snooze button calls our snooze() function and the new alarm time is returned. The entire process continues until Ctrl + C is pressed.

try:
	# Get alarm time from user
	response = raw_input("Enter the alarm time in 24-Hour format HHMM: ")
	print("Alarm time has been set for %s hrs" % response)
	buzz(500,0.1)

	alarm = int(response)

	# Clear LCD screen
	lcd.clear()

	while RUNNING:
		# Continually get the time as an integer
		# Output time in 24-Hour format to the LCD
		curr_time = int(time.strftime("%H%M"))
		lcd.home()
		lcd.message("  Current Time\n")
		lcd.message(time.strftime("    %H:%M:%S\n"))

		# Trigger the buzzer function when the alarm time is reached
		# The buzzer will have two different tones just for fun
		if curr_time == alarm:
			lcd.clear()
			lcd.home()
			lcd.message("    Wake Up!")
			buzz(10,0.25)
			time.sleep(0.1)
			buzz(20,0.25)
			time.sleep(0.1)
			alarm_sounding = True

		# Check for snooze button press
		input_button = GPIO.input(snooze_button)
		if alarm_sounding == True and input_button == True:
			print('Snooze Pressed!')

			# Call function to add snooze time
			alarm = snooze(alarm)

			print('New Alarm Time Is: %s' % alarm)
			alarm_sounding = False

			# Wait until the button is released to move on
			while input_button == True:
				input_button = GPIO.input(snooze_button)
				# Let the system have a brief break
				time.sleep(0.01)

except KeyboardInterrupt:
	RUNNING = False
	print "\nQuitting"

# Clear LCD screen upon exit
# Don't forget to clean up after so we
# can use the GPIO next time
finally:
	lcd.clear()
	GPIO.cleanup()

The addition of a snooze button to our previous project turned out to be a bit of a challenge. Making sure the adjusted alarm time remained in proper 24-hour format required a bit of thought. Enjoy the project and have fun modifying it to suit your own needs. Above all, however, have fun!

Project 9a: 16×2 LCD Stock Ticker

What you will need:

  • Raspberry Pi
  • Breadboard
  • 16 x 2 LCD Screen
  • 10kΩ Potentiometer
  • 8 Female to Male Jumper Wires
  • 7 Male to Male Jumper Wires

Instructions:

Once my son and I were able to get our 16 x 2 LCD Screen operating with the Raspberry Pi, we decided to create some simple projects that utilize it. Our first variation, uses the identical breadboard layout from Project 9 and creates a simple stock ticker by using the Yahoo! Finance API.

This project builds upon Project 9 and requires the Adafruit Raspberry Pi Python Code Library. Be sure to follow the instructions in our Previous Project outlining the installation procedures before you continue.

Once you have your breadboard populated and the Adafruit Library cloned, enter the Python script below using your favorite editor:

#!/usr/bin/env python
#
#  stock_ticker_LCD.py
#
# A short program using the Yahoo Finance API and
# Adafruit's 'Adafruit_CharLCD' library to monitor
# stock values and to
# update a 16x2 LCD display in 4 bit mode
#
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
#  Copyright 2015  Ken Powers
# 

# Import the required libraries
from Adafruit_CharLCD import Adafruit_CharLCD
import urllib2
import json
import time
import RPi.GPIO as GPIO

# Set GPIO pins to Broadcom numbering system
GPIO.setmode(GPIO.BCM)

lcd = Adafruit_CharLCD()
RUNNING = True

# Create a list of stocks to check
stocks = ("^IXIC","YHOO","AAPL","WPZ","ETE","OKE","MWE")

try:
	while RUNNING:
		# Use JSON to obtain stock information
		# using an API call to Yahoo Finance

		for i in range(len(stocks)):
			f = urllib2.urlopen('http://download.finance.yahoo.com/d/quotes.csv?s=' + stocks[i] + '&f=sghn')
			json_string = f.read()

			# Create a list from the returned information by splitting at the comma character
			stockquotes = json_string.split(",")

			# Strip the quotes from the stock name in the first item
			stockquotes[0] = stockquotes[0].strip('"')
			stockdiff = float(stockquotes[2]) - float(stockquotes[1])

			# Print the stock information to the screen
			print(stockquotes[0])
			print("Low: %s" % stockquotes[1])
			print("High: %s" % stockquotes[2])
			print(stockdiff)
			print("\n")

			# Send information to 16x2 LCD screen Using Adafruit_CharLCD
			lcd.clear()
			lcd.home()
			# Set number of columns and rows of LCD display
			lcd.begin(16,2)
			# Set cursor position and scroll info from right to left
			lcd.setCursor(17,0)
			if stockdiff > 0:
				updown = '   ^'
			else:
				updown = '   v'
			lcd.message(stockquotes[0] + updown + str(abs(stockdiff)))
			lcd.setCursor(17,1)
			ticker = ('L: ' + stockquotes[1] + '  H: ' + stockquotes[2])
			lcd.message(ticker)
			for x in range(0, len(ticker)):
				lcd.DisplayLeft()
				time.sleep(.25) 

			time.sleep(.1)
			f.close()

except KeyboardInterrupt:
	RUNNING = False
	print "\nQuitting"

# Clear LCD screen upon exit
# Don't forget to clean up after so we
# can use the GPIO next time
finally:
	lcd.clear()
	GPIO.cleanup()

Code Analysis:

As in previous projects, our Raspberry Pi’s Python script begins by letting the interpreter know which language we are using as well as providing some comments that indicate the purpose of our program. We also take some effort to make some LCD screen GPIO pin connection notes for added clarity.

#!/usr/bin/env python
#
#  stock_ticker_LCD.py
#
# A short program using the Yahoo Finance API and
# Adafruit's 'Adafruit_CharLCD' library to monitor
# stock values and to
# update a 16x2 LCD display in 4 bit mode
#
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
#  Copyright 2015  Ken Powers
#

Next, we import the required modules and libraries necessary for our script to operate properly. We also create our constants, instantiate an LCD using the Adafruit library, and create a list of the stock symbols we wish to check with our ticker. Feel free to modify this list to reflect your own stock interests.

# Import the required libraries
from Adafruit_CharLCD import Adafruit_CharLCD
import urllib2
import json
import time
import RPi.GPIO as GPIO

# Set GPIO pins to Broadcom numbering system
GPIO.setmode(GPIO.BCM)

lcd = Adafruit_CharLCD()
RUNNING = True

# Create a list of stocks to check
stocks = ("^IXIC","YHOO","AAPL","WPZ","ETE","OKE","MWE")

Our main loop simply builds a URL for each of the stock symbols in our list using the Yahoo! Finance API. It then parses the returned information, removes the quotation marks, and prints the stock information to our main screen.

Next, the loop clears our LCD screen, sets the cursor position, displays the stock information, scrolls the data to the left, and continues until Ctrl + C is pressed.

try:
	while RUNNING:
		# Use JSON to obtain stock information
		# using an API call to Yahoo Finance

		for i in range(len(stocks)):
			f = urllib2.urlopen('http://download.finance.yahoo.com/d/quotes.csv?s=' + stocks[i] + '&f=sghn')
			json_string = f.read()

			# Create a list from the returned information by splitting at the comma character
			stockquotes = json_string.split(",")

			# Strip the quotes from the stock name in the first item
			stockquotes[0] = stockquotes[0].strip('"')
			stockdiff = float(stockquotes[2]) - float(stockquotes[1])

			# Print the stock information to the screen
			print(stockquotes[0])
			print("Low: %s" % stockquotes[1])
			print("High: %s" % stockquotes[2])
			print(stockdiff)
			print("\n")

			# Send information to 16x2 LCD screen Using Adafruit_CharLCD
			lcd.clear()
			lcd.home()
			# Set number of columns and rows of LCD display
			lcd.begin(16,2)
			# Set cursor position and scroll info from right to left
			lcd.setCursor(17,0)
			if stockdiff > 0:
				updown = '   ^'
			else:
				updown = '   v'
			lcd.message(stockquotes[0] + updown + str(abs(stockdiff)))
			lcd.setCursor(17,1)
			ticker = ('L: ' + stockquotes[1] + '  H: ' + stockquotes[2])
			lcd.message(ticker)
			for x in range(0, len(ticker)):
				lcd.DisplayLeft()
				time.sleep(.25) 

			time.sleep(.1)
			f.close()

except KeyboardInterrupt:
	RUNNING = False
	print "\nQuitting"

# Clear LCD screen upon exit
# Don't forget to clean up after so we
# can use the GPIO next time
finally:
	lcd.clear()
	GPIO.cleanup()

This was a fun project because we got to see our LCD screen interact with real data from the Internet and the American stock market. Have fun fiddling with which stock data is being read as well as the way the LCD screen displays the information. Above all, however, have fun!

Project 9: 16×2 LCD Screen Test

What you will need:

  • Raspberry Pi
  • Breadboard
  • 16 x 2 LCD Screen
  • 10kΩ Potentiometer
  • 8 Female to Male Jumper Wires
  • 7 Male to Male Jumper Wires

Instructions:

My son and I recently purchased a 16×2 LCD screen and decided it was time to see if we could make it operate. Although not exact, an identically functioning screen similar to what we purchased can be found through Adafruit Industries.

The LCD screen that we found needed to have header pins soldered to it so we could use it with our breadboard. We simply snapped off 16 pins from a 0.1″ header strip, inserted the strip’s pins through the LCD screen’s board, and soldered the pins to the corresponding pads.

If you have never soldered before, this is a great opportunity to learn. There are many tutorials online that show how simple it is. Just be sure to use a minimal amount of heat from your soldering iron in order to avoid damaging the LCD screen’s board.

Once you have soldered the header pins to the LCD screen and connected it to the breadboard, make the connections shown in the breadboard layout above. This is a good time to note that the 10kΩ Potentiometer in the layout can be bypassed but is a convenient contrast control.

Be very careful when connecting all the breadboard layout’s wires as there are a lot of connections to make. Double check your work to avoid damaging your Raspberry Pi.

I should note at this time that our screen was set up to use 5 volts so we used the Raspberry Pi’s 5 volt GPIO power supply pin for the project. Make sure your LCD screen requires 5 volts before you use this pin. If in doubt, use pin 1 from the Raspberry Pi’s GPIO which only supplies 3.3 volts.

The next step necessary to get the LCD screen to work is to download Adafruit Industries’ Open Source Raspberry Pi Python Code Library. It is a growing collection of libraries and example python scripts for controlling a variety of electronics and there is an excellent selection of functions for the 16 x 2 LCD screen we are using.

The easiest way we found to download the library is to use git to clone the library to our Raspberry Pi. First, make sure you have git installed by entering the following commands from a terminal window or the Raspberry Pi’s command line:

pi@raspberrypi ~ $ sudo apt-get update
pi@raspberrypi ~ $ sudo apt-get upgrade
pi@raspberrypi ~ $ sudo apt-get install -y git dialog

My son and I had set up a projects folder on the Raspbian desktop for easy access and that is the location to which we downloaded the Adafruit library. We simply navigated to our directory from the Raspberry Pi command line by typing:

pi@raspberrypi ~ $ cd Desktop/Projects

Next, we cloned the Adafruit Raspberry Pi Python Code Library to our directory by typing:

pi@raspberrypi ~/Desktop/Projects $ git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git

The above command clones the entire library to our directory but for now we are only interested in the Adafruit_CharLCD functions. There is a directory by that name within the library and within that directory is a file named Adafruit_CharLCD.py. We want to copy that file to the same directory where we have the projects on which we have been working.

In our case, we executed a copy command from within our Projects directory which copied the file from the Adafruit directory to our main Projects folder.

pi@raspberrypi ~/Desktop/Projects $ cp Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCD/Adafruit_CharLCD.py .

Once the Adafruit_CharLCD.py file is within your projects directory, use your favorite editor to enter the following Python script:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  LCD_screen_test.py
#
# A short Python script to test a 16 x 2 LCD display
# by using the Adafruit Raspberry Pi Python Library
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
#  Copyright 2015  Ken Powers
#  

from Adafruit_CharLCD import Adafruit_CharLCD
import RPi.GPIO as GPIO
import time

# Set GPIO pins to Broadcom numbering system
GPIO.setmode(GPIO.BCM)

RUNNING = True
lcd = Adafruit_CharLCD()

lcd.clear()
lcd.message(" Nicholas\n Powers")
print("Press Ctrl + C to Quit")

# Main loop
try:
    while RUNNING:

		# Scroll LCD screen text off to the right
		for x in range (0, 16):
			lcd.scrollDisplayRight()
			time.sleep(.2)

		# Wait 2 seconds
		time.sleep(2)

		# Scroll LCD screen text back into view
		for x in range (0, 16):
			lcd.DisplayLeft()
			time.sleep(.2)

		# Wait 2 seconds
		time.sleep(2)

# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

# Actions under 'finally' will always be called
# regardless of what stopped the program
finally:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

Code Analysis:

As in previous projects, our Python script begins by letting the interpreter know what language we are using. Next, we have a series of comments designed to clarify the intention of our script and to indicate which pins from the LCD screen are attached to our Raspberry Pi’s GPIO port.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  LCD_screen_test.py
#
# A short Python script to test a 16 x 2 LCD display
# by using the Adafruit Raspberry Pi Python Library
#
# LCD Screen 16x2 Pins
# --------------------
# Pin 1  to GND
# Pin 2  to 5v
# Pin 3  to variable resistor then to GND 'Contrast Adjustment'
# Pin 4  to GPIO 25 for 'Command or Data Mode Switching'
# Pin 5  to GND for 'Read/Write Mode'
# Pin 6  to GPIO 24 for 'Enable Pin'
# Pin 7  to Not Connected
# Pin 8  to Not Connected
# Pin 9  to Not Connected
# Pin 10 to Not Connected
# Pin 11 to GPIO 23 for 'Data 4'
# Pin 12 to GPIO 17 for 'Data 5'
# Pin 13 to GPIO 21 for 'Data 6'
# Pin 14 to GPIO 22 for 'Data 7'
# Pin 15 to 5v for 'Backlight Anode' - Could use variable resistor as a 'Brightness Control'
# Pin 16 to GND for 'LED Backlight Cathode'
#
#  Copyright 2015  Ken Powers
#

Next, we import the modules our Python script will require. We also define a constant that is used to determine if our main loop will execute followed by a command to instantiate an LCD via the Adafruit functions.

from Adafruit_CharLCD import Adafruit_CharLCD
import RPi.GPIO as GPIO
import time

# Set GPIO pins to Broadcom numbering system
GPIO.setmode(GPIO.BCM)

RUNNING = True
lcd = Adafruit_CharLCD()

Next, we clear the LCD screen, by using the Adafruit library’s clear() function and display some text on the 16 x 2 LCD screen by using the message() function. In our case, we chose to display my son’s name which helped to keep him interested in the project. The \n in the text is interpreted as a return character which puts my son’s last name on the second line of the LCD screen.

lcd.clear()
lcd.message(" Nicholas\n Powers")
print("Press Ctrl + C to Quit")

Our main loop uses the Adafruit library’s scroll functions to slide our text off the screen to the right and back again until Ctrl + C is pressed. scrollDisplayRight() moves the text to the right and DisplayLeft() moves it left. The functions are inconsistently named so please note that only the first function has the word scroll in front of it.

# Main loop
try:
    while RUNNING:

		# Scroll LCD screen text off to the right
		for x in range (0, 16):
			lcd.scrollDisplayRight()
			time.sleep(.2)

		# Wait 2 seconds
		time.sleep(2)

		# Scroll LCD screen text back into view
		for x in range (0, 16):
			lcd.DisplayLeft()
			time.sleep(.2)

		# Wait 2 seconds
		time.sleep(2)

# If CTRL+C is pressed the main loop is broken
except KeyboardInterrupt:
    RUNNING = False
    print "\Quitting"

# Actions under 'finally' will always be called
# regardless of what stopped the program
finally:
    # Stop and cleanup so the pins
    # are available to be used again
    GPIO.cleanup()

The Python script above performs a very simple task but was a really fun introduction to the 16 x 2 LCD screen and Adafruit’s library of functions. There are several more functions in the library that we haven’t used yet and we may incorporate them into some of our future projects. For now, however, have fun modifying the Python script above.