Last active
October 25, 2020 21:56
-
-
Save Cactus64k/843864f5374f1e06a985874ebb5c72a4 to your computer and use it in GitHub Desktop.
TM1637 display driver code for micropython with I2C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from micropython import const | |
class TM1637: | |
def __init__(self, i2c, brightness=7, power=True): | |
self.i2c = i2c | |
self.power = power | |
self.brightness = brightness | |
self.DIGITS = [0xFC, 0x60, 0xDA, 0xF2, 0x66, 0xB6, 0xBE, 0xE0, 0xFE, 0xF6, 0x00] | |
self.TM1637_DATA_CMD = const(0x02) # 0x40 data command | |
self.TM1637_ADDR_CMD = const(0x03) # 0xC0 address command | |
self.TM1637_CTRL_CMD = const(0x01) # 0x80 display control command | |
self.TM1637_BRIGHTNESS = [0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0] | |
self.TM1637_DSP_ON = const(0x10) | |
self.TM1637_COLON = const(0x01) | |
def _data_cmd(self): | |
self.i2c.start() | |
self.i2c.write(bytearray([self.TM1637_DATA_CMD])) | |
self.i2c.stop() | |
def _display_ctl(self): | |
br = self.TM1637_BRIGHTNESS[self.brightness] | |
status = self.TM1637_DSP_ON if self.power is True else 0x00 | |
self._data_cmd() | |
self.i2c.start() | |
self.i2c.write(bytearray([self.TM1637_CTRL_CMD | status | br])) | |
self.i2c.stop() | |
def set_numbers(self, num1, num2, colon=True): | |
c = self.TM1637_COLON if colon is True else 0x00 | |
self._data_cmd() | |
self.i2c.start() | |
self.i2c.write(bytearray([self.TM1637_ADDR_CMD])) | |
self.i2c.write(bytearray([self.DIGITS[num1 // 10]])) | |
self.i2c.write(bytearray([self.DIGITS[num1 % 10] | c])) | |
self.i2c.write(bytearray([self.DIGITS[num2 // 10]])) | |
self.i2c.write(bytearray([self.DIGITS[num2 % 10]])) | |
self.i2c.stop() | |
self._display_ctl() | |
def set_brightness(self, br): | |
self.brightness = max(min(br, 7), 0) | |
self._display_ctl() | |
def set_power(self, status): | |
self.power = status | |
self._display_ctl() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment