4 bit mode lcd 8 bit mode lcd lcd character display programming lcd python programming lcd python script raspberry pi raspberry pi lcd 16x2 raspberry pi python lcd RPLCD library Technology

How to Setup an LCD on the Raspberry Pi and Program It With Python

Raspberry Pi LCD 8 Bit Mode Connection Diagram

For those who plan on utilizing an LCD together with your Raspberry Pi, there’s a superb probability you’ll want to program it in Python sooner or later. Python might be the hottest programming language for coding on the Raspberry Pi, and lots of the tasks and examples you’ll discover are written in Python.

On this tutorial, I’ll present you ways to join your LCD and program it in Python, utilizing the RPLCD library. I’ll begin with displaying you ways to join it in both eight bit mode or four bit mode. Then I’ll clarify how to set up the library, and present examples for printing and positioning textual content, clearing the display, and controlling the cursor. I’ll additionally offer you examples for scrolling textual content, creating customized characters, printing knowledge from a sensor, and displaying the date, time, and IP handle of your Pi.

BONUS: I made a fast begin information for this tutorial that you could obtain and return to later in case you can’t set this up proper now. It covers all of the steps, diagrams, and code you want to get began.

I’m utilizing a 16X2 LCD show right here, however the examples will work with any LCD that makes use of the Hitachi HD44780 driver.

You can too join the LCD by way of I2C, which makes use of solely two wires, however it requires some additional hardware. Take a look at our article, How to Setup an I2C LCD on the Raspberry Pi to see how.

I additionally go over how to program the LCD with C in one other article, however for now let’s focus on Python…

Right here is the video model of this tutorial, the place you possibly can watch all of the instance packages under in actual time:

Connecting the LCD

There are two methods to join the LCD to your Raspberry Pi – in four bit mode or eight bit mode. four bit mode makes use of 6 GPIO pins, whereas eight bit mode makes use of 10. Because it makes use of up much less pins, four bit mode is the commonest technique, however I’ll clarify how to arrange and program the LCD each methods.

Every character and command is shipped to the LCD as a byte (eight bits) of knowledge. In eight bit mode, the byte is shipped abruptly via eight knowledge wires, one bit per wire. In four bit mode, the byte is cut up into two units of four bits – the higher bits and decrease bits, that are despatched one after the different over four knowledge wires.

Theoretically, eight bit mode transfers knowledge about twice as quick as four bit mode, since the complete byte is shipped all of sudden. Nevertheless, the LCD driver takes a comparatively very long time to course of the knowledge, so regardless of which mode is getting used, we don’t actually discover a distinction in knowledge switch velocity between eight bit and four bit modes.

Wiring the LCD in eight Bit Mode

To attach your LCD in eight bit mode set it up like this:

Raspberry Pi LCD 8 Bit Mode Connection Diagram

The backlight and distinction potentiometers are 10Okay Ohms, however they are often substituted with 1K to 3K Ohm resistors if you need.

Wiring the LCD in four Bit Mode

To attach the LCD to your Raspberry Pi in four bit mode, set it up like this:

Raspberry Pi LCD 4 bit modeRaspberry Pi LCD 4 bit mode

The potentiometers right here may also be substituted with 1K or 3K Ohm resistors.

Programming the LCD With Python

If that is your first time writing and operating a Python program, you may want to learn How to Write and Run a Python Program on the Raspberry Pi, which can clarify every thing you want to know to run the examples under.

We’ll be utilizing a Python library that gives a variety of helpful features. Its referred to as the RLPCD library, and was written by Danilo Bargen.

Putting in the RPLCD Library

The RPLCD library might be put in from the Python Package deal Index, or PIP. It may already be put in on your Pi, but when not, enter this at the command immediate to set up it:

sudo apt-get set up python-pip

After you get PIP put in, set up the RPLCD library by getting into:

sudo pip set up RPLCD

The instance packages under use the Raspberry Pi’s bodily pin numbers, not the BCM or GPIO numbers. I’m assuming you will have your LCD related the approach it’s in the diagrams above, however I’ll present you ways to change the pin connections should you want to.

Write to the Show in eight Bit Mode

Let’s begin with a easy program that may show “Hello world!” on the LCD. When you’ve got a special sized LCD than the 16×2 I’m utilizing (like a 20×four), change the variety of columns and rows in line 2 of the code. cols= units the variety of columns, and rows= units the variety of rows. You may also change the pins used for the LCD’s RS, E, and knowledge pins. The info pins are set as pins_data=[D0, D1, D2, D3, D4, D5, D6, D7].

Textual content strings are written to the show utilizing the liquid crystal display.write_string() perform:

from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23])
liquid crystal display.write_string(u’Hey world!’)

Write to the Show in four Bit Mode

In four bit mode, solely LCD pins D4, D5, D6, and D7 are used for knowledge. These are set in pins_data=[D4, D5, D6, D7] on line 2 under:

from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])
liquid crystal display.write_string(u’Hiya world!’)

