Arduino uno connection with touch screen. Touch buttons in Arduino. Connecting a touch button to Arduino

In this article we will talk about touch buttons in Arduino. With this simple and inexpensive component you can create simple and very impressive projects. Most often, such buttons are used to create all kinds of convenient touch interfaces, for example in smart home systems. Let's find out how you can connect touch buttons to Arduino, write a simple sketch and be sure to consider the principle of their operation.

It's no secret that progress does not stand still. New technologies are constantly emerging and old ones are being improved. Touch screens appeared quite recently (by human standards), but have already become firmly established in our daily lives. Phones, TVs, terminals and others mostly use “buttonless” technologies. This word is in quotes for the reason that they still use buttons, only touch ones. This article will be about them, or more precisely, about the Touch module for Arduino.

How touch buttons work

Modules with touch buttons mostly use projected capacitive touch screens (https://ru.wikipedia.org/wiki/Touch_screen). Without going into spatial explanations of their operation, to register a click, the calculation of the change in the capacitance of the capacitor (electric circuit) is used, and an important feature is the ability to set a different initial capacitance, which we will see later.

The human body has a certain electrical capacity, and therefore a low reactance for alternating electric current. If you touch it with your finger or any electrically conductive object, a small leakage current from the device will flow through it. A special chip detects this leak and sends a signal when the button is pressed. The advantages of this technology are: relative durability, low impact of pollution and resistance to water ingress.

Touch or mechanical buttons

The touch button “feels” pressure even through a small layer of non-metallic material, which ensures variety of use her in all kinds of projects.

This also follows from the previous point - the ability to use a touch button inside the case increases attractiveness project, which does not affect the functionality, but is quite important in Everyday life so as not to pay attention to it.

+Stable operation, which is expressed by the absence of moving parts and frequent calibration (which will be discussed below). You won't have to worry about button rattling that occurs when using a mechanical counterpart, which will make life much easier for a novice Arduino user. Therefore, another plus, although not for everyone, is ease of operation.

The disadvantages include the following:

  • Touch buttons do not work well at sub-zero temperatures, therefore they are not suitable for outdoor use.
  • High electricity consumption, caused by the need to constantly maintain the same capacity.
  • The touch button does not work when pressed with a gloved hand or a poorly conductive object

Overview of touch buttons

Before talking directly about working with the module, you need to decide which model to buy for use. Let's consider several options from different companies:

1. Troyka touch sensor

Response time: 80ms (in power mode) and 10ms (in high speed mode)

4 mm

Size: 25X25 mm

Supply voltage: 3–5 V

Response time: 220 ms and 80 ms

Maximum dielectric thickness for normal operation: 2 mm

Size: 20X20 mm

Supply voltage: 2–5 V

Timeresponse: 220 ms and 60 ms

Size: 24X24 mm

Supply voltage: 2–5 V

Size: 30X20 mm

Supply voltage: 3.3–5 V

Connecting a touch button to Arduino

To use the touch button, as well as all other modules and sensors, it must be connected to some kind of arduino board. In most cases, standard modules with three pins are used: power, signal and ground. Their locations vary from model to model; they are shown in the diagram according to the recent listing (the touch button is replaced by a switch due to its absence in Tincercad):

An important point: you need to remember that the touch button requires an average of half a second calibration during each startup, which allows you not to worry about unnecessary noise that would undoubtedly arise due to different positions buttons in projects. Therefore, you should not press the button immediately after starting, because... after this, the device is most likely to malfunction.

The touch module is essentially similar to a digital button. While the button is pressed, the sensor outputs a logical one, and if not, then a logical zero.

Projects using the touch button

Let's start with something simple: when you press the button, the built-in LED lights up.

Const int buttonPin = 7; // Set the values ​​of the port connected to the signal port of the button void setup() ( pinMode(LED_BUILTIN, OUTPUT); // Command for adequate response of the LED pinMode(buttonPin, INPUT); // Open the port for reading ) void loop() ( buttonState = digitalRead(buttonPin); // Read the status of the button (pressed / not pressed) if (digitalRead(buttonPin)) ( // If the button is pressed... digitalWrite(LED_BUILTIN, HIGH); // Apply voltage to LED_BUILTIN - the value for built-in LED ) else ( // Otherwise... digitalWrite(LED_BUILTIN, LOW); // Do not supply voltage ) )

Now let's complicate the task: Pressing the button changes the operating mode of the LED.

Const int buttonPin = 7; // Set the values ​​of the port connected to the signal port of the button int count = 0; // Variable for selecting the operating mode void setup() ( pinMode(LED_BUILTIN, OUTPUT); // Command for adequate response of the LED pinMode(buttonPin, INPUT); // Open the port for reading ) void loop() ( if(digitalRead (buttonPin))( // When the button is pressed... count = count + 1; // Change the button mode if(count > 2)( // If the count value is exceeded, we start counting again count = 0; ) while(digitalRead( buttonPin))( // An empty loop to wait until the user releases the button ) ) if(count == 0) ( // 3 modes for switching the button: digitalWrite(LED_BUILTIN, LOW); // 1: LED off ) else if( count == 1) ( digitalWrite(LED_BUILTIN, HIGH); // 2: On ) else ( digitalWrite(LED_BUILTIN, HIGH); // 3: Blinking delay(100); digitalWrite(LED_BUILTIN, LOW); delay(100); ) )

Conclusion

In this article, we looked at the principle of operation and the connection diagram of the touch button to Arduino boards. From the point of view of the software model, there are no special differences when working with this type of button. You are simply analyzing the level incoming signal and decide on your action. Considering that the touch button modules themselves are quite cheap and available in large quantities online stores, adding such an interesting and modern interface to your Arduino project will not be difficult.

This article describes how to connect the TE-ULCD to Arduino and how it can be used together with the Ethernet Shield v2 expansion board. In the process of studying the module, we got a library and a small sketch that received from the Internet and displayed time in UTC format, the state of road traffic in Moscow, using the Yandex.traffic service, and the weather, using the GisMeteo informer service.

I chose this module as one of the few ready-made solutions based on the SPI interface available in the Russian Federation, i.e., it does not require many (16-32) pins for control.

TE-ULCD is produced by Terraelectronics LLC. The module is based on a 3.5" (or 5.6") color graphic display with touch screen and a 32-bit ARM-7 microcontroller. Servicing a color graphic display using a specialized microcontroller allows you to separate the functions of information display and control and makes it possible to provide a “human-machine” interface in various information and control systems. A library of graphic functions is loaded into the microcontroller program memory at the manufacturing stage. Functions can be called from the application program using SPI commands. This greatly simplifies the creation of images on the TFT display, as well as maintenance of the touch screen. It is possible to update the downloaded library. A microSD memory card is used to store pictures in BMP format.

