Arduino:Примеры/GLCD BigDemo
Перейти к навигации
Перейти к поиску
Поддержать проект | Содержание | Знакомство с Arduino | Продукты | Основы | Справочник языка Arduino | Примеры | Библиотеки | Хакинг | Изменения | Сравнение языков Arduino и Processing |
Перевод: Максим Кузьмин (Cubewriter) Контакты:</br>* Skype: cubewriter</br>* E-mail: cubewriter@gmail.com</br>* Максим Кузьмин на freelance.ru
Проверка/Оформление/Редактирование: Мякишев Е.А.
Содержание
Большое демо [1]
Этот пример сочетает в себе несколько скетчей-примеров для библиотеки GLCD. Это неинтерактивный пример.
Код
1
2 /*
3 * Большое демо
4 *
5 * Неинтерактивное демо, показывающее несколько возможностей
6 * библиотеки GLCD.
7 * Комбинирует в себе несколько скетчей-примеров для библиотеки GLCD.
8 * Этот скетч использует 26 килобайт flash-памяти, поэтому на ATmega168
9 * его запустить не получится.
10 *
11 */
12
13 #include <Time.h> // загрузить можно тут: http://www.arduino.cc/playground/Code/Time
14 #include <glcd.h>
15
16 #include "fonts/allFonts.h" // здесь используются системный шрифт и шрифт arial14
17 #include "bitmaps/allBitmaps.h" // все нужные изображения находятся в папке «bitmap»
18
19
20 /*
21 * Проверяем размер дисплея, т.к. некоторым частям этого демо требуется
22 * большой дисплей.
23 */
24 #if DISPLAY_HEIGHT < 64
25 #error Скетчу «Большое демо» требуется дисплей, высота которого как минимум 64 пикселя
26 #endif
27 #if DISPLAY_WIDTH < 128
28 #error Скетчу «Большое демо» требуется дисплей, ширина которого как минимум 128 пикселей
29 #endif
30
31
32
33 Image_t icon;
34
35 gText textArea; // текстовая область, которая будет задана дальше в скетче
36 gText textAreaArray[3]; // массив текстовых областей
37 gText countdownArea = gText(GLCD.CenterX, GLCD.CenterY,1,1,Arial_14); // текстовая область для цифр обратного отсчета
38
39 unsigned long startMillis;
40 unsigned int loops = 0;
41 unsigned int iter = 0;
42 int theDelay = 20;
43
44 void setup()
45 {
46
47 GLCD.Init(); // инициализируем библиотеку в режиме рисования
48 if(GLCD.Height >= 64)
49 icon = ArduinoIcon64x64; // иконка высотой 64 пикселя
50 else
51 icon = ArduinoIcon64x32; // иконка высотой 32 пикселя
52 introScreen();
53 GLCD.ClearScreen();
54 GLCD.SelectFont(System5x7, BLACK); // шрифт для текстовой области по умолчанию
55 clockBegin(); // запускаем часы
56 clock(10); // в течение 10 секунд показываем часы, чтобы их можно было настроить
57
58 }
59
60 void loop()
61 {
62 GLCD.ClearScreen();
63 scribble(5000); // функция scribble() будет работать 5 секунд
64
65 GLCD.ClearScreen();
66
67 GLCD.SelectFont(System5x7, BLACK);
68 showCharacters("5x7 font:", System5x7);
69 countdown(3);
70 showCharacters("Arial_14:", Arial_14);
71 countdown(3);
72
73 clock(10); // показываем часы заданное количество секунд
74
75 life(20000); // 20 секунд
76
77 GLCD.ClearScreen();
78 textAreaDemo();
79
80 rocket(30000); // 30 секунд на игру «Ракета»
81
82 GLCD.SelectFont(System5x7, BLACK);
83 GLCD.ClearScreen();
84 scrollingDemo();
85
86 GLCD.ClearScreen();
87 FPS(GLCD.Width, GLCD.Height, 10000); // 10 секунд на функцию FPS()
88
89 if(GLCD.Width >= 192)
90 {
91 GLCD.ClearScreen();
92 FPS(GLCD.Width/2, GLCD.Height, 10000); // 10 секунд на функцию FPS()
93 }
94 }
95
96
97 void introScreen(){
98 GLCD.DrawBitmap(icon, 32,0); // рисуем картинку по указанным координатам X и Y
99 countdown(3);
100 GLCD.ClearScreen();
101 GLCD.SelectFont(Arial_14); // вы также можете создавать собственные шрифты
102 GLCD.CursorToXY(GLCD.Width/2 -44, 3);
103 GLCD.print("GLCD version "); // "Версия GLCD "
104 GLCD.print(GLCD_VERSION, DEC);
105 GLCD.DrawRoundRect(8,0,GLCD.Width-19,17, 5); // закругленный прямоугольник вокруг текстовой области
106 countdown(3);
107 GLCD.ClearScreen();
108 }
109
110
111 void showCharacters(char * title, Font_t font) {
112 // здесь будет показан выбранный шрифт
113 GLCD.ClearScreen();
114 GLCD.CursorTo(0,0);
115 GLCD.print(title);
116 GLCD.DrawRoundRect(GLCD.CenterX + 2, 0, GLCD.CenterX -3, GLCD.Bottom, 5); // закругленный прямоугольник вокруг текстовой области
117 textArea.DefineArea(GLCD.CenterX + 5, 3, GLCD.Right-2, GLCD.Bottom-4, SCROLL_UP);
118 textArea.SelectFont(font, BLACK);
119 textArea.CursorTo(0,0);
120 for(char c = 32; c < 127; c++){
121 textArea.print(c);
122 delay(20);
123 }
124 }
125
126 void drawSpinner(byte pos, byte x, byte y) {
127 // эта функция рисует объект, который появится в счетчике
128 switch(pos % 8) {
129 case 0 : GLCD.DrawLine( x, y-8, x, y+8); break;
130 case 1 : GLCD.DrawLine( x+3, y-7, x-3, y+7); break;
131 case 2 : GLCD.DrawLine( x+6, y-6, x-6, y+6); break;
132 case 3 : GLCD.DrawLine( x+7, y-3, x-7, y+3); break;
133 case 4 : GLCD.DrawLine( x+8, y, x-8, y); break;
134 case 5 : GLCD.DrawLine( x+7, y+3, x-7, y-3); break;
135 case 6 : GLCD.DrawLine( x+6, y+6, x-6, y-6); break;
136 case 7 : GLCD.DrawLine( x+3, y+7, x-3, y-7); break;
137 }
138 }
139
140 void textAreaDemo()
141 {
142 showArea( textAreaFULL, "Full");
143 showArea( textAreaTOP, "Top");
144 showArea( textAreaBOTTOM, "Bottom");
145 showArea( textAreaRIGHT, "Right");
146 showArea( textAreaLEFT, "Left");
147 showArea( textAreaTOPLEFT, "Top Left");
148 showArea( textAreaTOPRIGHT, "Top Right");
149 showArea( textAreaBOTTOMLEFT, "Bot Left");
150 showArea( textAreaBOTTOMRIGHT,"Bot Right");
151 }
152
153 void textAreaDemox()
154 {
155 showArea( textAreaFULL, "F");
156 showArea( textAreaTOP, "T");
157 showArea( textAreaBOTTOM, "B");
158 showArea( textAreaRIGHT, "R");
159 showArea( textAreaLEFT, "L");
160 showArea( textAreaTOPLEFT, "TL");
161 showArea( textAreaTOPRIGHT, "TR");
162 showArea( textAreaBOTTOMLEFT, "BL");
163 showArea( textAreaBOTTOMRIGHT,"BR");
164 }
165
166 void showArea(predefinedArea area, char *description)
167 {
168 GLCD.ClearScreen();
169 GLCD.DrawBitmap(icon, 0, 0);
170 GLCD.DrawBitmap(icon, 64, 0);
171 textArea.DefineArea(area);
172 textArea.SelectFont(System5x7);
173 textArea.SetFontColor(WHITE);
174 textArea.ClearArea();
175 textArea.println(description);
176 textArea.print("text area");
177 delay(1000);
178 textArea.SetFontColor(WHITE);
179 textArea.ClearArea();
180 showLines(10);
181 delay(1000);
182 textArea.ClearArea();
183 textArea.SetFontColor(BLACK);
184 showLines(10);
185 delay(1000);
186 }
187
188 void showAscii()
189 {
190 for( char ch = 64; ch < 127; ch++)
191 {
192 GLCD.print(ch);
193 delay(theDelay);
194 }
195 }
196
197 void showLines(int lines)
198 {
199 for(int i = 1; i <= lines; i++)
200 {
201 textArea << " Line " << i << endl;
202 delay(theDelay); // короткая пауза между линиями
203 }
204 }
205
206
207 void countdown(int count){
208 while(count--){ // запускаем обратный отсчет
209 countdownArea.ClearArea();
210 countdownArea.print(count);
211 delay(1000);
212 }
213 }
214
215 void scrollingDemo()
216 {
217 GLCD.ClearScreen();
218 textAreaArray[0].DefineArea( textAreaTOPLEFT);
219 textAreaArray[0].SelectFont(System5x7, WHITE);
220 textAreaArray[0].CursorTo(0,0);
221 textAreaArray[1].DefineArea( textAreaTOPRIGHT, SCROLL_DOWN); // инвертируем скроллинг
222 textAreaArray[1].SelectFont(System5x7, BLACK);
223 textAreaArray[1].CursorTo(0,0);
224 textAreaArray[2].DefineArea(textAreaBOTTOM);
225
226 textAreaArray[2].SelectFont(Arial_14, BLACK);
227 textAreaArray[2].CursorTo(0,0);
228
229 for(byte area = 0; area < 3; area++)
230 {
231 for( char c = 64; c < 127; c++)
232 textAreaArray[area].print(c);
233 delay(theDelay);
234 }
235 for(char c = 32; c < 127; c++)
236 {
237 for(byte area = 0; area < 3; area++)
238 textAreaArray[area].print(c);
239 delay(theDelay);
240 }
241
242 for(byte area = 0; area< 3; area++)
243 {
244 textAreaArray[area].ClearArea();
245 }
246 for(int x = 0; x < 15; x++)
247 {
248 for(byte area = 0; area < 3; area++)
249 {
250 textAreaArray[area].print("line ");
251 textAreaArray[area].println(x);
252 delay(50);
253 }
254 }
255 delay(1000);
256 }
257
258 /*
259 * Рисовальная функция, за основу которой взят скетч от TellyMate:
260 * http://www.batsocks.co.uk/downloads/tms_scribble_001.pde
261 */
262 void scribble( const unsigned int duration )
263 {
264 const float tick = 1/128.0;
265 float g_head_pos = 0.0;
266
267 for(unsigned long start = millis(); millis() - start < duration; )
268 {
269 g_head_pos += tick ;
270
271 float head = g_head_pos ;
272 float tail = head - (256 * tick) ;
273
274 // рисуем пиксели в головной части линии...
275 byte x = fn_x( head ) ;
276 byte y = fn_y( head ) ;
277 GLCD.SetDot( x , y , BLACK) ;
278
279 // стираем пиксели в хвостовой части линии...
280 x = fn_x( tail ) ;
281 y = fn_y( tail ) ;
282 GLCD.SetDot( x , y , WHITE) ;
283 }
284 }
285
286 byte fn_x( float tick )
287 {
288 return (byte)(GLCD.Width/2 + (GLCD.Width/2-1) * sin( tick * 1.8 ) * cos( tick * 3.2 )) ;
289 }
290
291 byte fn_y( float tick )
292 {
293 return (byte)(GLCD.Height/2 + (GLCD.Height/2 -1) * cos( tick * 1.2 ) * sin( tick * 3.1 )) ;
294 }
295
296 void FPS(const byte width, const byte height, const unsigned long msecs)
297
298 {
299
300 unsigned long stime = millis();
301
302 while(millis() - stime < msecs)
303
304 FPS(width, height);
305
306 }
307
308
309 void FPS( const byte width, const byte height)
310 {
311
312 const byte CenterX = width/2;
313 const byte CenterY = height/2;
314 const byte Right = width-1;
315 const byte Bottom = height-1;
316
317 iter=0;
318 startMillis = millis();
319 while(iter++ < 10){ // делаем 10 проходов
320 GLCD.DrawRect(0, 0, CenterX, Bottom); // прямоугольник в левой части экрана
321 GLCD.DrawRoundRect(CenterX + 2, 0, CenterX - 3, Bottom, 5); // закругленный прямоугольник вокруг текстовой области
322 for(int i=0; i < Bottom; i += 4)
323 GLCD.DrawLine(1,1, CenterX-1, i); // рисуем линии, идущие из левого верхнего к правому нижнему углу
324 GLCD.DrawCircle(GLCD.CenterX/2, GLCD.CenterY-1, min(GLCD.CenterX/2, GLCD.CenterY)-2); // рисуем круг с центром в левой части экрана
325 GLCD.FillRect( CenterX + CenterX/2-8 , CenterY + CenterY/2 -8,16,16, WHITE); // стираем предыдущую позицию счетчика
326 drawSpinner(loops++, CenterX + CenterX/2, CenterY + CenterY/2); // рисуем новую позицию счетчика
327 GLCD.CursorToXY(CenterX/2, Bottom -15);
328 GLCD.print(iter); // печатаем номер текущего прохода в текущей позиции курсора
329 }
330 // показываем количество проходов в секунду:
331 unsigned long duration = millis() - startMillis;
332 int fps = 10000 / duration;
333 int fps_fract = (10000 % duration) * 10 / (duration/10);
334 GLCD.ClearScreen(); // очищаем экран
335 GLCD.CursorToXY(CenterX + 16, 9);
336 GLCD.print("GLCD ");
337 GLCD.print(GLCD_VERSION, DEC);
338 if(GLCD.Height <= 32)
339 GLCD.CursorToXY(CenterX + 4, 1);
340 else
341 GLCD.CursorToXY(CenterX + 4, 24);
342 GLCD.print("FPS="); // печатаем текстовую строку
343 GLCD.print(fps); // печатаем целочисленное значение
344 GLCD.print(".");
345 if(fps_fract < 10)
346 GLCD.print((int)0); // когда нужно, вручную печатаем ведущий нуль
347 GLCD.print(fps_fract);
348 }
См.также
Внешние ссылки