Programming arduino lcd

Arduino и дисплей LCD1602

Описание

Классический LCD дисплей, раньше такие стояли в кассовых аппаратах и офисной технике.

  • Бывают разного размера, самый популярный – 1602 (16 столбцов 2 строки), есть ещё 2004, 0802 и другие. В наборе идёт 1602.
  • Снабжён отключаемой светодиодной подсветкой. Существует несколько вариантов, например синий фон белые буквы, зелёный фон чёрные буквы, чёрный фон белые буквы и проч. В наборе идёт с зелёным фоном и чёрными буквами.
  • Сам по себе требует для подключения 6 цифровых пинов, но китайцы выпускают переходник на шину I2C на базе PCF8574, что сильно упрощает подключение и экономит пины. В наборе идёт дисплей с припаянным переходником.
  • На переходнике также распаян потенциометр настройки контрастности (синий параллелепипед с крутилкой под крестовую отвёртку). В зависимости от напряжения питания нужно вручную подстроить контрастность. Например при питании платы от USB на пин 5V приходит

4.7V, а при внешнем питании от адаптера – 5.0V. Контрастность символов на дисплее будет разной!

  • Переходник может иметь разный адрес для указания в программе: 0х26 , 0x27 или 0x3F , об этом ниже.
  • Подключение

    Дисплей подключается по шине I2C, выведенной на пины:

    • Arduino: SDA – A4, SCL – A5
    • Wemos: SDA – D2, SCL – D1
    • Питание: 5V в обоих случаях

    Библиотеки

    Для этого дисплея существует несколько библиотек, я рекомендую LiquidCrystal_I2C от Frank de Brabander. Библиотека идёт в архиве к набору, а также её можно скачать через менеджер библиотек по названию LiquidCrystal_I2C и имени автора. Репозиторий на GitHub.

    Пример вывода

    При первой работе с дисплеем нужно настроить контраст и определиться с адресом:

    • Прошить пример “Демо”
    • Если дисплей показывает чёрные прямоугольники или пустой экран – крутим контраст
    • Если кроме чёрных прямоугольников и пустого экрана ничего не видно – меняем адрес в программе: 0х26 , 0x27 и 0x3F
    • Снова крутим контраст, должно заработать
    • Если не работает – проверяем подключение и повторяем сначала
    • Примечание: в наборе должны идти дисплеи с адресом 0x27 , но может зависеть от партии!

    Символы дисплея

    В памяти дисплея содержится 255 символов, это английские буквы, стандартные символы и китайские буквы. Стандартные символы, такие как !@#$%&()* и так далее выводятся через print() , остальные можно вывести по их коду при помощи write() :

    • Стрелка вправо – 126
    • Стрелка влево – 127
    • Символ градуса – 223
    • Прямоугольник – 255

    Свои символы

    Библиотека поддерживает создание “своих” дополнительных символов размером 5х7 точек, можно воспользоваться онлайн-генератором кодов символов – ссылка. Для компактности рекомендую переключить его в HEX. Вот так будет выглядеть “символ” крестик: byte myX[] = <0x00, 0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x00>;

    Дисплей имеет 8 ячеек под сторонние символы, добавляются они при помощи createChar(номер, массив) , где номер – от 0 до 7, а массив – имя массива с данными, которое мы создали для символа. Выводятся символы при помощи write(номер) .

    Важный момент: после вызова createChar сбрасывается позиция вывода текста, нужно обязательно вызвать setCursor!

    Важная информация по дисплеям

    Данная информация относится ко всем дисплеям.

    • Вывод данных на дисплей занимает время, поэтому выводить нужно либо по таймеру, либо по факту изменения данных.
    • Очищать дисплей полностью не всегда целесообразно, иногда достаточно вывести новые значения поверх старых, либо частично очистить “пробелами”.

    Источник

    Arduino — LCD

    In this Arduino LCD tutorial, we will learn how to connect an LCD (Liquid Crystal Display) to the Arduino board. LCDs are very popular and widely used in electronics projects for displaying information. There are many types of LCD. This tutorial takes LCD 16×2 (16 columns and 2 rows) as an example. The other LCDs are similar.

    If you want to simplify the wiring, You can use LCD I2C instead. See LCD I2C tutorial

    Hardware Required

    1 × Arduino UNO or Genuino UNO
    1 × USB 2.0 cable type A/B
    1 × LCD
    1 × Potentiometer
    1 × Breadboard
    n × Jumper Wires

    About LCD 16×2

    Pinout

    LCD has up to 16 pins. In the most common uses, we do NOT use all pins.

    With the support of LiquidCrystal library, we even can use LCD WITHOUT knowing the meaning of these pins. However, if you are curious or want to know in-depth, let’s see these pins and their functionality:

    4-bit mode and 8-bit mode

    8-bit mode is faster than the 4-bit mode, but use more pins than 4-bit mode. The mode selection is performed at the initialization process by sending a command to LCD.

    This tutorial uses 4-bit mode, which is the most common-used.

    In this mode, LCD’s pins:

    LCD pin table in 4-bit mode

    LCD PIN CONNECTED TO
    01 GND GND
    02 VCC 5V
    03 Vo 5V or potentiometer’s pin
    04 RS An Arduino’s pin
    05 R/W GND
    06 EN An Arduino’s pin
    07 D0 NOT connected
    08 D1 NOT connected
    09 D2 NOT connected
    10 D3 NOT connected
    11 D4 An Arduino’s pin
    12 D5 An Arduino’s pin
    13 D6 An Arduino’s pin
    14 D7 An Arduino’s pin
    15 A 5V
    16 K GND

    LCD Coordinate

    LCD 16×2 includes 16 columns and 2 rows. the conlums and rows are indexed from 0.

    How It Works

    The process of sending data (to be displayed) to LCD:

    The process of sending command (to control) to LCD (e.g, blink LCD, set the cursor to a specific location, clear the display . ):

    Arduino — LCD

    Controlling LCD is a quite complicated task. Fortunately, thanks to the LiquidCrystal library, this library simplifies the process of controlling LCD for you so you don’t need to know the low-level instructions. You just need to connect Arduino to LCD and use the functions of the library. The using LCD is a piece of cake.

    Wiring Diagram

    Image is developed using Fritzing. Click to enlarge image

    Источник

    Arduino 16×2 LCD Tutorial – Everything You Need to Know

    In this Arduino tutorial we will learn how to connect and use an LCD (Liquid Crystal Display) with Arduino. LCD displays like these are very popular and broadly used in many electronics projects because they are great for displaying simple information, like sensors data, while being very affordable.

    I’ve already used them in several of my Arduino projects, and you can check them out here:

    You can watch the following video or read the written tutorial below. It includes everything you need to know about using an LCD character display with Arduino, such as, LCD pinout, wiring diagram and several example codes.

    What is LCD Character Display?

    An LCD character display is a unique type of display that can only output individual ASCII characters with fixed size. Using these individual characters then we can form a text.

    If we take a closer look at the display we can notice that there are small rectangular areas composed of 5×8 pixels grid. Each pixel can light up individually, and so we can generate characters within each grid.

    The number of the rectangular areas define the size of the LCD. The most popular LCD is the 16×2 LCD, which has two rows with 16 rectangular areas or characters. Of course, there are other sizes like 16×1, 16×4, 20×4 and so on, but they all work on the same principle. Also, these LCDs can have different background and text color.

    16×2 LCD Pinout

    It has 16 pins and the first one from left to right is the Ground pin. The second pin is the VCC which we connect the 5 volts pin on the Arduino Board. Next is the Vo pin on which we can attach a potentiometer for controlling the contrast of the display.

    Next, The RS pin or register select pin is used for selecting whether we will send commands or data to the LCD. For example if the RS pin is set on low state or zero volts, then we are sending commands to the LCD like: set the cursor to a specific location, clear the display, turn off the display and so on. And when RS pin is set on High state or 5 volts we are sending data or characters to the LCD.

    Next comes the R/W pin which selects the mode whether we will read or write to the LCD. Here the write mode is obvious and it is used for writing or sending commands and data to the LCD. The read mode is used by the LCD itself when executing the program which we don’t have a need to discuss about it in this tutorial.

    Next is the E pin which enables the writing to the registers, or the next 8 data pins from D0 to D7. So through this pins we are sending the 8 bits data when we are writing to the registers or for example if we want to see the latter uppercase A on the display we will send 0100 0001 to the registers according to the ASCII table. The last two pins A and K, or anode and cathode are for the LED back light.

    After all we don’t have to worry much about how the LCD works, as the Liquid Crystal Library takes care for almost everything. From the Arduino’s official website you can find and see the functions of the library which enable easy use of the LCD. We can use the Library in 4 or 8 bit mode. In this tutorial we will use it in 4 bit mode, or we will just use 4 of the 8 data pins.

    How to Connect Arduino to LCD – Wiring Diagram

    Here’s how we need to connect the 16×2 LCD display to an Arduino board.

    We will use just 6 digital input pins from the Arduino Board. The LCD’s registers from D4 to D7 will be connected to Arduino’s digital pins from 4 to 7. The Enable pin will be connected to pin number 2 and the RS pin will be connected to pin number 1. The R/W pin will be connected to Ground and the Vo pin will be connected to the potentiometer middle pin.

    You can get these components from any of the sites below:

    Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

    Adjusting the contrast of the LCD

    We can adjust the contrast of the LCD by adjusting the voltage input at the Vo pin. We are using a potentiometer because in that way we can easily fine tune the contrast, by adjusting input voltage from 0 to 5V.

    Can I use the LCD without Potentiometer?

    Yes, in case we don’t have a potentiometer, we can still adjust the LCD contrast by using a voltage divider made out of two resistors. Using the voltage divider we need to set the voltage value between 0 and 5V in order to get a good contrast on the display. I found that voltage of around 1V worked worked great for my LCD. I used 1K and 220 ohm resistor to get a good contrast.

    There’s also another way of adjusting the LCD contrast, and that’s by supplying a PWM signal from the Arduino to the Vo pin of the LCD. We can connect the Vo pin to any Arduino PWM capable pin, and in the setup section, we can use the following line of code:

    It will generate PWM signal at pin D11, with value of 100 out of 255, which translated into voltage from 0 to 5V, it will be around 2V input at the Vo LCD pin.

    LCD Arduino Code

    Here’s a simple code through which we can explain the working principle of the Liquid Crystal library. This is the code of the first example from the video:

    Code description:

    First thing we need to do is it insert the Liquid Crystal Library. We can do that like this: Sketch > Include Library > Liquid Crystal. Then we have to create an LC object. The parameters of this object should be the numbers of the Digital Input pins of the Arduino Board respectively to the LCD’s pins as follow: (RS, Enable, D4, D5, D6, D7). In the setup we have to initialize the interface to the LCD and specify the dimensions of the display using the begin() function.

    In the loop we write our main program. Using the print() function we print on the LCD.

    The setCursor() function is used for setting the location at which subsequent text written to the LCD will be displayed.

    The blink() function is used for displaying a blinking cursor and the noBlink() function for turning off.

    The cursor() function is used for displaying underscore cursor and the noCursor() function for turning off. Using the clear() function we can clear the LCD screen.

    Scrolling text example on 16×2 LCD and Arduino

    In case we have a text with length greater than 16 characters, we can scroll the text using the scrollDisplayLeft() or scrollDisplayRight() function from the LiquidCrystal library.

    Here’s an example code:

    We can choose whether the text will scroll left or right, using the scrollDisplayLeft() or scrollDisplayRight() functions. With the delay() function we can set the scrolling speed.

    If you want more control over how the text is scrolling, you could also make the scrolling on your own using a “for” loop. Here’s an example:

    How to Generate and Display Custom Characters on the LCD

    In addition to the ASCII characters, with the LiquidCrystal library it is also possible to generate and display custom characters on the LCD.

    We can specify the appearance of each character by an array of 8 bytes. Here’s an example code:

    We can notice how we can specify the appearance of the character by changing the 0s into 1s within the 5×8 pixels grid.

    In the setup we have to create the custom character using the createChar() function.

    The first parameter in this function is a number between 0 and 7, or we have to reserve one of the 8 supported custom characters. The second parameter is the name of the array of bytes.

    We write the custom character to the display using the write() function and as a parameter we use the number of the character.

    Conclusion

    So, we have covered pretty much everything we need to know about using an LCD with Arduino. These LCD Character displays are really handy for displaying information for many electronics project. In the examples above I used 16×2 LCD, but the same working principle applies for any other size of these character displays.

    I hope you enjoyed this tutorial and learned something new. Feel free to ask any question in the comments section below and don’t forget to check out my full collection of 30+ Arduino Projects.

    Источник