Required Components

Connection

The display module is powered from 5 volts direct current, in the user manual the manufacturer indicates a rated current of 0.2 A. I measured the current consumption using a digital power supply and it turned out to be a stable 0.299 A, so we should focus on 0.3 A. When powering the TE-ULCD from an Arduino, a voltage converter installed on the board It got quite hot, so just in case, I powered the display module from the USB of a personal computer using a cord from an old mouse. The X8 TE-ULCD connector is designed for power supply and has the following pinout: PIN 1, 3, 7 and 9 - 5 V input, PIN 2, 4, 6, 8, 10 - GND, PIN5 is used as a key to control the correct connection. You can supply power to any one pin +5 V and GND.
The Arduino is connected to the X6 connector of the display module, according to the diagram shown in the figure. SPI TE-ULCD operates at a level of 3.3 V, so you should match the levels of the display module and Arduino using a simple resistor divider.
Since the plan is to use the TE-ULCD and the Ethernet Shield expansion card together, PIN9 and PIN10 will be used to select managed (slave) devices, respectively. PIN9 was chosen based on ease of connection and you can use any other free one by changing the value of slaveSelectPin in the sketch.

The TE-ULCD write and read commands correspond to the SPI settings CPOL=1 and CPHA=1, which corresponds to SPI_MODE3 for Arduino. For the Ethernet Shield v2 expansion card, the SPI settings correspond to SPI_MODE0. These settings will be needed to access the corresponding module.

Program description

The program described in the article uses the ULCD library specially prepared for Arduino. Pictures for TE-ULCD should be stored on microSD.