Place the Textual content

The textual content could be positioned anyplace on the display utilizing liquid crystal display.cursor_pos = (ROW, COLUMN). The rows are numbered ranging from zero, so the prime row is row Zero, and the backside row is row 1. Equally, the columns are numbered beginning at zero, so for a 16×2 LCD the columns are numbered Zero to 15. For instance, the code under locations “Hello world!” beginning at the backside row, fourth column:

from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

liquid crystal display.cursor_pos = (1, three)
liquid crystal display.write_string(u’Howdy world!’)

Clear the Display

The perform liquid crystal display.clear() will clear the display. The next code will print “Hello world!” to the display for 2 seconds earlier than clearing it:

import time
from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

liquid crystal display.write_string(u’Hey world!’)
time.sleep(2)
liquid crystal display.clear()

Blinking Textual content

Combining liquid crystal display.clear() and time.sleep() shortly loop will produce a blinking textual content impact:

import time
from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

whereas True:
liquid crystal display.write_string(u”Hello world!”)
time.sleep(1)
liquid crystal display.clear()
time.sleep(1)

Press Ctrl-C to exit the program.

Flip the Cursor On and Off

The RPLCD library offers a number of features for controlling the cursor. You possibly can have a block cursor, an underline cursor, or a blinking cursor. Use the following features to set the cursor:

  • Blinking block cursor: liquid crystal display.cursor_mode = CursorMode.blink
  • Line cursor: liquid crystal display.cursor_mode = CursorMode.line
  • Cursor off: liquid crystal display.cursor_mode = CursorMode.cover

The code under locations a blinking cursor after the final character of textual content:

from RPLCD import CharLCD
from RPLCD import CursorMode
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

liquid crystal display.write_string(u’Hiya world!’)

liquid crystal display.cursor_mode = CursorMode.blink
#liquid crystal display.cursor_mode = CursorMode.line
#liquid crystal display.cursor_mode = CursorMode.disguise

Line Breaks

Textual content will routinely wrap to the subsequent line if the size of the textual content is bigger than the column size of your LCD. You may as well management the place the textual content string breaks to the subsequent line by inserting nr the place you need the break to happen. The code under will print “Hello” to the prime row, and “world!” to the backside row.

from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

liquid crystal display.write_string(u’Hellonrworld!’)

Print the Date and Time

This program will show the date and time on the LCD:

from RPLCD import CharLCD
import time
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

whereas True:
liquid crystal display.write_string(“Time: %s” %time.strftime(“%H:%M:%S”))

liquid crystal display.cursor_pos = (1, Zero)
liquid crystal display.write_string(“Date: %s” %time.strftime(“%m/%d/%Y”))

Print Your IP Handle

This program will print the IP tackle of your ethernet connection to the LCD. To print the IP of your WiFi connection, simply change eth0 in line 19 to wlan0:

from RPLCD import CharLCD
import socket
import fcntl
import struct

liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915,
struct.pack(‘256s’, ifname[:15])
)[20:24])

liquid crystal display.write_string(“IP Address:”)

liquid crystal display.cursor_pos = (1, Zero)
liquid crystal display.write_string(get_ip_address(‘eth0’))

Customized Characters

Every character on the LCD is an array of 5×eight of pixels. You possibly can create any sample or character you possibly can consider, and show it on the display as a customized character. Take a look at this web site for an interactive software that creates the bit array used to outline customized characters.

First we outline the character in strains four to 12 of the code under. Then we use the perform liquid crystal display.create_char(Zero-7, NAME) to retailer the character in the LCD’s CGRAM reminiscence. Up to eight (Zero-7) characters could be saved at a time. To print the customized character, we use liquid crystal display.write_string(unichr(Zero)), the place the quantity in unichr() is the reminiscence location (Zero-7) outlined in liquid crystal display.create_char().

Printing a Single Customized Character

Check out this code, which prints a single smiley face character to the show:

from RPLCD import CharLCD, cleared, cursor
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

smiley = (
0b00000,
0b01010,
0b01010,
0b00000,
0b10001,
0b10001,
0b01110,
0b00000,
)
liquid crystal display.create_char(Zero, smiley)
liquid crystal display.write_string(unichr(Zero))

Printing A number of Customized Characters

This program will print the Greek letters omega, pi, and mu, together with symbols for temperature (a thermometer) and humidity (a water drop):

from RPLCD import CharLCD, cleared, cursor
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

omega = (
0b00000,
0b01110,
0b10001,
0b10001,
0b10001,
0b01010,
0b11011,
0b00000,
)

pi = (
0b00000,
0b00000,
0b11111,
0b01010,
0b01010,
0b01010,
0b10011,
0b00000,
)

mu = (
0b00000,
0b10010,
0b10010,
0b10010,
0b10010,
0b11101,
0b10000,
0b10000,
)

drop = (
0b00100,
0b00100,
0b01010,
0b01010,
0b10001,
0b10001,
0b10001,
0b01110,
)

