lcd module python code supplier
An online editor for creating customer characters is available online at https://clach04.github.io/lcdchargen/ (source code available from https://github.com/clach04/lcdchargen/tree/python)
In the previous project of the Raspberry Pi Series, I have shown you how to blink an LED using Raspberry Pi and Python Program. Moving forward in the series, in this project, I’ll show you the interfacing 16×2 LCD with Raspberry Pi.
In this project, you can see all the steps for Interfacing a 16×2 LCD with Raspberry Pi like circuit diagram, components, working, Python Program and explanation of the code.
Even though the Raspberry Pi computer is capable of doing many tasks, it doesn’t have a display for implementing it in simple projects. A 16×2 Alphanumeric Character LCD Display is a very important types of display for displaying some basic and vital information.
A 16×2 LCD is one of the most popular display modules among hobbyists, students and even electronics professionals. It supports 16 characters per row and has two such rows. Almost all the 16×2 LCD Display Modules that are available in the market are based on the Hitachi’s HD44780 LCD Controller.
The pin description in the above table shows that a 16×2 LCD has 8 data pins. Using these data pins, we can configure the 16×2 LCD in either 8 – bit mode or 4 – bit mode. I’ll show the circuit diagram for both the modes.
In 8 – bit mode, all the 8 data pins i.e. D0 to D7 are used for transferring data. This type of connection requires more pins on the Raspberry Pi. Hence, we have opted for 4 – bit mode of LCD. The circuit diagram (with Fritzing parts) is shown below.
The following image shows the wiring diagram of the featured circuit of this project i.e. LCD in 4 – bit mode. In this mode, only 4 data pins i.e. D4 to D7 of the LCD are used.
NOTE: In this project, we have used the 4 – bit mode of the 16×2 LCD display. The Python code explained here is also related to this configuration. Slight modifications are needed in the Python Program if the circuit is configured in 8 – bit mode.
The design of the circuit for Interfacing 16×2 LCD with Raspberry Pi is very simple. First, connect pins 1 and 16 of the LCD to GND and pins 2 and 15 to 5V supply.
Then connect a 10KΩ Potentiometer to pin 3 of the LCD, which is the contrast adjust pin. The three control pins of the LCD i.e. RS (Pin 4), RW (Pin 5) and E (Pin 6) are connected to GPIO Pin 7 (Physical Pin 26), GND and GPIO Pin 8 (Physical Pin 24).
Now, the data pins of the LCD. Since we are configuring the LCD in 4 – bit mode, we need only 4 data pins (D4 to D7). D4 of LCD is connected to GPIO25 (Physical Pin 22), D5 to GPIO24 (Physical Pin 18), D6 to GPIO24 (Physical Pin 16) and D7 to GPIO18 (Physical Pin 12).
The working of project for Interfacing 16×2 LCD with Raspberry Pi is very simple. After making the connections as per the circuit diagram, login to your Raspberry Pi using SSH Client like Putty in Windows.
I’ve created a folder named “Python_Progs” on the desktop of the Raspberry Pi. So, I’ll be saving my Python Program for Interfacing 16 x 2 LCD with Raspberry Pi in this folder.
Using “cd” commands in the terminal, change to this directory. After that, open an empty Python file with name “lcdPi.py” using the following command in the terminal.
Now, copy the above code and paste it in the editor. It is important to properly use the Tab characters as they help in grouping the instructions in Python.
Save the file and close the editor. To test the code, type the following command in the terminal. If everything is fine with your connections and Python Program, you should be able to see the text on the 16×2 LCD.
First, I’ve imported the RPi.GPIO Python Package as GPIO (here after called as GPIO Package) and sleep from time package. Then, I have assigned the pin for LCD i.e. RS, E, D4, D5, D6 and D7. The numbering scheme I followed is GPIO or BCM Scheme.
Finally, using some own functions like lcd_init, lcd_string, lcd_display, etc. I’ve transmitted the data to be printed from the Raspberry Pi to the 16×2 LCD Module.
By interfacing 16×2 LCD with Raspberry Pi, we can have a simple display option for our raspberry Pi which can display some basic information like Date, Time, Status of a GPIO Pin, etc.
Many simple and complex application of Raspberry Pi like weather station, temperature control, robotic vehicles, etc. needs this small 16×2 LCD Display.
I"m trying to use some Python code to write text on a 16x2 LCD display ("compatible" with classics Hitachi HD44780) connected to a RaspberryPi model B+ via an I2C "back-pack".
The problem is that running multiple times this sample code, in sequence, one time it goes OK and the next time the LCD displays random characters; then again, one OK, one wrong.
In this tutorial, we will Control a 16x2 LCD Display using Raspberry Pi. We will connect the LCD to GPIO (General Purpose Input Output) pins of PI to display characters on it. We will write a program in PYTHON to send the appropriate commands to the LCD through GPIO and display the needed characters on its screen. This screen will come in handy to display sensor values, interrupt status and also for displaying time.
There are different types of LCDs in the market. Graphic LCD is more complex than 16x2 LCD. So here we are going for 16x2 LCD display, you can even use 16x1 LCD if you want. 16x2 LCD has 32 characters in total, 16 in 1st line and another 16 in 2nd line. JHD162 is 16x2 LCD Module characters LCD. We have already interfaced 16x2 LCD with 8051, AVR, Arduino etc. You can find all our 16x2 LCD related project by following this link.
There are +5V (Pin 2 or 4) and +3.3V (Pin 1 or 17) power output pins on the board, these are for connecting other modules and sensors. We are going to power the 16*2 LCD through the +5V rail.We can send control signal of +3.3v to LCD but for working of LCD we need to power it by +5V. The LCD will not work with +3.3V.
As shown in the Circuit Diagram, we have Interfaced Raspberry Pi with LCD display by connecting 10 GPIO pins of PI to the 16*2 LCD’s Control and Data Transfer Pins. We have used GPIO Pin 21, 20, 16, 12, 25, 24, 23, and 18 as a BYTE and created ‘PORT’ function to send data to LCD. Here GPIO 21 is LSB (Least Significant Bit) and GPIO18 is MSB (Most Significant Bit).
16x2 LCD Module has 16 pins, which can be divided into five categories, Power Pins, contrast pin, Control Pins, Data pins and Backlight pins. Here is the brief description about them:
6. Once this E pin goes low, the LCD process the received data and shows the corresponding result. So this pin is set to high before sending data and pulled down to ground after sending data.
As said we are going to send the characters one after the other. The characters are given to LCD by ASCII codes (American standard Code for Information Interchange). The table of ASCII codes is shown below. For example, to show a character “@”, we need to send a hexadecimal code “40”. If we give value 0x73 to the LCD it will display “s”. Like this we are going to send the appropriate codes to the LCD to display the string “CIRCUITDIGEST”.
Raspberry Pi 16×2 LCD I2C Interfacing and Python Programming– I have been using 16×2 LCD for quite a long time in different Arduino and IoT related projects. You know we have two types of the 16×2 LCD, the normal one used more wires and the other one is based on the I2C interface which needs only two wires.
The backpack module uses the I-squred-C (or I2C) protocol to communicate with the Raspberry Pi, which uses only two wires: SDA and SCL (data and clock). Please note that the display is a 5 volt device, and it is powered by 5 volts, but due to design of the I2C protocol, and the fact that the Raspberry Pi is the controlling device, it is safe to connect such display to the Raspberry Pi directly.
I suggest using wires of different colors to connect the LCD display. This minimizes the risk of damage due to incorrect connections. For example, I’m using
Before you start using the I2C 16×2 LCD display with Python, you need to make sure that the I2C protocol is enabled on your Raspberry Pi. You can use the sudo raspi-config utility to take care of that. This program is navigated using keyboard arrows, tab and the Enter key. Look for I2C in the interfacing options and enable it. Enabling I2C requires a reboot.
The 27 hexadecimal addresses happen to be the most common, but your display’s address may be different. For example, it could be 3f. This will depend on the chip version of the backpack module. As long as the i2cdetect command shows the display is connected, you are good to go.
The easiest way to program this 16×2 I2C LCD display in Python is by using a dedicated library. There are many to choose from. I like things simple, so the library I recommend is rpi_lcd.
This library has the default 27 address hard-coded. If your display has a different address you will need to change it. You need to find the library on your system and the following command should do that for you.
Connecting an LCD to your Raspberry Pi will spice up almost any project, but what if your pins are tied up with connections to other modules? No problem, just connect your LCD with I2C, it only uses two pins (well, four if you count the ground and power).
In this tutorial, I’ll show you everything you need to set up an LCD using I2C, but if you want to learn more about I2C and the details of how it works, check out our article Basics of the I2C Communication Protocol.
BONUS: I made a quick start guide for this tutorial that you can download and go back to later if you can’t set this up right now. It covers all of the steps, diagrams, and code you need to get started.
There are a couple ways to use I2C to connect an LCD to the Raspberry Pi. The simplest is to get an LCD with an I2C backpack. But the hardcore DIY way is to use a standard HD44780 LCD and connect it to the Pi via a chip called the PCF8574.
The PCF8574 converts the I2C signal sent from the Pi into a parallel signal that can be used by the LCD. Most I2C LCDs use the PCF8574 anyway. I’ll explain how to connect it both ways in a minute.
I’ll also show you how to program the LCD using Python, and provide examples for how to print and position the text, clear the screen, scroll text, print data from a sensor, print the date and time, and print the IP address of your Pi.
Connecting an LCD with an I2C backpack is pretty self-explanatory. Connect the SDA pin on the Pi to the SDA pin on the LCD, and the SCL pin on the Pi to the SCL pin on the LCD. The ground and Vcc pins will also need to be connected. Most LCDs can operate with 3.3V, but they’re meant to be run on 5V, so connect it to the 5V pin of the Pi if possible.
If you have an LCD without I2C and have a PCF8574 chip lying around, you can use it to connect your LCD with a little extra wiring. The PCF8574 is an 8 bit I/O expander which converts a parallel signal into I2C and vice-versa. The Raspberry Pi sends data to the PCF8574 via I2C. The PCF8574 then converts the I2C signal into a 4 bit parallel signal, which is relayed to the LCD.
Before we get into the programming, we need to make sure the I2C module is enabled on the Pi and install a couple tools that will make it easier to use I2C.
Now we need to install a program called I2C-tools, which will tell us the I2C address of the LCD when it’s connected to the Pi. So at the command prompt, enter sudo apt-get install i2c-tools.
Next we need to install SMBUS, which gives the Python library we’re going to use access to the I2C bus on the Pi. At the command prompt, enter sudo apt-get install python-smbus.
Now reboot the Pi and log in again. With your LCD connected, enter i2cdetect -y 1 at the command prompt. This will show you a table of addresses for each I2C device connected to your Pi:
We’ll be using Python to program the LCD, so if this is your first time writing/running a Python program, you may want to check out How to Write and Run a Python Program on the Raspberry Pi before proceeding.
I found a Python I2C library that has a good set of functions and works pretty well. This library was originally posted here, then expanded and improved by GitHub user DenisFromHR.
There are a couple things you may need to change in the code above, depending on your set up. On line 19 there is a function that defines the port for the I2C bus (I2CBUS = 0). Older Raspberry Pi’s used port 0, but newer models use port 1. So depending on which RPi model you have, you might need to change this from 0 to 1.
The function mylcd.lcd_display_string() prints text to the screen and also lets you chose where to position it. The function is used as mylcd.lcd_display_string("TEXT TO PRINT", ROW, COLUMN). For example, the following code prints “Hello World!” to row 2, column 3:
On a 16×2 LCD, the rows are numbered 1 – 2, while the columns are numbered 0 – 15. So to print “Hello World!” at the first column of the top row, you would use mylcd.lcd_display_string("Hello World!", 1, 0).
You can create any pattern you want and print it to the display as a custom character. Each character is an array of 5 x 8 pixels. Up to 8 custom characters can be defined and stored in the LCD’s memory. This custom character generator will help you create the bit array needed to define the characters in the LCD memory.
The code below will display data from a DHT11 temperature and humidity sensor. Follow this tutorial for instructions on how to set up the DHT11 on the Raspberry Pi. The DHT11 signal pin is connected to BCM pin 4 (physical pin 7 of the RPi).
By inserting the variable from your sensor into the mylcd.lcd_display_string() function (line 22 in the code above) you can print the sensor data just like any other text string.
These programs are just basic examples of ways you can control text on your LCD. Try changing things around and combining the code to get some interesting effects. For example, you can make some fun animations by scrolling with custom characters. Don’t have enough screen space to output all of your sensor data? Just print and clear each reading for a couple seconds in a loop.
The built-in controller used in this LCD is ST7735S, which is an LCD controller with 162 x RGB x 132 pixels, while the pixels of this LCD are 160 (H) RGB x 80 (V).
Since the display starting position of the LCD is inconsistent with the origin of the controller, it is necessary to perform offset processing when using the controller to initialize the full-screen display area: the display starts from the second pixel in the horizontal direction, and the 27th pixel in the vertical direction. Click to start. In this way, it can be ensured that the corresponding position of the RAM in the displayed LCD is consistent with the actual one.
For most LCD controllers, the communication mode of the controller can be configured, usually with 8080 parallel interfaces, three-wire SPI, four-wire SPI, and other communication methods. This LCD uses a four-wire SPI communication interface, which can greatly save the GPIO port, and the communication speed will be faster.
The 0.96inch LCD uses the PH2.0 8PIN interface, which can be connected to the Raspberry Pi according to the above table: (Please connect according to the pin definition table. The color of the wiring in the picture is for reference only, and the actual color shall prevail.)
PS: If you are using the system of the Bullseye branch, you need to change "apt-get" to "apt", the system of the Bullseye branch only supports Python3.
2. The module_init() function is automatically called in the INIT () initializer on the LCD, but the module_exit() function needs to be called by itself
Python has an image library PIL official library link, it do not need to write code from the logical layer like C, can directly call to the image library for image processing. The following will take 1.54inch LCD as an example, we provide a brief description for the demo.
The demo is developed based on the HAL library. Download the demo, find the STM32 program file directory, and open the LCD_demo.uvprojx in the STM32\STM32F103RBT6\MDK-ARM directory to check the program.
image.cpp(.h): is the image data, which can convert any BMP image into a 16-bit true color image array through Img2Lcd (downloadable in the development data).
Write numbers with decimals: at (Xstart Ystart) as the left vertex, write a string of numbers with decimals, you can choose Ascii code visual character font, font foreground color, font background color
If your display is equipped with an IC2 module, it’s not that difficult to connect an LCD display to a Raspberry Pi. Learn with this tutorial how to connect and to program an 1602 LCD with a Raspberry Pi.
There are many types of LCD displays. In this tutorial we are using the popular and affordable 1602 LCD. The LCD has an IC2 module soldered on it (see the pictures below). If your LCD is of the same type, but has a different size, it won’t be a problem to continue with this tutorial. You’ll just have to correct some parameters in the Python script. But if it is from a different type or it has no I2C module, you better look for another tutorial.Prepare the hardware
– First, you need to have a Raspberry Pi running on the latest version of Raspberry Pi OS. This version includes “Thonny”. We’ll use this user-friendly IDE to write our Python code. If you’re not familiar with Python or with Thonny or GPIO-pins, I suggest to have a look at our tutorials “How to write your first Python program on the Raspberry Pi” and/or “How to use the Raspberry Pi GPIO pins” to have a quick introduction.
In this tutorial we are using the popular and quite basic 16×2 or 1602 LCD. It can display 16 characters per line on 2 lines. Each character is made from a matrix with 5×7 dots. It is equipped with a backlight for easy reading. Besides sending text, thanks to specific commands, we can give instructions to the display, as to switch on/off the backlight for example.
The display we use in this tutorial is equipped with a I2C-module (black part on the picture below). I2C is a communication protocol which allows an easier connection between the display and the Raspberry Pi. Indeed, instead of having to wire all the pins on the top of the screen, we only have to connect the display with 4 wires to our Raspberry Pi.
If you bought one of our kits, the hexadecimal address of the LCD is ‘0x27’. We will need the I2C address from the display to insert it in our Python code.
To avoid extensive and complicated code writing, libraries are often used. For our LCD, we will also be using a library. We found the most appropriate library at GitHub from Dave Hylands . As these files from this quite specific library don’t come automatically with Python, we have to install them ourselves.
So, before writing the code, we’ll have to upload the files to our Raspberry Pi. You can download a ZIP-folder containing the 2 files to be installed here.
Download and unzip the files. If you did this operation on your computer, upload the files to your Raspberry Pi. And if you don’t know how to do that, have a look at our tutorial ‘How to transfer files between Raspberry Pi and PC‘. Make sure you upload them in the same folder as the new file we will create for our main code. And don’t change the filenames of the library of course.
And before running the script, it’s important to adjust the contrast of your LCD. If the contrast isn’t adjusted well, it’s possible you don’t see appearing anything. You can adjust it by turning with a small screwdriver at the blue potentiometer at the back of your LCD (see the pictures here above). Make sure the backlight of the display is on to see the result. If the LCD’s contrast is adjusted right, you can just see the darker rectangles for the characters appear.
Besides the commands we used in the last lines of our script, there are more possibilities to communicate with the LCD. If you want to learn more about, have a look at this Github webpage.
LCD screens are useful and found in many parts of our life. At the train station, parking meter, vending machines communicating brief messages on how we interact with the machine they are connected to. LCD screens are a fun way to communicate information in Raspberry Pi Pico projects and other Raspberry Pi Projects. They have a big bright screen which can display text, numbers and characters across a 16 x 2 screen. The 16 refers to 16 characters across the screen, and the 2 represents the number of rows we have. We can get LCD screens with 20x2, 20x4 and many other configurations, but 16x2 is the most common.
In this tutorial, we will learn how to connect an LCD screen, an HD44780, to a Raspberry Pi Pico via the I2C interface using the attached I2C backpack, then we will install a MicroPython library via the Thonny editor and learn how to use it to write text to the display, control the cursor and the backlight.
2. Import four librariesof pre-written code. The first two are from the Machine library and they enable us to use I2C and GPIO pins. Next we import the sleep function from Time enabling us to pause the code. Finally we import the I2C library to interact with the LCD screen.from machine import I2C, Pin
3. Create an objecti2c to communicate with the LCD screen over the I2C protocol. Here we are using I2C channel 0, which maps SDA to GP0 and SCL to GP1.i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
5. Create an objectlcdto set up the I2C connection for the library. It tells the library what I2C pins we are using, set via the i2c object, the address of our screen, set via I2C_ADDRand finally it sets that we have a screen with two rows and 16 columns.lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
6. Create a loopto continually run the code, the first line in the loop will print the I2C address of our display to Thonny’s Python Shell.while True:
8. Write two lines of textto the screen. The first will print “I2C Address:” followed by the address stored inside the I2C_ADDR object. Then insert a new line character “\n” and then write another line saying “Tom’s Hardware" (or whatever you want it to say). Pause for two seconds to allow time to read the text.lcd.putstr("I2C Address:"+str(I2C_ADDR)+"\n")
9. Clear the screenbefore repeating the previous section of code, but this time we display the I2C address of the LCD display using its hex value. The PCF8574T chip used in the I2C backpack has two address, 0x20 and 0x27 and it is useful to know which it is using, especially if we are using multiple I2C devices as they may cause a clash on the bus.lcd.clear()
12. Turn the backlight back onand then hide the cursor. Sometimes, a flashing cursor can detract from the information we are trying to communicate.lcd.backlight_on()
13. Create a for loopthat will print the number 0 to 19 on the LCD screen. Note that there is a 0.4 second delay before we delete the value and replace it with the next. We have to delete the text as overwriting the text will make it look garbled.for i in range(20):
Save and runyour code. As with any Python script in Thonny, Click on File >> Saveand save the file to your Raspberry Pi Pico. We recommend calling it i2c_lcd_test.py. When ready, click on the Green play buttonto start the code and watch as the test runs on the screen.
This is all carried out with code. Display manufacturers usually supply some of these procedures/methods but leave the rest up to the end user to construct.
At the top of our driver program we will always import a minimal set of libraries using this block at the top of our MicroPython script (we add even more later when we want to do advanced programs):
The following methods draw shapes (such as those above) onto the FrameBuffer. They only become visible to the user once the lcd.show() instruction is executed.
Each program contains the screen driver code, sets up the buttons/joystick (if applicable), sets the width and height variables, loads the essential libraries, defines the colour (R, G, B) and clear (c) procedures, then displays some colour checking text like this:
Using lcd.fill_rect, fill the whole screen green and then fill the middle of the screen black, leaving a 10 pixel border. Put red 10-pixel squares in each corner.
This is routine is very complicated. It splits the original triangle into two with a horizontal line and then fills them in. If you uncomment all the # lcd.show() lines and sleep instructions it will slow right down and you can see it working (unfortunately, the 2” display needs such a large buffer that there is not enough memory for the filled triangles code):
For the imports we added the math library as this is needed for Sin and Cos in graph plotting. The random library has also been imported, for the randomly generated triangles. These are followed by the basic LCD board setup we covered earlier.
Start with the MIN program you saved earlier. Save it with the name Bar.py. Delete the main part of the program and paste in this code. It allows us to control a variable, v, in the range 0 to 100 with two buttons. You can also halt the program with the third button.
This article was written by Tony Goodhew. Tony is a retired teacher of computing who starting writing code back in 1968 when it was called programming - he started with FORTRAN IV on an IBM 1130! An active Raspberry Pi community member, his main interests now are coding in MicroPython, travelling and photography.
I"m trying to use some Python code to write text on a 16x2 LCD display ("compatible" with classics Hitachi HD44780) connected to a RaspberryPi model B+ via an I2C "back-pack".
The problem is that running multiple times this sample code, in sequence, one time it goes OK and the next time the LCD displays random characters; then again, one OK, one wrong.