The descriptions of the commands, registers and messages of the TE-ULCD graphic module used in the ULCD library were taken from the operator's manual for the TE-ULCD35/56 modules. The TE-ULCD module supports two operating modes: terminal and operating mode using a library of graphical functions (presented in this example).

Currently, the set of built-in widgets (graphical user interface primitives) of TE-ULCD includes:

    Frame (0x01). Required, used to host widgets.

    Window (0x00). Designed for placing widgets, it has a specified set of properties.

    Panel (0x06). Designed for placing widgets, it has a specified set of properties.

    StaticLine (0x12). It is a line with a shadow and can be used to separate some components from others.

    Button (0x0A). Allows you to place a button and perform some action when you click on it.

    Text (0x07). Used to display text on the screen.

    Bitmap (0x05). Designed to display images in bmp format.

    RotateControl (0x0V). Designed to display an image of a regulator in the form of a rotating “wheel”.

    Slider (0x0C). Designed to display an image of the controller in the form of a “slider” on the screen.

Using the ULCD Library

The ULCD library for Arduino implements the following procedures for working with the TE-ULCD universal display module:

    ULCD() - constructor;

    void RESET() - software reset of the module;

    void digitalPortWrite(byte value) - sending one byte from Arduino to TE-ULCD;

    void LOAD_FONT(byte R, String FileName) - loading a font from the TE-ULCD flash memory into the TE-ULCD register;

    void LOAD_PICTURE(byte R, String FileName) - loading a picture in BMP format from a microSD card into the TE-ULCD register;

    void LOAD_TEXT(byte R, String Text) - loading a text string from Arduino into the TE-ULCD register;

    void LOAD_SCRIPT(byte R, byte Number) - loading a script from Arduino into the TE-ULCD register;

    void SET_SIZE(int X, byte Y) - setting the widget size;

    void SET_POS(int X, byte Y) - setting the position (lower left corner) of the widget;

    void SET_BACK_COLOR(byte R, byte G, byte B) - setting the background color of the widget;

    void SET_FONT_COLOR(byte R, byte G, byte B) - setting the widget font color;

    void SET_FONT(byte R) - setting the widget font from the TE-ULCD register;

    void SET_MAIN(byte R) - setting the widget as the main one (applies only to the frame);

    void SET_SCALE(byte min, byte max, byte pos) - setting the minimum, maximum and default values ​​of the widget (for the slider and the wheel);

    void SET_SCRIPT(byte R) - setting the script for the widget (the action that will be performed by TE-ULCD upon a given event) from the TE-ULCD register;

    void SET_TEXT(byte R) - setting a string for the widget from the TE-ULCD register;

    void SET_PICTURE(byte R) - setting a picture in BMP format for the widget from the TE-ULCD register;

    void SEND_REG(byte R1, byte R2) - send the contents of register R2 to R1;

    void WRITE_REG(byte R, byte value) - writing a value to the specified TE-ULCD register;

    void CR_WID(byte WidType) - creating a widget of the specified type (from the list of built-in TE-ULCD widgets);

    byte READ(byte R) - read the contents of the TE-ULCD register;

    void REPAINT_TEXT(byte R1, byte R2, String Text) - replace (redraw) the widget text stored in the R1 register with the text transferred in the Text variable, save the text in the R2 register;

    void REPAINT_BMP(byte R1, byte R2) - redraw the picture of the widget stored in the R1 register to the picture stored in the R2 register;

For example, the background image in the program is set as follows:

#include ULCD lcd; // ... lcd.LOAD_PICTURE (1, "back.bmp" ) ; //Load the picture from microSD into register R1 lcd.CR_WID(5); //Create a BitMap widget (for the background) lcd.SET_SIZE(320, 240); //Set the BitMap size equal to the TE-ULCD35 screen size lcd.SET_POS(0, 0); //Set BitMap position lcd.SET_PICTURE(1); //set the image for the widget from register R1

For user convenience, TE-ULCD has 32 registers (R0-R31) general purpose for storing pointers to widgets (pictures, text, scripts). If desired, pointers can be stored in the Arduino.

Getting traffic status

I wanted to make my own traffic light immediately after I saw a similar one in Yandex, only there it was controlled from a PC, but I still want an autonomous one - just an Arduino and an Ethernet Shield. You cannot receive a direct request about the traffic status from the Yandex.Traffic server. A letter to the technical support team of Ya.probka also did not help: “Thank you for your attention to our service. We do not supply such information. Try connecting the traffic jam module and using the “Traffic” control.”

To obtain the state of road traffic, I used the informer, or rather the picture that is transmitted in it. The algorithm of actions is as follows:

    Connect to the server (info.maps.yandex.net);

    We analyze the resulting image, it is transmitted in the PNG standard (0xFF 0xA4 0x00 yellow, 0x3F 0xBB 0x00 green, 0xFF 0x2A 0x00 red), the presence of colors is unique for each state green-yellow-red (even moreover, by counting the number of pixels of each color you can determine the score plugs, not just color);

    We display the picture on the TE-ULCD screen.

The request for an informer image has the following form:

GET http://info.maps.yandex.net/traffic/moscow/current_traffic_88.gif HTTP/1.1 Accept: image/gif Accept-Language: en-US; Cache-Control: max-age=0 Host: info.maps.yandex.net User-Agent: Chrome

This request is suitable for Moscow, but you can request the traffic status in any city for which the Ya.Traffic informer service operates. This block, with a little modification, can be used to control your own traffic light using Arduino and relays, it will be like in Yandex :).

Getting time

The simplest and easiest way to get time in UTC format is to send a request to some server (at first I used Google, but then to save memory I switched to the Yandex.Traffic server) and parse the response, the resulting string looks like this:

Currently the request to get the time looks like this:

GET http://info.maps.yandex.net/traffic/moscow HTTP/1.1

The accuracy of such time is not high - up to minutes, but for simple watch fits.

Getting a weather forecast

To get the weather forecast for the next day, I used the service for receiving an informer from GisMeteo in XML format. Weather data is a detailed summary of all weather parameters, in 6-hour increments and one day in advance. Everything is simple here, we indicate the city in the request and receive a weather forecast for it in response, we parse it and display the forecast for the next 6 hours on the screen.

int freeRam () ( extern int __heap_start, * __brkval; int v; return (int ) & v - (__brkval == 0 ? (int ) & __heap_start : (int ) __brkval) ; )

If someone can tell me how to improve the program, I will be grateful :), there is for discussion

The touchscreen display will be a decoration for any Arduino project.

In this article we will look at a touchscreen display shield with a built-in slot for a microSD card. The TFT display has a 2.8" diagonal, backlighting, which uses 4 white LEDs, and the ability to display 262,000 shades of colors (18 bits)! The display has a resolution of 240x320 pixels with individual control. Please note that this is much more than, for example, black -white LCD display 5110. The shield has a built-in resistive touchscreen, which allows you to determine the position of your finger when you press the screen.

General information and technical characteristics of TFT LCD shield 2.8"

TFT shield is sold fully assembled, ready to use. You just need to install it on top of your Arduino and connect the necessary library to the Arduino IDE. The installation/commissioning/first start-up procedure will take no more than 10 minutes!

The TFT shield has a built-in controller with RAM buffering. As a result, most operations are transferred to the shield itself, rather than loading the controller onto the Arduino. To connect a TFT display shield, a few pins are enough: 12 pins are responsible for the display, 13 for the operation of the SD card, if you use one.

Of course, the manufacturers did not leave us alone with the datasheet and the wish “Good luck!” There are libraries that will greatly facilitate your work with the TFT shield.

There is an excellent open-source graphics library that allows you to draw pixels, lines, rectangles, circles and text: Download on Github.

In addition, a touchscreen library has been written: Download on Github, which determines x, y and z coordinates (pressure), which contains an example sketch to demonstrate these capabilities. This sketch is written for Arduino, but can be adapted for other microcontrollers!