temp = (
0b00100,
0b01010,
0b01010,
0b01110,
0b01110,
0b11111,
0b11111,
0b01110,
)

liquid crystal display.create_char(Zero, omega)
liquid crystal display.create_char(1, pi)
liquid crystal display.create_char(2, mu)
liquid crystal display.create_char(three, drop)
liquid crystal display.create_char(four, temp)

liquid crystal display.write_string(unichr(Zero))
liquid crystal display.write_string(unichr(1))
liquid crystal display.write_string(unichr(2))
liquid crystal display.write_string(unichr(three))
liquid crystal display.write_string(unichr(four))

Scrolling Textual content

This program scrolls textual content from proper to left in an infinite loop:

framebuffer = [
”,
”,
]

def write_to_lcd(liquid crystal display, framebuffer, num_cols):
liquid crystal display.residence()
for row in framebuffer:
liquid crystal display.write_string(row.ljust(num_cols)[:num_cols])
liquid crystal display.write_string(‘rn’)

from RPLCD import CharLCD
liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])
write_to_lcd(liquid crystal display, framebuffer, 16)

import time
long_string = ‘This string is just too lengthy to match’

def loop_string(string, liquid crystal display, framebuffer, row, num_cols, delay=Zero.5): #DELAY= CONTROLS THE SPEED OF SCROLL
padding = ‘ ‘ * num_cols
s = padding + string + padding
for i in vary(len(s) – num_cols + 1):
framebuffer[row] = s[i:i+num_cols] write_to_lcd(liquid crystal display, framebuffer, num_cols)
time.sleep(delay)

whereas True:
loop_string(long_string, liquid crystal display, framebuffer, 1, 16)

You possibly can change the scroll velocity in delay=Zero.5 (line 19).

Print Knowledge from a Sensor

To exhibit how to print knowledge from a sensor, right here’s a program that shows the temperature from a DS18B20 Digital Temperature Sensor. There’s some arrange to do earlier than you will get this to work on the Raspberry Pi, so take a look at our tutorial on the DS18B20 to see how.

Normally, you’re taking the enter variable out of your sensor and convert it to an integer to carry out any calculations. Then convert the end result to a string, and output the string to the show utilizing liquid crystal display.write_string(sensor_data()):

import os
import glob
import time
from RPLCD import CharLCD

liquid crystal display = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23])

os.system(‘modprobe w1-gpio’)
os.system(‘modprobe w1-therm’)

base_dir = ‘/sys/bus/w1/units/’
device_folder = glob.glob(base_dir + ’28*’)[0] device_file = device_folder + ‘/w1_slave’

def read_temp_raw():
f = open(device_file, ‘r’)
strains = f.readlines()
f.shut()
return strains

#CELSIUS CALCULATION
def read_temp_c():
strains = read_temp_raw()
whereas strains[0].strip()[-3:] != ‘YES’:
time.sleep(Zero.2)
strains = read_temp_raw()
equals_pos = strains[1].discover(‘t=’)
if equals_pos != -1:
temp_string = strains[1][equals_pos+2:] temp_c = int(temp_string) / 1000.Zero # TEMP_STRING IS THE SENSOR OUTPUT, MAKE SURE IT’S AN INTEGER TO DO THE MATH
temp_c = str(spherical(temp_c, 1)) # ROUND THE RESULT TO 1 PLACE AFTER THE DECIMAL, THEN CONVERT IT TO A STRING
return temp_c

#FAHRENHEIT CALCULATION
def read_temp_f():
strains = read_temp_raw()
whereas strains[0].strip()[-3:] != ‘YES’:
time.sleep(Zero.2)
strains = read_temp_raw()
equals_pos = strains[1].discover(‘t=’)
if equals_pos != -1:
temp_string = strains[1][equals_pos+2:] temp_f = (int(temp_string) / 1000.Zero) * 9.Zero / 5.Zero + 32.Zero # TEMP_STRING IS THE SENSOR OUTPUT, MAKE SURE IT’S AN INTEGER TO DO THE MATH
temp_f = str(spherical(temp_f, 1)) # ROUND THE RESULT TO 1 PLACE AFTER THE DECIMAL, THEN CONVERT IT TO A STRING
return temp_f

whereas True:

liquid crystal display.cursor_pos = (Zero, Zero)
liquid crystal display.write_string(“Temp: ” + read_temp_c() + unichr(223) + “C”)
liquid crystal display.cursor_pos = (1, Zero)
liquid crystal display.write_string(“Temp: ” + read_temp_f() + unichr(223) + “F”)

Properly, that about covers most of what you’ll want to get began programming your LCD with Python. Attempt combining the packages to get some fascinating results. You possibly can show knowledge from a number of sensors by printing and clearing the display or positioning the textual content. It’s also possible to make enjoyable animations by scrolling customized characters.

In case you have any issues or questions, simply depart a remark under. And make sure to subscribe in case you’d like to get an e mail notification once we publish new articles. Okay, speak to you subsequent time!