These devices work best when you send them 4 bytes of data. If you send say, 3 bytes, the controller will remember where you left off, and the next character will go into the 4th position instead of the 1st as you’d likely intended.
So what I’ve seen done and what’s worked in my code is this. (It’s from a clock, so yyyy is the name of one of my 7-seg’s for showing the year. p.year is the real time clock’s variable for the year.
// includes
#include <NewSoftSerial.h>
// global variables
NewSoftSerial yyyy(-1,4);
//setup
yyyy.begin (9600); //Set baud rate (default 9600)
yyyy.print("v"); //This clears the display
//loop
char time1[4]; //Make a 4 byte variable
sprintf(time1, "%02d", p.year); // %02d will add a leading 0 if necessary.
yyyy.print(time1);
Now if you want, you can dim these displays too.
void backlight(){
// Read from the analog pin our resistor's value, and map it into numbers we can pass to the 7-seg. Numbers are reversed as 0 is brightest on the display. Technically the 200 can be 250 I think, but that's very dim.
int brightness = map(analogRead(6),0,1023,200,0);
if (old_brightness != brightness){ // Only change the brightness if it's changed
yyyy.print("z"); //Tells 7-seg serial to expect the brightness command next
yyyy.print(brightness, BYTE);
monthday.print("z");
monthday.print(brightness, BYTE);
hourmin.print("z");
hourmin.print(brightness, BYTE);
sec.print("z");
sec.print(brightness, BYTE);
old_brightness = brightness; // Set the old value to the new value so we can compare it on the next loop.
}
}
There are a couple of different options for displaying numbers that aren’t 4 digits. You can either pad with leading zeros (as I’ve done), or you can send “off” commands to the unused digits. Here’s the format to shut off the 3rd and 4th digits. If you do, make your variable only 2 bytes instead, and pass these after the .print command.
char time4[2];
sprintf(time4, "%02d", p.second);
sec.print(time4);
sec.print(125,BYTE); //Blank the last 2 digits if hundredths are not wanted
sec.print(126,BYTE);