Arduino:Примеры/graphicstest
Перейти к навигации
Перейти к поиску
Поддержать проект | Содержание | Знакомство с Arduino | Продукты | Основы | Справочник языка Arduino | Примеры | Библиотеки | Хакинг | Изменения | Сравнение языков Arduino и Processing |
Перевод: Максим Кузьмин (Cubewriter) Контакты:</br>* Skype: cubewriter</br>* E-mail: cubewriter@gmail.com</br>* Максим Кузьмин на freelance.ru
Проверка/Оформление/Редактирование: Мякишев Е.А.
Содержание
Графический тест[1]
Это текстовый скетч для библиотеки ST7735, который при помощи платы Arduino совершает с TFT-дисплеем различные действия: печатает текст, картинки, рисует фигуры и пр.
Код
1
2 /***************************************************
3
4 Графический тест
5
6 Эта библиотека предназначена для работы с TFT-дисплеями (с SPI-интерфейсом) от Adafruit. Библиотека поддерживает следующие устройства:
7
8 * 1,8-дюймовую TFT-плату с SD-картой:
9 https://www.adafruit.com/products/358
10 * 1,8-дюймовый TFT-модуль:
11 https://www.adafruit.com/product/802
12 * 1,44-дюймовую TFT-плату:
13 https://www.adafruit.com/product/2088
14 * «Голый» 1,8-дюймовый TFT-дисплей (без плат и модулей):
15 https://www.adafruit.com/products/618
16
17 Руководства и схемы подключения ищите по ссылкам выше. Этим дисплеям
18 для коммуникации требуется SPI-интерфейс с 4 или 5 контактами (контакт
19 RST опционален).
20
21 Adafruit инвестировала время и ресурсы, создавая эту библиотеку с
22 открытым кодом. Пожалуйста, поддержите Adafruit и оборудование с
23 открытым кодом, покупая продукты Adafruit!
24
25 Библиотека написана Лимор Фрид (Limor Fried, Ladyada) для Adafruit
26 Industries. Весь текст выше должен быть включен при любом повторном
27 распространении.
28
29 ****************************************************/
30
31 #include <Adafruit_GFX.h> // подключаем графическую библиотеку
32 #include <Adafruit_ST7735.h> // подключаем библиотеку для управления дисплеем
33 #include <SPI.h>
34
35
36 // для TFT-платы можно использовать 2-3 контакта;
37 // эти контакты будут работать и для 1,8-дюймового TFT-модуля:
38 #define TFT_CS 10
39 #define TFT_RST 9 // этот контакт можно подключить к RESET-
40 // контакту Arduino, но тогда вместе «9»
41 // надо указать «0».
42 #define TFT_DC 8
43
44 // Вариант 1 (рекомендуемый): используются аппаратные SPI-контакты
45 // (на UNO: SCLK – это 13-ый контакт, а MOSI – это 11-ый контакт),
46 // а 10-ый контакт должен быть выходным. Этот способ быстрее, и его
47 // необходимо использовать, если вы работаете с картой microSD
48 // (подробнее смотрите в примере, где рисуется изображение):
49 Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
50
51 // Вариант 2: можно использовать любые контакты,
52 // но процесс будет идти медленней!
53 #define TFT_SCLK 13 // здесь можно задать любой контакт
54 #define TFT_MOSI 11 // здесь можно задать любой контакт
55 //Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
56
57
58 float p = 3.1415926;
59
60 void setup(void) {
61 Serial.begin(9600);
62 Serial.print("Hello! ST7735 TFT Test"); // "Привет! Это тест TFT-дисплея ST7735"
63
64 // используйте этот инициализатор, если работаете
65 // с 1,8-дюймовым TFT-дисплеем:
66 tft.initR(INITR_BLACKTAB); // инициализируем чипa ST7735S, черный ярлычок
67
68 // используйте этот инициализатор, если работаете
69 // с 1,44-дюймовым TFT-дисплеем (нужно раскомментировать):
70 //tft.initR(INITR_144GREENTAB); // инициализируем чипa ST7735S, зеленый ярлычок
71
72 Serial.println("Initialized"); // "Дисплей инициализирован"
73
74 uint16_t time = millis();
75 tft.fillScreen(ST7735_BLACK);
76 time = millis() - time;
77
78 Serial.println(time, DEC);
79 delay(500);
80
81 // большой блок текста:
82 tft.fillScreen(ST7735_BLACK);
83 testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST7735_WHITE);
84 delay(1000);
85
86 // функция печати на TFT-дисплее:
87 tftPrintTest();
88 delay(4000);
89
90 // рисуем один пиксель:
91 tft.drawPixel(tft.width()/2, tft.height()/2, ST7735_GREEN);
92 delay(500);
93
94 // тест, проверяющий рисование линии:
95 testlines(ST7735_YELLOW);
96 delay(500);
97
98 // оптимизированные линии:
99 testfastlines(ST7735_RED, ST7735_BLUE);
100 delay(500);
101
102 testdrawrects(ST7735_GREEN);
103 delay(500);
104
105 testfillrects(ST7735_YELLOW, ST7735_MAGENTA);
106 delay(500);
107
108 tft.fillScreen(ST7735_BLACK);
109 testfillcircles(10, ST7735_BLUE);
110 testdrawcircles(10, ST7735_WHITE);
111 delay(500);
112
113 testroundrects();
114 delay(500);
115
116 testtriangles();
117 delay(500);
118
119 mediabuttons();
120 delay(500);
121
122 Serial.println("done"); // "Дисплей инициализирован"
123 delay(1000);
124 }
125
126 void loop() {
127 tft.invertDisplay(true);
128 delay(500);
129 tft.invertDisplay(false);
130 delay(500);
131 }
132
133 void testlines(uint16_t color) {
134 tft.fillScreen(ST7735_BLACK);
135 for (int16_t x=0; x < tft.width(); x+=6) {
136 tft.drawLine(0, 0, x, tft.height()-1, color);
137 }
138 for (int16_t y=0; y < tft.height(); y+=6) {
139 tft.drawLine(0, 0, tft.width()-1, y, color);
140 }
141
142 tft.fillScreen(ST7735_BLACK);
143 for (int16_t x=0; x < tft.width(); x+=6) {
144 tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
145 }
146 for (int16_t y=0; y < tft.height(); y+=6) {
147 tft.drawLine(tft.width()-1, 0, 0, y, color);
148 }
149
150 tft.fillScreen(ST7735_BLACK);
151 for (int16_t x=0; x < tft.width(); x+=6) {
152 tft.drawLine(0, tft.height()-1, x, 0, color);
153 }
154 for (int16_t y=0; y < tft.height(); y+=6) {
155 tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
156 }
157
158 tft.fillScreen(ST7735_BLACK);
159 for (int16_t x=0; x < tft.width(); x+=6) {
160 tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
161 }
162 for (int16_t y=0; y < tft.height(); y+=6) {
163 tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
164 }
165 }
166
167 void testdrawtext(char *text, uint16_t color) {
168 tft.setCursor(0, 0);
169 tft.setTextColor(color);
170 tft.setTextWrap(true);
171 tft.print(text);
172 }
173
174 void testfastlines(uint16_t color1, uint16_t color2) {
175 tft.fillScreen(ST7735_BLACK);
176 for (int16_t y=0; y < tft.height(); y+=5) {
177 tft.drawFastHLine(0, y, tft.width(), color1);
178 }
179 for (int16_t x=0; x < tft.width(); x+=5) {
180 tft.drawFastVLine(x, 0, tft.height(), color2);
181 }
182 }
183
184 void testdrawrects(uint16_t color) {
185 tft.fillScreen(ST7735_BLACK);
186 for (int16_t x=0; x < tft.width(); x+=6) {
187 tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
188 }
189 }
190
191 void testfillrects(uint16_t color1, uint16_t color2) {
192 tft.fillScreen(ST7735_BLACK);
193 for (int16_t x=tft.width()-1; x > 6; x-=6) {
194 tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
195 tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
196 }
197 }
198
199 void testfillcircles(uint8_t radius, uint16_t color) {
200 for (int16_t x=radius; x < tft.width(); x+=radius*2) {
201 for (int16_t y=radius; y < tft.height(); y+=radius*2) {
202 tft.fillCircle(x, y, radius, color);
203 }
204 }
205 }
206
207 void testdrawcircles(uint8_t radius, uint16_t color) {
208 for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
209 for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
210 tft.drawCircle(x, y, radius, color);
211 }
212 }
213 }
214
215 void testtriangles() {
216 tft.fillScreen(ST7735_BLACK);
217 int color = 0xF800;
218 int t;
219 int w = tft.width()/2;
220 int x = tft.height()-1;
221 int y = 0;
222 int z = tft.width();
223 for(t = 0 ; t <= 15; t+=1) {
224 tft.drawTriangle(w, y, y, x, z, x, color);
225 x-=4;
226 y+=4;
227 z-=4;
228 color+=100;
229 }
230 }
231
232 void testroundrects() {
233 tft.fillScreen(ST7735_BLACK);
234 int color = 100;
235 int i;
236 int t;
237 for(t = 0 ; t <= 4; t+=1) {
238 int x = 0;
239 int y = 0;
240 int w = tft.width()-2;
241 int h = tft.height()-2;
242 for(i = 0 ; i <= 16; i+=1) {
243 tft.drawRoundRect(x, y, w, h, 5, color);
244 x+=2;
245 y+=3;
246 w-=4;
247 h-=6;
248 color+=1100;
249 }
250 color+=100;
251 }
252 }
253
254 void tftPrintTest() {
255 tft.setTextWrap(false);
256 tft.fillScreen(ST7735_BLACK);
257 tft.setCursor(0, 30);
258 tft.setTextColor(ST7735_RED);
259 tft.setTextSize(1);
260 tft.println("Hello World!"); // "Привет, мир!"
261 tft.setTextColor(ST7735_YELLOW);
262 tft.setTextSize(2);
263 tft.println("Hello World!"); // "Привет, мир!"
264 tft.setTextColor(ST7735_GREEN);
265 tft.setTextSize(3);
266 tft.println("Hello World!"); // "Привет, мир!"
267 tft.setTextColor(ST7735_BLUE);
268 tft.setTextSize(4);
269 tft.print(1234.567);
270 delay(1500);
271 tft.setCursor(0, 0);
272 tft.fillScreen(ST7735_BLACK);
273 tft.setTextColor(ST7735_WHITE);
274 tft.setTextSize(0);
275 tft.println("Hello World!"); // "Привет, мир!"
276 tft.setTextSize(1);
277 tft.setTextColor(ST7735_GREEN);
278 tft.print(p, 6);
279 tft.println(" Want pi?"); // " А хотите число «Пи»?"
280 tft.println(" ");
281 tft.print(8675309, HEX); // печатаем число «8,675,309» в шестнадцатеричном виде
282 tft.println(" Print HEX!"); // " Печатаем шестнадцатеричный формат!"
283 tft.println(" ");
284 tft.setTextColor(ST7735_WHITE);
285 tft.println("Sketch has been"); // "Скетч"
286 tft.println("running for: "); // "работает в течение: "
287 tft.setTextColor(ST7735_MAGENTA);
288 tft.print(millis() / 1000);
289 tft.setTextColor(ST7735_WHITE);
290 tft.print(" seconds."); // " секунд."
291 }
292
293 void mediabuttons() {
294 // кнопка «Play»:
295 tft.fillScreen(ST7735_BLACK);
296 tft.fillRoundRect(25, 10, 78, 60, 8, ST7735_WHITE);
297 tft.fillTriangle(42, 20, 42, 60, 90, 40, ST7735_RED);
298 delay(500);
299 // кнопка «Пауза»:
300 tft.fillRoundRect(25, 90, 78, 60, 8, ST7735_WHITE);
301 tft.fillRoundRect(39, 98, 20, 45, 5, ST7735_GREEN);
302 tft.fillRoundRect(69, 98, 20, 45, 5, ST7735_GREEN);
303 delay(500);
304 // цветная кнопка «Play» (синяя):
305 tft.fillTriangle(42, 20, 42, 60, 90, 40, ST7735_BLUE);
306 delay(50);
307 // цветная кнопка «Pause»:
308 tft.fillRoundRect(39, 98, 20, 45, 5, ST7735_RED);
309 tft.fillRoundRect(69, 98, 20, 45, 5, ST7735_RED);
310 // цветная кнопка «Play» (зеленая):
311 tft.fillTriangle(42, 20, 42, 60, 90, 40, ST7735_GREEN);
312 }
См.также
Внешние ссылки