TFT display specifications:

  • The diagonal of the LCD TFT display is 2.8"
  • Resolution 240x320 pixels, 18-bit (262000) color gamut
  • ILI9325 or ILI9328 controller with built-in buffer random access memory
  • 8-bit digital interface, plus 4 control lines
  • Uses digital pins 5-13 and analog 0-3. This means that you can use digital pins 2, 3 and analog 4 and 5. Pin 12 is also available if you are not using a microSD card
  • Compatible with any Arduino "328 or Mega board
  • Compatible with 5V! Can use 3.3V and 5V logic power
  • There is a built-in LDO regulator 3.3 V @ 300 mA LDO regulator
  • Illuminated with 4 white LEDs. Enabled by default. For control, you can connect a transistor to a backlit digital pin
  • 4-wire resistive touch screen

Additional questions and answers

I looked at the datasheet and found that an SPI interface is available. Why are you using a parallel interface? SPI is better, fewer pins will be used!

Indeed, the driver on the display supports SPI, but there are no displays that can use it. On the touchscreen shield the corresponding pins are simply not displayed as connectors. This is most likely due to the fact that the transfer speed over SPI would be very slow.

All pins are included! How can I connect something else to the Arduino?

Example of drawing on a touch screen

This LCD TFT shield has a built-in 2.8" 4-wire resistive display. It can be used to determine the contact point of a finger, stylus, etc. To work with a touch display, you will need 4 pins on the Arduino.

You can download the example here: Github repository. Don't forget to unzip the downloaded file and move it to your Arduino IDE libraries folder.

The touch display is connected to Arduino as follows:

  • Y+ connects to analog pin 1
  • Y - connects to digital pin 7
  • X+ connects to digital pin 6
  • X - connects to analog pin 2

Once connected, download the tftpaint_shield example, which is located in the TFTLCD library. “Boxes with flowers” ​​will appear on the right side of the screen. You can click on one of the boxes to select the color you will paint with. By clicking on the left side of the screen you can clear it.

The touch display is made of thin glass. He is very fragile. The slightest crack or damage will render it unusable. Be careful when moving the display, especially around the corners. To interact with the resistive screen, you can use not only your fingers, but also styluses. Of course, you shouldn’t put too much pressure on the surface of the display either.


Uploading pictures

The 2.8" TFT LCD display has a built-in slot for a micoSD card. This slot can be used to upload images! Pre-format the card in FAT32 or FAT16 (more details on how an SD card works with Arduino are shown here).

In most example sketches, the SD card will not work. It must be initialized first.

To increase data transfer speed, you can download an additional library here: Fixes & Updates to the Arduino SD Library. Don't forget to copy the extracted library to the appropriate folder in the Arduino IDE.

If you are using Arduino Mega, make some changes to the SD/utility/Sd2Card.h file. You need to remove the comment tag from the line #define MEGA_SOFT_SPI 1. Thanks to this, to exchange data with the SD card, Arduino Mega will be able to use the same pins as classic Arduino. For testing, you can download this image of a tiger: Download this tiger bitmap and save it to the microsd card!

Launch the Arduino IDE and select the tftbmp_shield sketch. Upload it to your Arduino and voila! The screen will display the following:


Images smaller than 240x320 pixels are suitable for uploading. Drawings must be saved in 24-bit BMP format. Even if the drawing was not originally 24-bit, resave it, as this is the easiest format to read from using Arduino. You can rotate pictures using the setRotation() procedure.

Backlight control

By default, Shield developers assume that you will use the backlight all the time. However, you can control its brightness using PWM outputs or turn it off altogether to save energy. To do this you will need to work a little. Find two backlight connectors on the back of the 2.8" TFT LCD shield. Using a knife, remove the track between the VCC terminals and connect the two squares labeled Pin3. After this, you can control the backlight using digital pin 3.

Leave your comments, questions and share personal experience below. New ideas and projects are often born in discussions!

The shield in question is a board with built-in display and control modules. Indication is carried out using the TC1602 LCD display, control is via built-in buttons. It is possible to adjust the display brightness directly on the board using a trim resistor. The board is equipped with connectors into which other devices, such as sensors, can be connected. To work with the screen, pins 4-10 are used; to detect button presses, only one analog pin A0 is used. Digital pins 0-3, 11-13 and analog pins A1-A5 are free.

The main areas of application of the shield: the creation of control modules that implement device settings using the menu interface. The shield screen can be used to display information received from sensors, with the ability for the user to perform any actions by pressing the built-in buttons. Naturally, you can find other ways to use the board: for example, to implement a game like Tetris.

