Учебное пособие по ЖК-дисплею Arduino
Учебное пособие по ЖК-дисплею Arduino: How to Connect and Program a 16x2 LCD
LCD displays are widely used in Arduino projects because they provide a simple and reliable way to show sensor readings, состояние системы, меню, сообщения, and other information. A 16x2 character LCD is one of the most popular choices for beginners. Он может отображать 16 characters on each of its two rows and is suitable for electronic prototypes, встроенные системы, измерительные инструменты, панели управления, и DIY-проекты.
This Arduino LCD display tutorial explains how to connect a standard 16x2 LCD to an Arduino, upload a basic program, display changing values, and solve common display problems. It also introduces the easier I2C connection method.
Components Required
To complete this project, prepare the following components:
- Arduino Uno or compatible development board
- 16x2 character LCD module
- 10K potentiometer
- 220-ohm resistor
- Breadboard
- Jumper wires
- USB cable
- Arduino IDE
Most 16x2 LCD modules use an HD44780-compatible controller. These displays normally include 16 pins for power, data communication, регулировка контрастности, and backlight control.
Understanding the 16x2 LCD Pins
A standard 16x2 LCD usually has the following pin arrangement:
- VSS – Ground
- VDD – 5V power supply
- VO – Contrast adjustment
- RS – Register Select
- RW – Read or Write control
- E – Enable pin
- D0 – Data pin
- D1 – Data pin
- D2 – Data pin
- D3 – Data pin
- D4 – Data pin
- D5 – Data pin
- D6 – Data pin
- D7 – Data pin
- А – Backlight anode
- K – Backlight cathode
LCD can operate in either 8-bit mode or 4-bit mode. For most Arduino projects, 4-bit mode is preferred because it requires fewer Arduino pins. In 4-bit mode, only data pins D4, D5, D6, and D7 are used.
Connecting the LCD to Arduino
Use the following wiring arrangement for a standard 16x2 LCD in 4-bit mode:
| LCD Pin | Arduino Connection |
|---|---|
| VSS | Гнездо |
| VDD | 5В |
| VO | Middle pin of 10K potentiometer |
| RS | Digital pin 12 |
| RW | Гнездо |
| E | Digital pin 11 |
| D4 | Digital pin 5 |
| D5 | Digital pin 4 |
| D6 | Digital pin 3 |
| D7 | Digital pin 2 |
| А | 5V through a 220-ohm resistor |
| K | Гнездо |
Connect the two outer pins of the potentiometer to 5V and GND. The middle pin connects to the LCD VO pin. Rotating the potentiometer changes the display contrast.
The resistor connected to the backlight helps limit current. Some LCD modules already include a backlight resistor, but using an external resistor is a safer option when the module specifications are unknown.
Installing the Arduino LCD Library
The Arduino IDE includes the standard LiquidCrystal библиотека. This library allows the Arduino to control HD44780-compatible character displays without manually programming every communication signal.
To include the library in your sketch, add the following line:
#include <LiquidCrystal.h>Следующий, define which Arduino pins are connected to the LCD:
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);The pin order is:
LiquidCrystal lcd(RS, E, D4, D5, D6, D7);Basic Arduino LCD Program
Upload the following code to display a simple message:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2);
lcd.print("Hello, Arduino!");
}
void loop() {
}The lcd.begin(16, 2) command tells the Arduino that the display contains 16 columns and two rows. The lcd.print() command writes text to the screen.
After uploading the program, the first row should display:
Hello, Arduino!If the backlight turns on but no text appears, slowly rotate the potentiometer until the characters become visible.
Displaying Text on the Second Row
The LCD cursor can be moved by using the lcd.setCursor() function.
The format is:
lcd.setCursor(column, row);The column and row positions start from zero. Поэтому, the first character of the first row is position 0, 0, while the first character of the second row is position 0, 1.
Example:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("LCD Tutorial");
lcd.setCursor(0, 1);
lcd.print("Arduino Project");
}
void loop() {
}This program displays one message on each row.
Displaying a Changing Counter
LCD modules can display changing values such as temperature, Напряжение, speed, время, distance, or sensor data. The following program creates a simple counter:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int counter = 0;
void setup() {
lcd.begin(16, 2);
lcd.print("Counter:");
}
void loop() {
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(counter);
counter++;
delay(1000);
}Пустые места очищают предыдущее число перед отображением нового значения.. Это предотвращает сохранение старых символов на экране, когда число становится короче..
Отображение данных датчика
Одним из наиболее распространенных приложений Arduino LCD является отображение значений аналоговых датчиков.. Потенциометр, датчик освещенности, датчик давления, или другое аналоговое устройство можно подключить к аналоговому входу Arduino..
В следующем примере считывается аналоговый сигнал с контакта A0.:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
lcd.begin(16, 2);
lcd.print("Sensor Value:");
}
void loop() {
int sensorValue = analogRead(A0);
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(sensorValue);
delay(500);
}Аналого-цифровой преобразователь Arduino Uno обычно возвращает значение из 0 к 1023. Это значение также можно преобразовать в напряжение.:
float voltage = sensorValue * (5.0 / 1023.0);Затем напряжение можно отобразить с помощью:
lcd.print(voltage, 2);
lcd.print(" V");Число 2 сообщает Arduino отображать две цифры после десятичной точки.
Полезные команды LiquidCrystal
Библиотека LiquidCrystal предоставляет несколько полезных функций.:
Очистить дисплей
lcd.clear();This removes all characters and returns the cursor to the first position.
Move the Cursor
lcd.setCursor(5, 1);This moves the cursor to column five on the second row.
Turn the Display Off
lcd.noDisplay();Turn the Display On
lcd.display();Enable Cursor Display
lcd.cursor();Enable a Blinking Cursor
lcd.blink();Scroll Text
lcd.scrollDisplayLeft();
lcd.scrollDisplayRight();These commands can be used to create menus, предупреждающие сообщения, scrolling text, and interactive interfaces.
Using an I2C LCD Module
Standard LCD connection uses at least six Arduino signal pins. An I2C adapter reduces the connection to only four wires:
- Венчурной
- Гнездо
- ПДД
- СКЛ
On an Arduino Uno, SDA is normally connected to A4 and SCL is connected to A5. Some boards also provide dedicated SDA and SCL pins.
Typical I2C LCD program looks like this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Hello Arduino");
lcd.setCursor(0, 1);
lcd.print("I2C LCD");
}
void loop() {
}The I2C address is commonly 0x27 или 0x3F, but it may vary. If the display does not respond, an I2C scanner program can be used to identify the correct address.
The exact initialization command may also depend on the installed I2C library version.
Common Arduino LCD Problems
Backlight Is On but No Text Appears
Отрегулируйте потенциометр контрастности. Incorrect contrast is one of the most common reasons for an apparently blank LCD.
Black Rectangles Appear
Black rectangles usually mean that the LCD has power but is not receiving the correct initialization commands. Check the RS, E, D4, D5, D6, and D7 connections.
Random or Corrupted Characters
Loose wires, incorrect pin definitions, unstable power, or poor breadboard connections can cause corrupted characters.
Text Does Not Update Correctly
Clear the previous value before displaying new data. You can use lcd.clear(), but repeatedly clearing the entire screen may cause visible flickering. Printing blank spaces over the previous value is often smoother.
I2C LCD Does Not Work
Check the SDA and SCL connections, confirm the I2C address, install a compatible library, and make sure the backlight has been enabled in the program.
Arduino LCD Project Ideas
After completing the basic tutorial, the LCD can be used in many projects, включая:
- Digital thermometers
- Humidity monitors
- Battery voltage meters
- Distance measurement systems
- Electronic clocks
- Motor control panels
- Умные счетчики энергии
- Alarm systems
- Menu-based controllers
- Industrial monitoring equipment
Buttons, rotary encoders, датчики, and communication modules can also be added to create a complete user interface.
Заключение
Connecting a 16x2 LCD to an Arduino is an excellent introduction to display control and embedded system programming. A standard parallel LCD offers simple operation and reliable performance, while an I2C LCD saves Arduino pins and reduces wiring.
Научившись инициализировать дисплей, расположить курсор, распечатать текст, обновить изменяющиеся значения, и устранять распространенные проблемы, вы можете добавить практичный визуальный интерфейс практически в любой проект Arduino.. Создаете ли вы сенсорный монитор, электронный инструмент, панель управления, или образовательный прототип, символьный ЖК-дисплей обеспечивает четкое и экономичное решение для отображения.






