For my next book I wanted an example program that had the need for lots of 7-segment display digits, buttons, and LEDs. I found what I wanted, at a low cost, in one of these:
This has 8 7-segment (plus decimal point) digits, 8 LEDs, and 8 push buttons, and used a three-wire SPI interface. Here’s the link to what I bought: https://www.amazon.com/gp/product/B01D140BT6
If you have any familiarity with SPI you are probably wondering how it is a three-wire and not a four-wire interface. It saves a wire by having data travel bidirectionally, basically combining MOSI with MISO. The DIO data signal is normally driven by the master (the Arduino in this case), but when the TM1638 receives the command to read the switches the master stops driving DIO and the TM1638 starts, and continues to do so until the end of the transfer (SS, here called STB goes high). The TM1638 data sheet shows the signals:
Most SPI devices use “Mode 0” or CPOL=0, CPHA=0. This device uses an inverted clock (CPOL=1), and bidirectional operation requires CPHA=1 so the pin is driven on the leading edge of the clock and capture occurs on the trailing edge.
All the libraries I could find for this part use “bit banging” and not the built-in SPI interface. This has negative repercussions for what I will be trying to achieve. Functions that wrote to (and updated) just the 7-segment display took about 3½ ms to execute, during which time they blocked, so no other processing was possible. My code, using the SPI interface and interrupts takes 250µs to update the 7-segment display and the LEDs. But it happens in the background. The function that starts the display update takes half a microsecond to execute, or is 6,000 times faster.
Connection of the LED&KEY to the Arduino is straightforward:
I used digital pin 2 for the SS (STB) function, because SS is not always available (it isn’t on the Leonardo board). The test program runs on the Uno, Nano, Mega, Leonardo, Micro, Nano Every, and Pro Micro, and probably more. It should work fine on any AVR microcontroller Arduino board that presents the SPI interface. It also uses the Pins.h library mentioned (and downloadable) in my previous post.
My next post will present the source code, which will be downloadable.