Introduction: Arduino With Touch Screen Display
Would you like to create more personalized menus and better human/machine interfaces? For such projects, you can use an Arduino and a Touch Screen Display. Does this idea sound enticing? If so, check out the video today, where I will show you an assembly with a Mega Arduino and a Touch Screen Display. You will see how to make the designs you want on the screen, and also how to determine the screen region to touch and activate a specific command. I emphasize that I chose to use the Arduino Mega due to its amount of pins.
So today, I'll introduce you to the Touch Screen display, its graphic functions, and how to grab the touch point on the screen. Let's also create an example containing all the elements, such as positioning, writing, designing shapes, colors, and touch.
Step 1: Arduino Mega 2560
Step 2: TFT LCD Shield 2.4"
This display that we use in our project has an interesting feature: it has an SD card. However, the writing and reading involved in this will be shown in another video, which I will soon produce. The objective of today’s lesson is to specifically address the graphic and touch screen features of this display.
Characteristics:
Screen Dimension: 2.4 inches
MicroSD card slot
Color LCD: 65K
Driver: ILI9325
Resolution: 240 x 320
Touchscreen: 4-wire resistive touchscreen
Interface: 8 bit data, plus 4 control lines
Operating voltage: 3.3-5V
Dimensions: 71 x 52 x 7mm
Step 3: Libraries
Add the libraries:
"SWTFT"
Click on the links and download the libraries.
Unzip the file and paste it into the libraries folder of the Arduino IDE.
C: / Program Files (x86) / Arduino / libraries
Note
Before we start our program, we need to address something important: the TOUCH calibration.
Using a simple program to get the touch points on the display, store the value of the points (x, y) at each end (highlighted in yellow in the figure below). These values are important for mapping the touch to the graphic points on the screen.
#include <TouchScreen.h>
//Portas de leitura das coordenadas do touchvoid #define YP A1 // Y+ is on Analog1 #define XM A2 // X- is on Analog2 #define YM 7 // Y- is on Digital7 #define XP 6 // X+ is on Digital6 //objeto para manipulacao dos eventos de toque na tela TouchScreen ts = TouchScreen(XP, YP, XM, YM); void setup() { Serial.begin(9600); } void loop() { TSPoint touchPoint = ts.getPoint();//pega o touch (x,y,z=pressao) Serial.print("X: "); Serial.println(touchPoint.x); Serial.print("Y: "); Serial.println(touchPoint.y); delay(1000); }
Step 4: Functions
Now let's take a look at some graphical functions that libraries can offer us.
1. drawPixel
The drawPixel function is responsible for painting a single point on the screen at the given point.
void drawPixel (int16_t x, int16_t and, uint16_t color);
2. drawLine
The drawLine function is responsible for drawing a line from two points.
<p>void drawLine (int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color);</p>
3. drawFastVLine
The drawFastVLine function is responsible for drawing a vertical line from a point and a height.
void drawFastVLine (int16_t x, int16_t y, int16_t h, uint16_t color);
4. drawFastHLine
The drawFastHLine function is responsible for drawing a horizontal line from a point and a width.
void drawFastHLine (int16_t x, int16_t y, int16_t w, uint16_t color);
5. drawRect
The drawRect function is responsible for drawing a rectangle on the screen, passing a point of origin, its height and width.
void drawRect (int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color);
6. fillRect
The fillRect function is the same as drawRect, but the rectangle will be filled with the given color.
void fillRect (int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color);
7. drawRoundRect
The drawRoundRect function is the same as drawRect, but the rectangle will have rounded edges.
<p>void drawRoundRect (int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color);</p>
8. fillRoundRect
The fillRoundRect function is the same as drawRoundRect, but the rectangle will be filled with the given color.
void fillRoundRect (int16_t x0, int16_t y0, int16_t w, int16_t h, int16_t radius, uint16_t color);
9. drawTriangle
The drawTriangle function is responsible for drawing a triangle on the screen, passing the point of the 3 vertices.
void drawTriangle (int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color);
10. fillTriangle
The fillTriangle function is the same as drawTriangle, but the triangle will be filled with the given color.
void fillTriangle (int16_t x0, int16_t y0, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint16_t color);
11. drawCircle
The drawCircle function is responsible for drawing a circle from a source point and a radius.
void drawCircle (int16_t x0, int16_t y0, int16_t r, uint16_t color);
12. fillCircle
The fillCircle function is the same as drawCircle, but the circle will be filled with the given color.
void fillCircle (int16_t x0, int16_t y0, int16_t r, uint16_t color);
13. fillScreen
The fillScreen function is responsible for filling the screen with a single color.
void fillScreen (uint16_t color);
14. setCursor
The setCursor function is responsible for positioning the cursor for writing to a given point.
void setCursor (int16_t x, int16_t y);
15. setTextColor
The setTextColor function is responsible for assigning a color to the text to be written. We have two ways to use it:
void setTextColor (uint16_t c); // sets the color of writing only<br>void setTextColor (uint16_t c, uint16_t bg); // set the writing color and background color
16. setTextSize
The setTextSize function is responsible for assigning a size to the text that will be written.
void setTextSize (uint8_t s);
17. setTextWrap
The setTextWrap function is responsible for breaking the line if it reaches the limit of the screen.
void setTextWrap (boolean w);
18. setRotation
The setRotation function is responsible for rotating the screen (landscape, portrait).
void setRotation (uint8_t r); // 0 (standard), 1,2,3
Step 5: Example
We will create a program in which we will use most of the resources that the display provides us.
Let's write some strings in different sizes, create three geometric figures, and pick up the touch event on them, each time we touch one of the figures, we will have the feedback of the figure name just below them.
Step 6: Libraries
First let's define the libraries that we will use.
#include <SWTFT.h> //responsável pela parte gráfica
#include <TouchScreen.h> //responsável por pegar os toques na tela
#include <SPI.h> //comunicação com o display
#include <Wire.h> //comunicação com o display
#include "math.h" //calcular potencia
Step 7: Defines
We will define some macros for the pins, and also the important values that we will use.
//Portas de leitura das coordenadas do touch
#define YP A1 // Y+ #define XM A2 // X- #define YM 7 // Y- #define XP 6 // X+ //valores encontrados através da calibração do touch //faça um código simples para imprimir os valores (x,y) a cada toque //então encontre os valores nas extremidades max/min (x,y) #define TS_MINX 130 #define TS_MINY 80 #define TS_MAXX 900 #define TS_MAXY 900 //tamanho dos textos #define TEXT_SIZE_L 3 #define TEXT_SIZE_M 2 #define TEXT_SIZE_S 1 //posicionamento dos textos de feedback #define FEEDBACK_LABEL_X 10 #define FEEDBACK_LABEL_Y 200 #define FEEDBACK_TOUCH_X 120 #define FEEDBACK_TOUCH_Y 200 //valores para detectar a pressão do toque #define MINPRESSURE 10 #define MAXPRESSURE 1000
We continue with the definition of some macros.
//Associa o nome das cores aos valores correspondentes
#define BLACK 0x0000 #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define YELLOW 0xFFE0 #define WHITE 0xFFFF //dados de criação do circulo const int circle_radius = 30; const int circle_x = 240; const int circle_y = 125; //objeto para manipulacao dos eventos de toque na tela TouchScreen ts = TouchScreen(XP, YP, XM, YM); //objeto para manipulacao da parte grafica SWTFT tft;
Step 8: Setup
In the setup, we will initialize our graphic control object and make the first configurations.
void setup() {
Serial.begin(9600); //reseta o objeto da lib grafica tft.reset(); //inicializa objeto controlador da lib grafica tft.begin(); delay(500); //rotaciona a tela para landscape tft.setRotation(1); //pinta a tela toda de preto tft.fillScreen(BLACK); //chama a função para iniciar nossas configurações initialSettings(); }
Step 9: Loop
In the loop, we will pick up the point at which we touch the screen, and see if the touch occurred in one of the figures.
void loop() {
TSPoint touchPoint = ts.getPoint();//pega o touch (x,y,z=pressao) pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); //mapeia o ponto de touch para o (x,y) grafico // o fato de termos rotacionado a tela para landscape implica no X receber o mapeamento de Y TSPoint p; p.x = map(touchPoint.y, TS_MINY, TS_MAXY, 0, 320); p.y = map(touchPoint.x, TS_MINX, TS_MAXX, 240, 0); //verifica se a pressão no toque foi suficiente if (touchPoint.z > MINPRESSURE && touchPoint.z < MAXPRESSURE) { //verifica se tocou no retangulo if(pointInRect(p)) { writeShape("Rect"); } //verifica se tocou no triangulo else if(pointInsideTriangle(TSPoint(110,150,0), TSPoint(150,100,0), TSPoint(190,150,0), p)) { writeShape("Triangle"); } //verifica se tocou no circulo else if(pointInCircle(p)) { writeShape("Circle"); } } }
Step 10: Check If We Touch the Circle
In this step we deal with screen initialization and define the colors of the texts to be displayed.
/*
Desenha na tela os elementos */ void initialSettings() { tft.setTextColor(WHITE); tft.setTextSize(TEXT_SIZE_S); tft.println("ACESSE"); tft.setTextColor(YELLOW); tft.setTextSize(TEXT_SIZE_M); tft.println("MEU BLOG"); tft.setTextColor(GREEN); tft.setTextSize(TEXT_SIZE_L); tft.println("FERNANDOK.COM"); createRect(); createTriangle(); createCircle(); tft.setCursor(FEEDBACK_LABEL_X, FEEDBACK_LABEL_Y); tft.setTextColor(CYAN); tft.setTextSize(TEXT_SIZE_L); tft.println("SHAPE: "); }
Step 11: Functions of Creating Geometric Shapes
We create a rectangle, a triangle, and a circle with the origins we determine.
//cria um retangulo com origem (x,y) = (10,100)
//width = 80 e height = 50 void createRect() { tft.fillRect(10, 100, 80, 50, RED); tft.drawRect(10, 100, 80, 50, WHITE); } //cria um triangulo com os vertices: //A = (110,150) ; B = (150,100) ; C = (190,150) void createTriangle() { tft.fillTriangle(110, 150, 150, 100, 190, 150, YELLOW); tft.drawTriangle(110, 150, 150, 100, 190, 150, WHITE); } //cria um circulo com origem no ponto (x,y) = (240,125) e raio = 30 void createCircle() { tft.fillCircle(240, 125, 30, GREEN); tft.drawCircle(240, 125, 30, WHITE); }
Step 12: Check If We Touch the Rectangle
This function checks if the point is inside the rectangle.
//Função que verifica se o ponto está dentro do retângulo
bool pointInRect(TSPoint p) { //max/min X do retangulo if( p.x >= 10 && p.x <= 90) { //max/min Y do retangulo if( p.y <= 150 && p.y >= 100) { return true; } } return false; }
Step 13: Check If We Touch the Circle
This is the same as with the circle.
//distancia entre pontos D = raiz( (xb-xa)^2 + (yb-ya)^2 )
//vefifica se o ponto está dentro do circulo //se a distancia do ponto pra origem do circulo for menor ou igual ao raio, ele está dentro bool pointInCircle(TSPoint p) { float distance = sqrt( pow(p.x - circle_x,2) + pow(p.y - circle_y,2)); if(distance <= circle_radius) { return true; } return false; }
Step 14: Check If We Touch the Triangle
The same check of that of the point also occurs within the triangle.
// Função que verifica se o ponto p esta dentro do triangulo ABC
// Se estiver dentro retorna TRUE senão retorna FALSE bool pointInsideTriangle(TSPoint a, TSPoint b, TSPoint c, TSPoint p){ float ABC = triangleArea(a, b, c); float ACP = triangleArea(a, c, p); float ABP = triangleArea(a, b, p); float CPB = triangleArea(c, p, b); if(ABC == ACP+ABP+CPB){ return true; } return false; } // Função que calcula a area de um triangulo com base nos pontos x,y float triangleArea(TSPoint a, TSPoint b, TSPoint c){ return fabs(((b.x - a.x)*(c.y - a.y) - (c.x - a.x) * (b.y - a.y))/2); }
Step 15: Function to Print the Name of the Object Touched
Here we write on the screen the name of the geometric figure that is used.
//escreve na tela o nome da figura geométrica que foi tocada
void writeShape(String shape) { tft.fillRect(FEEDBACK_TOUCH_X, FEEDBACK_TOUCH_Y, 170, 30, BLACK); tft.setCursor(FEEDBACK_TOUCH_X, FEEDBACK_TOUCH_Y); tft.setTextSize(TEXT_SIZE_G); tft.setTextColor(WHITE); tft.println(shape); }