Specifications

  • Display type: LCD 1602, character, 4-bit mode.
  • Resolution: 16×2 (two lines of 16 characters each). Familiar place 5x8 points.
  • Display color: blue (options with yellow and green). The letters are white.
  • Technology: STN, Transflective, Positive.
  • Display controller: HD44780U.
  • Screen refresh rate limit: 5Hz
  • Display power: 5 Volts
  • Buttons: 6 buttons (5 control and reset buttons).
  • Additional elements: backlight brightness adjustment (potentiometer).
  • Screen operating temperature: from -20 °C to +70 °C;
  • Screen storage temperature: from -30 °C to +80 °C.

LCD shield pinout for connecting to Arduino

Display contactLCD 1602 Description Contact atLCD Shield
PinsLCD screen
GNDEarth
VDDPower supply 5V
ContrastContrast controlPotentiometer
R.S.Commands/Data8
R/WRead/Write
EnableTurning on (activation)9
DB0Not used
DB1Not used
DB2Not used
DB3Not used
DB4Date 14
DB5Date 25
DB6Date 36
DB7Date 47
Back LED+Turn on the backlight10
Back LED –Backlight power
Pins for buttons
UP buttonControl buttonA0
DOWN buttonControl buttonA0
LEFT buttonControl buttonA0
RIGHT buttonControl buttonA0
SELECT buttonControl buttonA0
ResetReset
ICSPICSP for flashing the built-in microcontroller HD44780U
UARTContacts for UART connection0, 1

Additional shield elements

  • Indicator LED (turns on when power is connected to the board).
  • Contact pads for connecting analog devices (GND, VSS, data pin).
  • Potentiometer for adjusting screen contrast.

Connecting LCD Shield Board to Arduino

Connecting the shield is very simple - you need to place the legs into the corresponding connectors of the Arduino board and carefully align them. There is no need to connect or solder anything additional. You need to remember and take into account the fact that some pins are reserved for controlling the display and buttons and cannot be used for other needs! For ease of connection additional equipment The board has additional 5V and GND connectors to each analog pin pad. This certainly makes working with sensors easier. You can also connect digital devices via free pins 0-3 and 11-13. Having connected the shield, we can work with the screen and buttons on it in the same way as with individual devices, taking into account only the numbers of the pins to which the corresponding contacts are soldered.

Sketch for the screen on Arduino LCD shield

To work with LCD screens, the popular LiquidCrystal library is usually used. At the initialization stage, an object of the LiquidCrystal class is created, in the constructor of which we specify pins with connected screen contacts. For our shield we need to use this option: LiquidCrystal lcd(8, 9, 4, 5, 6, 7); Sequence of constructor arguments:

  • RS (8)
  • Enable (9)
  • data(4)
  • data(5)
  • data(6)
  • data(7)

There is nothing complicated about working with an object. In setup() we initialize the object by giving it the number of characters and lines:

Lcd.begin(16, 2);

To display information on the display, use the print() method:

Lcd.print (“Arduino Master!”);

The text will be displayed at the current location of the cursor (at the beginning of the sketch, this is the first line and the first character). To specify an arbitrary cursor position, you can use the setCursor(<столбец>, <строка>):

Lcd.setCursor(0, 0); // First character of the first line lcd.setCursor(0, 1); // First character of the second line lcd.setCursor(2, 1); // Third character of the second line

LCD Keypad Shield Buttons

There are five control buttons on the board, which are operated through one analog pin A0. The shield uses a fairly common method of simple signal encoding, in which each button generates a certain voltage value, which after the ADC is converted into the corresponding value from 0 to 1023. Thus, we can transmit information about pressing different buttons through one pin, reading it using functions;

Signal level values ​​on pin A0 depending on the selected button:

Button press Analog pin value
RIGHT0-100
U.P.100-200
DOWN200-400
LEFT400-600
SELECT600-800
Key not pressed800-1023

An example of a sketch of working with LCD Keypad Shield buttons:

