Анатолий беляев (aka mr.alb). персональный сайт

Содержание

More information

Examples

See the library examples for more information on how to use this library. See also the original examples by Ricardo Batista. Most will still work or only require minor changes.

Links

  • Original TM1638/TM1640 library: https://github.com/rjbatista/tm1638-library
  • TM1637 library used for reference: https://github.com/avishorp/TM1637
  • A TM1637 library optimized for speed and size: https://github.com/Erriez/ErriezTM1637
  • TM1650 library that uses the Wire interface: https://github.com/mozgy/Mozz_TM1650
  • MAX7219 LED Matrix library: https://github.com/markruys/arduino-Max72xxPanel
  • OneButton multi-state buttons: https://github.com/mathertel/OneButton
  • Adafruit GFX library: https://github.com/adafruit/Adafruit-GFX-Library

Animation and Animator Tool

The showAnimation() function projects a sequence of frames (patterns) onto the display. This works by defining the animation sequence through a multi-dimensional array of patterns.

// Data from Animator Tool
const uint8_t ANIMATION = {
  { 0x08, 0x00, 0x00, 0x00 },  // Frame 0
  { 0x00, 0x08, 0x00, 0x00 },  // Frame 1
  { 0x00, 0x00, 0x08, 0x00 },  // Frame 2
  { 0x00, 0x00, 0x00, 0x08 },  // Frame 3
  { 0x00, 0x00, 0x00, 0x04 },  // Frame 4
  { 0x00, 0x00, 0x00, 0x02 },  // Frame 5
  { 0x00, 0x00, 0x00, 0x01 },  // Frame 6
  { 0x00, 0x00, 0x01, 0x00 },  // Frame 7
  { 0x00, 0x01, 0x00, 0x00 },  // Frame 8
  { 0x01, 0x00, 0x00, 0x00 },  // Frame 9
  { 0x20, 0x00, 0x00, 0x00 },  // Frame 10
  { 0x10, 0x00, 0x00, 0x00 }   // Frame 11
};

  // Display Animation sequence
  display.showAnimation(ANIMATION, FRAMES(ANIMATION), TIME_MS(50));

код для Digispark:

Библиотеку для работы 7 сегментным индикатором можно взять тут или тут.

В проекте не предусмотрена настройка времени, нужно установить время в DS3231 с компьютера.

#include <TinyWireM.h>
#include "TM1637.h"
  
#define CLK 1
#define DIO 4 

TM1637 tm1637(CLK,DIO);

///// часы ..
byte decToBcd(byte val){
  return ( (val10*16) + (val%10) );
}

byte bcdToDec(byte val){
  return ( (val16*10) + (val%16) );
}

void setDateDs1307(byte second,        // 0-59
                   byte minute,        // 0-59
                   byte hour,          // 1-23
                   byte dayOfWeek,     // 1-7
                   byte dayOfMonth,    // 1-28/29/30/31
                   byte month,         // 1-12
                   byte year)          // 0-99
{
   TinyWireM.beginTransmission(0x68);
   TinyWireM.send();
   TinyWireM.send(decToBcd(second));    
   TinyWireM.send(decToBcd(minute));
   TinyWireM.send(decToBcd(hour));     
   TinyWireM.send(decToBcd(dayOfWeek));
   TinyWireM.send(decToBcd(dayOfMonth));
   TinyWireM.send(decToBcd(month));
   TinyWireM.send(decToBcd(year));
   TinyWireM.endTransmission();
}

void getDateDs1307(byte *second,
          byte *minute,
          byte *hour,
          byte *dayOfWeek,
          byte *dayOfMonth,
          byte *month,
          byte *year)
{

  TinyWireM.beginTransmission(0x68);
  TinyWireM.send();
  TinyWireM.endTransmission();

  TinyWireM.requestFrom(0x68, 7);

  *second     = bcdToDec(TinyWireM.receive() & 0x7f);
  *minute     = bcdToDec(TinyWireM.receive());
  *hour       = bcdToDec(TinyWireM.receive() & 0x3f); 
  *dayOfWeek  = bcdToDec(TinyWireM.receive());
  *dayOfMonth = bcdToDec(TinyWireM.receive());
  *month      = bcdToDec(TinyWireM.receive());
  *year       = bcdToDec(TinyWireM.receive());
}

