// TM1637 high speed comms demo
// https://wokwi.com/projects/451693102662251521
// https://forum.arduino.cc/t/help-with-tm1637-6-digit-and-button/1416196
// D9 = PB1 = CLOCK = 0x02
// D10 = PB2 = DATA = 0x04
#define liftCLOCK() (PORTB |= 0x02)
#define lowerCLOCK() (PORTB &= ~0x02)
#define liftDATA() (PORTB |= 0x04)
#define lowerDATA() (PORTB &= ~0x04)
#define readDATA() (PINB & 0x04)
#define DATA_OUTPUT() (DDRB |= 0x04)
#define DATA_INPUT() (DDRB &= ~0x04)
static const unsigned char digits[] = {
0b00111111, 0b00000110, 0b01011011, 0b01001111,
0b01100110, 0b01101101, 0b01111101, 0b00000111,
0b01111111, 0b01101111
};
void tm1637Start()
{
liftDATA();
liftCLOCK();
lowerDATA();
lowerCLOCK();
}
void tm1637Stop()
{
lowerDATA();
liftCLOCK();
liftDATA();
}
void tm1637WriteByte(unsigned char b)
{
DATA_OUTPUT();
for (unsigned char i = 0; i < 8; i++) {
lowerCLOCK();
(b & 0x01) ? liftDATA() : lowerDATA();
b >>= 1;
liftCLOCK();
}
// ACK
lowerCLOCK();
DATA_INPUT(); // release DATA
liftCLOCK();
lowerCLOCK();
DATA_OUTPUT();
}
void tm1637Command(unsigned char cmd)
{
tm1637Start();
tm1637WriteByte(cmd);
tm1637Stop();
}
void tm1637Display(unsigned char d0, unsigned char d1, unsigned char d2, unsigned char d3)
{
tm1637Command(0x40); // auto increment
tm1637Start();
tm1637WriteByte(0xC0);
tm1637WriteByte(d0);
tm1637WriteByte(d1);
tm1637WriteByte(d2);
tm1637WriteByte(d3);
tm1637Stop();
tm1637Command(0x8F); // display on, brightness max
}
void setup()
{
Serial.begin(115200);
Serial.println("TM1637 direct-port test\n\n");
DDRB |= 0x02; // CLOCK
DDRB |= 0x04; // DATA
}
void loop()
{
static unsigned char digit = 0;
unsigned long start = micros();
tm1637Display(
digits[digit],
digits[(digit + 1) % 10],
digits[(digit + 2) % 10],
digits[(digit + 3) % 10]
);
unsigned long elaspsedTime = micros() - start;
Serial.println(elaspsedTime);
digit = (digit + 1) % 10;
delay(333);
}