Int keyAnalog = analogRead(A0); if (keyAnalog< 100) { // Значение меньше 100 – нажата кнопка right // Выполняем какое-то действие для кнопки вправо. } else if (keyAnalog < 200) { // Значение больше 100 (иначе мы бы вошли в предыдущий блок результата сравнения, но меньше 200 – нажата кнопка UP // Выполняем какое-то действие для кнопки вверх } else if (keyAnalog < 400) { // Значение больше 200, но меньше 400 – нажата кнопка DOWN // Выполняем действие для кнопки вниз } else if (keyAnalog < 600) { // Значение больше 400, но меньше 600 – нажата кнопка LEFT // Выполняем действие для кнопки влево } else if (keyAnalog < 800) { // Значение больше 600, но меньше 800 – нажата кнопка SELECT // Выполняем действие для кнопки выбора пункта меню } else { // Все остальные значения (до 1023) будут означать, что нажатий не было }

There are two main disadvantages to the chosen encoding method:

  • You cannot track the simultaneous pressing of several buttons;
  • Possible signal distortions can lead to false alarms.

You need to take these limitations into account when choosing this SSD in your projects if you plan to use the device in systems with a lot of noise that can distort the signal at the A0 input, which is why the ADC can generate an erroneous value and the sketch will execute different instructions as a result.

An example sketch for working with the screen and menu buttons

In this example, we detect the currently pressed button and display its name on the screen. Please note that for convenience, we have separated the button definition operation into a separate function. Also in the sketch we highlighted a separate method for displaying text on the screen. In it we show a message (message parameter) and clear it after a second. It must be remembered that during this second, button presses are not processed

#include LiquidCrystal lcd(8, 9, 4, 5, 6, 7); #define BTN_UP 1 #define BTN_DOWN 2 #define BTN_LEFT 3 #define BTN_RIGHT 4 #define BTN_SELECT 5 #define BTN_NONE 10 int detectButton() ( int keyAnalog = analogRead(A0); if (keyAnalog< 100) { // Значение меньше 100 – нажата кнопка right return BTN_RIGHT; } else if (keyAnalog < 200) { // Значение больше 100 (иначе мы бы вошли в предыдущий блок результата сравнения, но меньше 200 – нажата кнопка UP return BTN_UP; } else if (keyAnalog < 400) { // Значение больше 200, но меньше 400 – нажата кнопка DOWN return BTN_DOWN; } else if (keyAnalog < 600) { // Значение больше 400, но меньше 600 – нажата кнопка LEFT return BTN_LEFT; } else if (keyAnalog < 800) { // Значение больше 600, но меньше 800 – нажата кнопка SELECT return BTN_SELECT; } else { // Все остальные значения (до 1023) будут означать, что нажатий не было return BTN_NONE; } } void clearLine(int line){ lcd.setCursor(0, 1); lcd.print(" "); } void printDisplay(String message){ Serial.println(message); lcd.setCursor(0, 1); lcd.print(message); delay(1000); clearLine(1); } void setup() { Serial.begin(9600); lcd.begin(16, 2); lcd.print("Arduino Master"); delay(3000); lcd.setCursor(0, 0); lcd.print("Arduino Master"); } void loop() { int button = detectButton(); switch (button) { case BTN_UP: printDisplay("UP"); break; case BTN_DOWN: printDisplay("DOWN"); break; case BTN_LEFT: printDisplay("LEFT"); break; case BTN_RIGHT: printDisplay("RIGHT"); break; case BTN_SELECT: printDisplay("SELECT"); break; default: //printDisplay("Press any key"); break; } }

Brief conclusions about the LCD keypad shield expansion board

The LCD Keypad expansion board is quite popular, it is simple and easy to use in Arduino projects. Today you can easily buy it in almost any online store.

Pros of LCD Shield:

  • Makes it easy to connect the LCD screen.
  • Reduces general dimensions devices, because removes protruding wires and circuit boards.
  • Reduces the number of errors associated with incorrect installation and connection.
  • Adds push-button control functionality if the board has buttons installed (LCD Keypad shield).

Flaws:

  • The cost of a shield is higher than the cost of a separate screen.
  • Additional functionality in the form of buttons is not always needed.
  • The shield consumes more energy than individual board elements.


If you find an error, please select a piece of text and press Ctrl+Enter.