Обзор дисплея LED AND KEY на чипе TM1638 — Часы на дисплее LED AND KEY
Обзор дисплея LED AND KEY на чипе TM1638 — Часы на дисплее LED AND KEY.
Часы на дисплее LED AND KEY на чипе TM1638
Ссылки на компоненты:
Дисплей LED AND KEY на чипе TM1638 — http://ali.pub/1sfhl3
Часы реального времени Ds3231 — http://ali.pub/1e3pfr
Датчик атмосферного давления GY-68 BMP180 (аналог BMP085) — http://ali.pub/1sfhyi
Часы на TM1638 LED&KEY
Оставьте комментарий:
Навигация по сайту:
Юный Технарь:
Помощь проекту:
Деньги можно перечислить на карту Сбербанка России:
4276 5400 2194 5088
Поиск
Последние статьи
Идея — датчик уровня жидкости на тензода…
Идея — датчик уровня жидкости на тензодатчике своими руками.
Фреймворк JeeUI2 в программе FLProg — Ко…
Фреймворк JeeUI2 в программе FLProg — Контролер для полива своими руками.
Мой канал на YouTube
Подпишитесь!
2015, Arduinoprom.ru — блог Чилингаряна Грачика. Все авторские права на тексты принадлежат ему.
При размещении текстов и видеоматериалов на сторонних ресурсах активная гиперссылка ОБЯЗАТЕЛЬНА.
Все логотипы и товарные знаки, размещенные на сайте, принадлежат только их законным владельцам (правообладателям).
tronixstuff.com
fun and learning with electronics since 2010
Arduino and TM1638 LED Display Modules
If you need a fast and easy way to add some user input and output to a project, these display modules are interesting and fun.
They contain eight 7-segment red LED digits, eight red/green LEDs and also eight buttons for user input. The units can also be daisy-chained, allowing up to five at once, and a short cable is included with each module, as well as some short spacers and bolts, such as:
The spacers are just long enough to raise the PCB above a surface, however to mount the boards anywhere useful you would need longer ones. You may also want to remove the IDC sockets if you want to mount the module close to the surface of a panel. This would be a simple desoldering task as they are through-hole sockets:
The board is controlled by a TM1638 IC:
This is an LED and interface driver IC from “Titan Micro Electronics“. You can also buy these ICs from PMD Way. You can also download the datasheet for more details.
Getting Started
Now to make things happen…
Hardware – Connection to an Arduino-compatible board (or other MCU) is quite simple. The pinouts are shown on the rear of the PCB, and match the fitting on the ribbon cable. If you look at the end of the cable as such:
The top-right hole is pin one, with the top-left being pin two, the bottom-right pin nine and bottom-left pin ten. Therefore the pinouts are:
For Arduino use, pins 1
4 are the minimum necessary to use one module. Each additional module will require another digital pin connected to STB2, STB3, etc. More on this later. Please note that each module set to full brightness with every LED on consumes 127mA, so it would be wise to use external power with more than one module and other connections with Arduino boards.
Software – download and install the T1638 library from here. Thanks and kudos to rjbatista at gmail dot com for the library. Initialising modules in the sketch is simple. Include the library with:
then use one of the following for each module:
x is the Arduino digital pin connected to the module cable pin 4, y is the Arduino digital pin connected to the module cable pin 3, and z is the strobe pin. So if you had one module with data, clock and strobe connected to pins 8, 7, and 6 you would use:
If you had two modules, with module one’s strobe connected to Arduino digital 6, and module two’s strobe connected to digital 5, you would use:
and so on for more modules. Now to control the display…
The bi-colour LEDs
Controlling the red/green LEDs is easy. For reference they are numbered zero to seven from left to right. To turn on or off a single LED, use the following:
Using the method above may be simple it is somewhat inefficient. A better way is to address all of the LEDs in one statement. To do this we send two bytes of data in hexadecimal to the display. The MSB (most significant byte) consists of eight bits, each representing one green LED being on (1) or off (0). The LSB (least significant byte) represents the red LEDs.
An easy way to determine the hexadecimal value to control the LEDs is simple, image you have one row of LEDs – the first eight being green and the second eight being red. Set each digit to 1 for on and 0 for off. The convert the two binary numbers to hexadecimal and use this function:
Where green is the hexadecimal number for the green LEDs and red is the hexadecimal number for the red LEDs. For example, to turn on the first three LEDs as red, and the last three as green, the binary representation will be:
00000111 11100000 which in hexadecimal is E007. So we would use:
which produces the following:
The 7-segment display
To clear the numeric display (but not the LEDs below), simply use:
or to turn on every segment AND all the LEDs, use the following
To display decimal numbers, use the function:
where a is the integer, b is the position for the decimal point (0 for none, 1 for digit 8, 2, for digit 7, 4 for digit 6, 8 for digit 4, etc), and the last parameter (true/false) turns on or off leading zeros. The following sketch demonstrates the use of this function:
and the results:
One of the most interesting features is the ability to scroll text across one or more displays. To do so doesn’t really need an explanation as the included demonstration sketch:
included with the TM1638 library is easily followed. Just insert your text in the const char string[], ensure that the module(s) are wired according to the module definition at the start of the sketch and you’re set. To see the available characters, visit the function page. Note that the display is only seven-segments, so some characters may not look perfect, but in context will give you a good idea – for example:
Finally, you can also individually address each segment of each digit. Consider the contents of this array:
each element represents digits 1
8. The value of each element determines which segment of the digit turns on. For segments a
f, dp the values are 1,2,4,6,16,32,64,128. So the results of using the array above in the following function:
Naturally you can combine values for each digit to create your own characters, symbols, etcetera. For example, using the following values:
The buttons
The values of the buttons are returned as a byte value from the function:
As there are eight buttons, each one represents one bit of a binary number that is returned as a byte. The button on the left returns decimal one, and the right returns 128. It can also return simultaneous presses, so pressing buttons one and eight returns 129. Consider the following sketch, which returns the values of the button presses in decimal form, then displays the value:
and the results:
A reader from Brazil has used one of the modules as part of a racing simulator – read more about it here, and view his demonstration below.
These display boards are useful and hopefully find a home in your projects.
Особенности адресации контроллера TM1638 для индикаторов с ОА.
В конце поста приложена более крупная схема из инета.
«JY-LKM1638», имеет 2х4 семисегментных индикатора 0,56″ с ОК (5461AS, 14.20mm), 8 двухцветных светодиодов, 8 кнопок, габариты 102x50x10;
В конце поста приложена более крупная схема из инета.
Основное отличие от «LED&KEY» — более крупные индикаторы и двухцветные светодиоды. Также он сделан как проходной модуль, для облегчения соединения до 6 модулей в цепочку.
«QYF-TM1638», имеет 2х4 семисегментных индикатора 0,36″ с ОА (3461BS, 9.14mm), 16 кнопок, отдельные светодиоды отсутствуют, габариты 68х69х9;
Схемы не нашел, основное отличие от «LED&KEY» — применение индикаторов с ОА. Я думал, что практически это означает, что выводимые знаки на нем будет необходимо инвертировать. Все оказалось гораздо хуже…
Подключение индикаторов
Начал разбираться, как к одному чипу можно подключить индикаторы с разной полярностью.
Выходы для управления индикаторами в даташите описаны так:
Схемы подключения индикаторов с ОК и ОА также присутствуют:
Судя по схемам подключения чип может обслуживать не более 8 индикаторов с ОК, и до десяти индикаторов с ОА.
То же самое написано в даташите:
Чип имеет 16 регистров для хранения кодов отображаемых символов. Причем в 8 четных хранятся полноценные байты для отображения символов, в нечетных для отображения используются только два младших бита.
Это применимо только к индикаторам с ОК, управление индикаторами с ОА может кому то напомнить удаление аденоидов через задний проход. Подробнее:
Адресная табличка для управления индикаторами с ОК:
Здесь SEG1-SEG8 обозначают сегменты индикатора, GRID1-GRID8 разряды.
Вполне нормальная адресация, правда байты идут через один, что ставит под сомнение режим автоинкремента байтов чипом.
Адресная табличка для управления индикаторами с ОА:
Здесь GRID1-GRID8 обозначают сегменты индикатора, SEG1-SEG10 разряды.
Сначала я составил ее в уме, не поверил, перерисовал на твердой копии, перепроверил, офигел…
Даже на контроллере, имеющем битовый процессор вывод одного. знакоместа займет не менее 16/24 ассемблерных команд ((установка адреса + битовая операция) * 8 (кол-во бит в байте)).
Если говорить о контроллере его не имеющем (AVR, Arduino), то битовая операция превратится в чтение-модификацию-запись, т.е. не менее 32+ ассемблерных команд.
Для чего я вообще занялся адресацией индикатора с ОА, ведь у меня на модуле индикаторы с ОК?
Для одного проекта у меня применен 10-разрядный семисегментный индикатор. Сейчас в нем прописаны ЖКИ на 2xML1001 или на HD44780. Но ЖКИ при всем удобстве не сравнить с крупным LCD индикатором.
Переделать модуль «LED&KEY» в 10-разрядный теоретически несложно. Тем более я хотел заменить индикаторы 0,36″ на 0,56″. Имеющиеся индикаторы заменить на 5641 (ОК, есть), добавить пару одиночных или двухразрядную сборку ОА (найду).
Практически это будет очень похоже на схему «JY-LKM1638», если двухцветные светодиоды заменить на двухразрядную сборку ОА. Конечно применять в одном дисплее индикаторы с ОК и ОА немного странно, но дома пошла бы.
После просмотра картинки адресации индикаторов с ОА контроллером TM1638, у меня такая крамольная мысль пропала.
P.S. Краткая выжимка из комментариев.
Я сразу, как поглядел на адресацию индикаторов с ОА, понял что это гиблое дело, даже проверочный код не стал писАть. Некоторым это показалось неочевидно. Развязался флейм, для проверки своего предположения я попросил VGA предоставить проверочный код. Код на ассемблере MCS-51 был предоставлен. Приведу результаты тестирования, вырезка, орфография сохранена:
Из за чего все это начиналось — накладные расходы на дебильную адресацию чипом TM1638 индикаторов с ОА. Теперь можно посчитать код от VGA:
Брекпойнты стоят в начале и конце функции преобразования. К ним привязана простейшая функция
Она просто выводит в окно отладчика кол-во выполненных команд на момент вызова.
Итого, 1169 — 31 = 1138 команд потрачено на дебильную адресацию…
Меня тут-же поправили, что речь идет не о командах, а о тактах. Для классических MCS-51 это не совсем так, команда у них выполняется за 1 и более циклов, каждый из них состоит из 12 тактов (периодов тактовой частоты). В новых MCS-51 эти понятия равнозначны. Удачи, читайте комментарии.