float get3231Temp(){
  byte tMSB, tLSB; 
  float temp3231;

  TinyWireM.beginTransmission(0x68);
  TinyWireM.send(0x11);
  TinyWireM.endTransmission();
  TinyWireM.requestFrom(0x68, 2);

  if(TinyWireM.available()) {
    tMSB = TinyWireM.receive(); //2's complement int portion
    tLSB = TinyWireM.receive(); //fraction portion

    temp3231 = (tMSB & B01111111); //do 2's math on Tmsb
    temp3231 += ( (tLSB >> 6) * 0.25 ); //only care about bits 7 & 8
  }
  else {
    //oh noes, no data!
  }

  return temp3231;
}
/////////////////

void setup() {
  
  TinyWireM.begin();
  tm1637.init();
  tm1637.set(1); // яркость, от 0 до 7
  
  /*  // установка часов  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;  second = 30;  minute = 0;  hour = 14;  dayOfWeek = 3; // день недели  dayOfMonth = 1; // день  month = 4;  year = 14;  setDateDs1307(second, minute, hour, dayOfWeek, dayOfMonth, month, year); */
}

void loop(){
  
  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; 
  getDateDs1307(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  
  byte temp = get3231Temp(); 
  
  int8_t TimeDisp4; 
  
 
  // вывод температуры .. каждые 10 сек на 2 сек
  if (second >=  && second <= 1 ||
      second >= 10 && second <= 11 ||
      second >= 20 && second <= 21 ||
      second >= 30 && second <= 31 ||
      second >= 40 && second <= 41 ||
      second >= 50 && second <= 51)
  {
    tm1637.point(POINT_OFF); // выключаем точки 
    TimeDisp = 19; //  
    TimeDisp1 = temp  10; // заполняем массив
    TimeDisp2 = temp % 10;
    TimeDisp3 = 12; // C

  }
/*  // дата  else if(second >= 25 && second <= 26 ||          second >= 45 && second <= 46)  {    tm1637.point(POINT_OFF);      TimeDisp = dayOfMonth / 10;    TimeDisp = dayOfMonth % 10;    TimeDisp = month / 10;    TimeDisp = month % 10;    }*/
  /// часы
  else
  {  
    tm1637.point(POINT_ON); // включаем точки
    TimeDisp = hour  10;
    TimeDisp1 = hour % 10;
    TimeDisp2 = minute  10;
    TimeDisp3 = minute % 10;        
  }
  
  tm1637.display(TimeDisp); // отправляем массив на экран
 
  
}

TM16xxMatrixGFX class

#include <Adafruit_GFX.h>
#include <TM1640.h>
#include <TM16xxMatrixGFX.h>

Then you can instantiate the TM16xxMatrixGFX class, refering to the chip specific class:

TM1640 module(13, 14);    // For ESP8266/WeMos D1-mini: DIN=D7/13/MOSI, CLK=D5/14/SCK
#define MATRIX_NUMCOLUMNS 8
#define MATRIX_NUMROWS 8
TM16xxMatrixGFX matrix(&module, MATRIX_NUMCOLUMNS, MATRIX_NUMROWS);    // TM16xx object, columns, rows

Note that the TM1640 has sufficient outputs to drive two 8×8 matrices. The WeMOS D1 Mini Matrix LED Shield also uses the TM1640, but has only one 8×8 matrix.

These methods can be used to draw on the matrix:

  matrix.setIntensity(1);         // Use a value between 0 and 7 for brightness
  matrix.fillScreen(LOW);         // Clear the matrix
  matrix.drawPixel(1, 4, HIGH);   // set one pixel in the memory bitmap on
  matrix.write();                 // Send the memory bitmap to the display
  matrix.drawChar(, , 'A', HIGH, LOW, 1);
  matrix.drawLine(, matrix. height(), matrix.width(), , HIGH);
  matrix.drawRect(, , 6, 6, HIGH);

Multiple identical modules can be combined to form a large matrix. The data line
can be shared to reduce the number of pins:

  TM1640 module(D7, D5);    // For ESP8266/WeMos D1-mini: DIN=D7/13/MOSI, CLK=D5/14/SCK
  TM1640 module2(D7, D6);   // For ESP8266/WeMos D1-mini: shared DIN=D7/13/MOSI, different CLK
  TM16xx * modules[]={&module,&module2};      // put modules in an array
  TM16xxMatrixGFX matrix(modules, MODULE_SIZECOLUMNS, MODULE_SIZEROWS, 2, 1);    // modules, size of each module, size combined

TM16xxMatrix class

The TM16xxMatrix class provides basic methods for using a single LED-matrix module. For more advanced graphics use the class. To use the TM16xxMatrix class on top of the base class, all you need to do is instantiate it, refering to the chip specific class:

TM1640 module(9, 10);    // DIN=9, CLK=10
#define MATRIX_NUMCOLUMNS 16
#define MATRIX_NUMROWS 8
TM16xxMatrix matrix(&module, MATRIX_NUMCOLUMNS, MATRIX_NUMROWS);    // TM16xx object, columns, rows

Note that the TM1640 has sufficient outputs to drive two 8×8 matrices.

These methods can be used to set the pixels of the matrix:

  matrix.setAll(true);    // set all pixels on
  matrix.setPixel(5,6, true);   // set one pixel on
  matrix.setPixel(3,2, false);   // set another pixel off

See TM16xxMatrix.h for the provided methods.

Работа программного обеспечения

Интерфейс DS5000

Программа, приведённая в Приложении, написана для взаимодействия DS5000 с DS1307 с помощью двухпроводного интерфейса. DS5000 запрограммирован с использованием макетной платы DS5000T фирмы Dallas Semiconductor, которая позволяет использовать ПК в качестве терминала ввода/вывода. Программные средства KIT5K поставляемые вместе с макетной платой DS5000T обеспечивают высокоуровневый интерфейс для загрузки программных приложений в DS5000 или установки его параметров через Program command. Программное обеспечение KIT5K содержит эмулятор терминала ввода/вывода, чтобы позволить пользователю запускать программные приложения в микроконтроллер DS5000, который связан с пользователем через COM порт ПК.

Исходный код DS1307

Первый раздел исходного кода, расположенный в Приложении, используется при конфигурации DS5000 для последовательного соединения с ПК. Также в начале кода находится подпрограмма MASTER_CONTROLLER, которая используется для управления демонстрационной программой.

Подпрограммы, которые следуют непосредственно за подпрограммой MASTER_CONTROLLER, являются драйверами низкого уровня и служат для управления двухпроводным интерфейсом. Они не являются индивидуальными для DS1307, а могут быть использованы с любым совместимым с двухпроводным интерфейсом «ведомым» устройством. Вот эти подпрограммы:

SEND_START

Подпрограмма используется для генерации состояния START на двухпроводной шине.

SEND_STOP

Подпрограмма используется для генерации состояния STOP на двухпроводной шине.

SEND_BYTE

Подпрограмма посылает 8-разрядное слово (первым является старший значащий бит (MSB)) по двухпроводной шине и девятый тактовый импульс для импульса подтверждения приёма.

READ_BYTE

Подпрограмма читает 8-разрядное слово с двухпроводной шины. Она проверяет очищен ли флаг LASTREAD после того, как считан последний байт из «ведомого» устройства. Если это был не последний байт, то DS5000 посылает импульс подтверждения по девятому тактовому импульсу, а если это был последний считанный байт из «ведомого» устройства, то DS5000 посылает «неподтверждение».

SCL_HIGH

Подпрограмма осуществляет переход линии SCL из низкого в высокое состояние и обеспечивает высокое состояние линии SCL перед продолжением.

DELAY и DELAY_4

Эти две подпрограммы включены для обеспечения сохранения временной диаграммы двухпроводной шины.

Остальная часть кода, включённая в приложение, специально предназначена для демонстрации функций DS1307. Продемонстрированы следующие функции:

Setting Time

Время считывается с клавиатуры и сохраняется в сверхоперативной памяти DS5000. Затем оно передаётся по двухпроводной шине в DS1307.

Set RAM

Одиночный байт в шестнадцатеричном виде считывается с клавиатуры и записывается в RAM DS1307.

Read Date/Time

Дата и время считываются по двухпроводной шине и сохраняются в сверхоперативной памяти DS5000. Затем они выводятся на экран. Это продолжается до тех пор, пока не будет нажата кнопка на клавиатуре.

OSC On/OSC Off

Тактовый генератор DS1307 может быть включен или выключен.

SQW/OUT On/SQW/OUT Off

Функция SQW/OUT может быть включена или выключена. Она будет переключаться на частоте 1 Гц.

Таблица 1. AC электрические характеристики

Параметр Символ Эффективноезначение Единицы
Тактовая частота SCL fSCL 59 кГц
Время свободного состояния шины между состояниями STOP и START tBUF 5.7 мкс
Время удержания(повторенного) состояния START tHD:STA 6.2 мкс
Период низкого состояния тактового импульса SCL tLOW 10.5 мкс
Период высокого состояния тактового импульса SCL tHIGH 6.5 мкс
Время установки для повторного состояния START tSU:STA 5.3 мкс
Время удержания данных tHD:DAT 5.5 мкс
Время установки данных tSU:DAT 3.1 мкс
Время установки для состояния STOP tSU:STO 5.4 мкс

Заключение

Было показано, как правильно подсоединять напрямую DS1307 или любое двухпроводное «ведомое» устройство к 8051-совместимому микроконтроллеру. Соединение должно быть таким, чтобы временная диаграмма двухпроводного интерфейса на микроконтроллере не нарушалась драйверами низкого уровня. Для этого в программный код должны быть включены подпрограммы задержки. Приведённых в таблице 1 эффективных значений, придерживались при конфигурации аппаратной части, описанной в данном техническом руководстве.

Документация

  Rus Пример программы на языке Асемблер
  100 Kb Engl Исходный фаил
  Rus Описание интерфейса I2C
  Програмное обеспечение микроконтроллеров MCS-51
  200 Kb Engl Описание DS1307 — часы реального времени с IIC интерфейсом

Главная —
Микросхемы —
DOC —
ЖКИ —
Источники питания —
Электромеханика —
Интерфейсы —
Программы —
Применения —
Статьи

Wiring – Connecting TM1637 4-digit 7-segment display to Arduino UNO

Connecting the display to an Arduino or other microcontroller is super easy. You only need to connect 4 wires: 2 for power and 2 to transfer the data.

The wiring diagram below shows you how you can connect the display to the Arduino.


TM1637 4 digit 7 segment display with Arduino UNO wiring diagram.

The connections are also given in the table below:

TM1637 Display Connections

TM1637 4-Digit Display Arduino
VCC 5 V
GND GND
CLK Digital pin 2
DIO Digital pin 3

Note that the order and location of the pins can be different depending on the manufacturer!

For this tutorial, I connected CLK and DIO to pin 2 and 3 respectively, but you can change this to any of the digital pins you want. You just have to change the pin configuration in the code accordingly.

Usage

The library provides a single class named TM1637TinyDisplay with the following functions:

  • — Display an integer and floating point numbers (positive or negative)
  • — Display a number with ability to manually set decimal points or colon
  • — Display a number in hexadecimal format and set decimal point or colon
  • — Display a ASCII string of text with optional scrolling for long strings
  • — Use display LEDs to simulate a level indicator (vertical or horizontal)
  • — Display a sequence of frames to render an animation
  • — Directly set the value of the LED segments in each digit
  • — Sets the brightness of the display
  • — Sets the speed for text scrolling

PROGMEM functions: Large string or animation data can be left in Flash instead of being loaded in to SRAM to save memory.

  • — Display a sequence of frames to render an animation (in PROGMEM)
  • — Display a ASCII string of text with optional scrolling for long strings (in PROGMEM)

Fun class extra methods

  • Creates a display object
  • Print 0-100% (2 steps per digit) vertical level e.g. volume, battery
  • Print 0-100% (1 step per digit) vertical level using custom symbol
  • Prints 4 horizontal levels e.g. equalizer
  • Prints text and (keeps) scrolling
  • Classic snake demo
  • Nightrider Kit demo
  • Count down a (bomb) timer
  • Bouncing ball demo

For more extended information on what arguments all above functions accept and return see the header files of the classes (SevenSegmentTM1637.h, SevenSegmentExtended.h and SevenSegmentFun.h).

Trouble shooting

Some boards might not have enough power on their 5V pin. In that case try to use an external 5V power supply. People reported that the ESP8266 might be one of those boards.

Todo

  • Refactor library to make it more modular and support more chips
    • Add support for all TM16xx chips (most should already work)
    • Add support for MAX7219 displays
    • Add support for TM74HC595 displays

Changelog

  • 09-07-2020 version 1.1.1
    • Bug fixes
  • 04-07-2020 version 1.1.0
    • Improved using pablo-lp

      The default printLevelVertical() can diplay twice the number of levels now (e.g. 9 levels for a defaulf 4 digit display)

      suggestions

    • Add configurable blink delay when using the methods (thanks to simoneluconi)
    • Added a new method to make it easier to print right aligned numbers
    • Bug fixes
      • Merge PR from berendkleinhaneveld to fix some compiler warnings
      • Merge PR from facelessloser Remove some calls
      • Merge PR from RAnders00 Fix incorrect repsonse from
      • Merge PR from per1234 Use correct separator in
  • 04-11-2016 version 1.0.4

22-05-2016 version 1.0.3

add support for all AVR MCU’s (thanks to per1234)

  • 08-05-2016 version 1.0.2
  • 28-09-2015 version 1.0.1
  • 28-09-2015 version 1.0.0

Note

I spend quite a bit of time to build this library. I hope it will be useful to others. I decided to publish it, although there still might be small bugs. If you find one, just let me know and I will try to fix it. If you have any other suggestion, don’t hesitate to contact me.

Sources

I’ve looked at many sources while constructing this library, bassicly all alternative Arduino TM1637 libraries and some AVR TM1637 libraries. While doing so I’ve found some really nice improvements compared to other implementations. For example, most libraries use a really low clock speed (~50us), I’ve tested with clock speeds as low as 1us and the chip still seems to respond well. Furthermore, from the (Chinese) datasheet it seems that you always have to perform three operation when communicating with the IC; set some configuration, set the address and send 1-4 digit data and set the display brightness. I’ve found out that this is not the case, you can do all of those separately if you want.

Still without all these fine examples it would have taken me a lot more time to figure out the inner workings of this IC!

Sources:

New in this library

Added library functionality:

  • Revised library structure to simplify support of other TM16xx chips.
  • Basic functionality in base class for a uniform API.
  • Support for TM1637. Note: TM1637 does not support simultaneous button presses.
    (Method derived from TM1637 library but using pins in standard output mode when writing).
  • Support for TM1668. Note: TM1668 can be used in 10×7 — 13×4 display modes. Datasheet partly translated.
  • Support for TM1650. Note: TM1650 can be used in 8×4 or 7×4 display mode. Datasheet fully translated.
  • Reduced required RAM memory by using PROGMEM fonts.
  • Support for ATtiny44A and ESP8266 in addition to regular Arduinos.
  • Separate classes for LED matrix and advanced LED display support.
  • Simple display of text and numbers on 7-segment displays using familiar print() and println() methods.
  • Support for the Adafruit GFX graphics library for advanced graphics on a LED matrix.
  • Full support for QYF-TM1638 module (8 digit common anode LED display and 4×4 keypad)
  • Support for TM1638 in Anode Mode (10 digit common anode LED 8 segment display)
  • Support for combining multiple modules into one large Adafruit GFX matrix.
  • Support for scanning all possible keys (K1, K2 and K3 lines) on TM1638.
  • Support for release, click, doubleclick and long press button detection using callback functions.
  • Added library examples.
  • Support for TM1620 (thanks @eddwhite)
  • Support for TM1630 (thanks @tokuhira)
  • Support for TM1628. Note: TM1628 can be used in 10×7 — 13×4 display modes.

Functionality in original library by Ricardo Batista:

  • Support for the TM1638 and TM1640, including common anode TM1638 module;
  • Helper methods for displaying numbers in decimal, hexadecimal and binary;
  • Support for multiple chained TM1638 and for TM1638 in inverted position;
  • Support for dimming the display and LEDs and for writing text;
  • Reading simultaneous button presses on TM1638;

TM16xx LEDs and Buttons library

This Arduino library facilitates driving LED displays using TM16xx LED driver chips.
The TM16xx chip family allows driving 7-segment LED displays or LED matrices.
Next to built-in high-frequency LED multiplexing, they offer control of LED brightness.
Most TM16xx chips also support reading key-scan data for button presses.
Using this library you can simply use print() on a 7-segment display or use Adafruit GFX on a LED matrix.
Currently this library supports the TM1620, TM1628, TM1630, TM1637, TM1638, TM1640, TM1650 and TM1668 chips. Note that there are similar chips made by other manufacturers that may be compatible with the Titan Micro chips. For instance: the HBS640 by WINRISE is compatible with the TM1640.

Made by Maxint R&D. See https://github.com/maxint-rd/

Initial version was based on the TM1638 library by Ricardo Batista. Further inspiration from the TM1637 library by Avishay, the Max72xxPanel library by Mark Ruys and the OneButton library by Matthias Hertel.

TM1637 Datasheet PDF

Взаимодействие микроконтроллера с микросхемой ТМ1637 осуществляется посредством двухпроводной шины. Метод связи не идентичен протоколу 12C полностью. Как мне показалось он намного проще. Вообще данная микросхема является драйвером и для работы с 8×2bit клавиатурой. Но эту опцию я еще не рассматривал. Здесь будет рассмотрен только процесс передачи данных на четырехразрядный индикатор. Кстати, весь процесс динамической индикации микросхема берет на себя, что является большущим плюсом. Намного упрощается написание программ с использованием данных индикаторов, не надо следить за массой временных интервалов. Яркость сегментов индикатора регулируется программно и имеет семь уровней, которые выбираются при помощи передачи в чип семи команд. От 0×88…0x8f, в двоичном коде, например, первая команда будет выглядеть так – ‘10001000’. Единица в старшем разряде, bit7 означает включение индикации. Если этот бит установлен в «0», то индикаторы светиться не будут. Т.е. появляется возможность отключать индикатор, например, для экономии энергии в мобильных устройствах. При передаче последней команды – 8fh, ‘10001111’, свечение индикаторов будет иметь самую высокую яркость.

TM16xxDisplay class

The TM16xxDisplay class adds some bytes to the memory footprint, but it provides the familiar easy to use print() and println() functions. Next to that it also provides some more advanced display methods. To use that class on top of the base class, all you need to do is instantiate it, refering to the chip specific class:

TM1638 module(8, 9, 7);   // DIO=8, CLK=9, STB=7
TM16xxDisplay display(&module, 8);    // TM16xx object, 8 digits

Simple print example using the TM16xxDisplay class:

#include <TM1638.h>
#include <TM16xxDisplay.h>

TM1638 module(8, 9, 7);   // DIO=8, CLK=9, STB=7
TM16xxDisplay display(&module, 8);    // TM16xx object, 8 digits

void setup() {
  display.println(F("HELLO !"));
}

int nCount=;
void loop() {
  delay(1000);
  display.print("Count:");
  display.println(nCount++);
}

See TM16xxDisplay.h for the provided methods.

Hardware

  • 6-Digit Display modules — see .

The display has four connectors:

  • CLK — Clock — attach to any GPIO output
  • DIO — Data — attach to any GPIO output
  • VCC — Power 5v
  • GND — Ground

Power Note: Steady clean power is important for circuit stability. If you are seeing display artifacts during high frequency updates or animation sequences, you may be experiencing power fluctuations that are impacting signal timing and communication with the TM1637. This is especially true with standalone microprocessor applications that lack any power conditioning (e.g. ATtiny85). A polarized 100uF electrolytic capacitor inserted across VCC and GND can help smooth out the spikes.

Decimals and Colons: Some TM1637 displays come equipped with a middle colon LED (as shown above) as used in digital clocks but with no decimal points. Some displays come with decimal point LEDS for each digit. Some come with both but often the decimal point LEDs are not connected. These extra LEDs are activated by setting the upper bit (0x80) for the digit next to the dot. This library will handle setting that for you via the showNumber() function when you specify floating point numbers or via the showNumberDec() function where you can set the decimal point manually.

Examples

Copy the file to your device, using ampy, webrepl or compiling and deploying. eg.

Basic usage

import tm1637
from machine import Pin
tm = tm1637.TM1637(clk=Pin(5), dio=Pin(4))

# all LEDS on "88:88"
tm.write()

# all LEDS off
tm.write()

# show "0123"
tm.write()

# show "COOL"
tm.write()

# show "HELP"
tm.show('help')

# display "dEAd", "bEEF"
tm.hex(0xdead)
tm.hex(0xbeef)

# show "12:59"
tm.numbers(12, 59)

# show "-123"
tm.number(-123)

# show temperature '24*C'
tm.temperature(24)

For more detailed examples, see tm1637_test.py

Seven Segment Font

They are called 7-segment displays as there are 7 LEDs for each digit (segment).
One byte (7 lower bits) for each segment. The 8th bit (MSB) is for the colon and only on the 2nd segment.

Display Bin Hex Dec
0b00111111 0x3F 63
1 0b00000110 0x06 6
2 0b01011011 0x5B 91
3 0b01001111 0x4F 79
4 0b01100110 0x66 102
5 0b01101101 0x6D 109
6 0b01111101 0x7D 125
7 0b00000111 0x07 7
8 0b01111111 0x7F 127
9 0b01101111 0x6F 111
A 0b01110111 0x77 119
b 0b01111100 0x7C 124
C 0b00111001 0x39 57
d 0b01011110 0x5E 94
E 0b01111001 0x79 121
F 0b01110001 0x71 113
G 0b00111101 0x3D 61
H 0b01110110 0x76 118
I 0b00000110 0x06 6
J 0b00011110 0x1E 30
K 0b01110110 0x76 118
L 0b00111000 0x38 56
M 0b01010101 0x55 85
n 0b01010100 0x54 84
O 0b00111111 0x3F 63
P 0b01110011 0x73 115
q 0b01100111 0x67 103
r 0b01010000 0x50 80
S 0b01101101 0x6D 109
t 0b01111000 0x78 120
U 0b00111110 0x3E 62
v 0b00011100 0x1C 28
W 0b00101010 0x2A 42
X 0b01110110 0x76 118
y 0b01101110 0x6E 110
Z 0b01011011 0x5B 91
blank 0b00000000 0x00
0b01000000 0x40 64
* 0b01100011 0x63 99

Methods

Get or set brightness.

brightness(val=None)

Write one or more segments at a given offset.

write(segments, pos=)

Convert a single hex digit (0x00-0x0f) to a segment.

encode_digit(digit)

Convert a string to a list of segments.

encode_string(string)

Convert a single character to a segment.

encode_char(char)

Display a number in hexadecimal format 0000 through FFFF.

hex(val)

Display a number -999 through 9999, right aligned.

number(num)

Display 2 independent numbers on either side of the (optional) colon, with leading zeros.

numbers(num1, num2, colon=True)

Display a temperature -9 through 99 followed by degrees C.

temperature(num)

Show a string on the display.
Shorthand for write(encode_string()).
Limited to first 4 characters.

show(string, colon=False)

Display a string on the display, scrolling from the right to left, speed adjustable.
String starts off-screen and scrolls until off-screen at 4 FPS by default.

scroll(string, delay=250)

Conclusion

In this article I have shown you how you can use a TM1637 4-digit 7-segment display with Arduino. We also looked at a clock and thermometer example. I hope you found it useful and informative. If you did, please share it with a friend who also likes electronics and making things!

I really like to use these displays to show sensor readings or things like the speed of a motor. With the TM1637Display library, programming the displays becomes very easy, so there is no reason you shouldn’t incorporate one in your next project.

I would love to know what projects you plan on building (or have already built) with this display. If you have any questions, suggestions, or if you think that things are missing in this tutorial, please leave a comment down below.

Note that comments are held for moderation to prevent spam.

Beginner

Подключение DS1307 к дисплею LCD 1602 i2c


Схема подключения часов реального времени с дисплеем

Рассмотрим два варианта подключения модуля RTC к Arduino и текстового дисплея 1602. В первом варианте используется протокол SPI для модуля часов, поэтому к предыдущей схеме потребуется добавить только дисплей с iic модулем. А в скетче следует расскомментировать соответствующую строку. После внесения правок в схему и программу — загрузите следующий скетч в микроконтроллер.

Скетч. Часы с экраном LCD 1602 и DS1302

#include <iarduino_RTC.h>
iarduino_RTC time(RTC_DS1302,6,8,7);  // для модуля DS1302 - RST, CLK, DAT

#include <Wire.h>                             // библиотека для устройств I2C 
#include <LiquidCrystal_I2C.h>       // подключаем библиотеку для дисплея
LiquidCrystal_I2C LCD(0x27,16,2);  // присваиваем имя дисплею

void setup() {
   delay(300);
   LCD.init();            // инициализация LCD дисплея
   LCD.backlight();  // включение подсветки дисплея
   time.begin();
   time.settime(0, 30, 18, 12, 6, 20, 5); // 0  сек, 30 мин, 18 часов, 12, июня, 2020, четверг
}

void loop() {
   // если прошла 1 секунда выводим время на дисплей
   if (millis() % 1000 == 0) {
      LCD.setCursor(0,0);
      LCD.print(time.gettime("d M Y, D"));
      LCD.setCursor(4,1);
      LCD.print(time.gettime("H:i:s"));
      delay(1);
   }
}
  1. в данном примере с помощью команды можно выводить на текстовый экран текущее время и дату в разном формате.

При подключении экрана и модуля RTC к одной шине iic — порты SDA(A4) и SCL(A5), следует указать в скетче какой модуль используется. Схема подключения размещена выше, кроме того вы можете использовать сканер шины i2c для того, чтобы увидеть адреса устройств. Если адреса, которые установлены производителем по умолчанию вы не изменяли — соберите схему и загрузите следующий пример в плату.


Схема подключения DS1307 и LCD по i2c

Скетч. Часы с LCD 1602 и DS1302 I2C Arduino

#include <iarduino_RTC.h>
iarduino_RTC time(RTC_DS1307);       // для модуля DS1307 с i2C

#include <Wire.h>                             // библиотека для устройств I2C 
#include <LiquidCrystal_I2C.h>       // подключаем библиотеку для дисплея
LiquidCrystal_I2C LCD(0x27,16,2);  // присваиваем имя дисплею

void setup() {
   delay(300);
   LCD.init();            // инициализация LCD дисплея
   LCD.backlight();  // включение подсветки дисплея
   time.begin();
   time.settime(0, 30, 18, 12, 6, 20, 5); // 0  сек, 30 мин, 18 часов, 12, июня, 2020, четверг
}

void loop() {
   // если прошла 1 секунда выводим время на дисплей
   if (millis() % 1000 == 0) {
      LCD.setCursor(0,0);
      LCD.print(time.gettime("d M Y, D"));
      LCD.setCursor(4,1);
      LCD.print(time.gettime("H:i:s"));
      delay(1);
   }
}

TM1637 6-Digit Display — TM1637TinyDisplay6

This library now supports the 6-digit display as well as the 4-digit display. The 6-digit display requires additional handling. Specifically, the display digits are not sequential (requires a map) and the 7-segment LED data must be uploaded in reverse order.

TM1637TinyDisplay6 handles this for you but you must initialize the display using the TM1637TinyDisplay6 class:

// Includes
#include <Arduino.h>
#include <TM1637TinyDisplay6.h>       // Include 6-Digit Display Class Header

// Define Digital Pins
#define CLK 1
#define DIO 2

TM1637TinyDisplay6 display(CLK, DIO); // 6-Digit Display Class

void setup()
{
  display.setBrightness(BRIGHT_HIGH);
  display.clear();
  display.showString("digits");
  delay(1000);
  display.showNumber(123456);
  delay(1000);
  display.showNumber(123.456);
  delay(1000);
}