Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Arduino 7-segment display shift register countdown with button
#define BTN 7
#define IN 9
#define CP 10
#define RS 11
#define MAX_SECS 10000
// q7, q6, q5, q4, q3, q2, q1, q0
// Layout bitmasks for the screen. This is highly dependent on the pinout of the 7-segment display
// and how it's connected and will probably not work without modifications.
const byte NUMS[10] = {0x7e, 0x48, 0x3d, 0x6d, 0x4b, 0x67, 0x77, 0x4c, 0x7f, 0x6f};
unsigned long timeStart;
unsigned long timeSinceStart;
// Simple button edge detection
bool buttonStateOld = false;
bool buttonStateCurrent = false;
bool isCounting = false;
void displayNumber(int number) {
// Only one digit display, lol. Just display the least significant digit
int numberIndex = number % 10;
// Bitmask for looping through. Starting with MSB with bitmask 0x80 = 10000000
byte pos = 0x80;
for(int i = 0; i < 8; i++) {
digitalWrite(CP, LOW);
digitalWrite(IN, NUMS[numberIndex] & pos ? LOW : HIGH);
digitalWrite(CP, HIGH);
pos = pos >> 1;
}
}
bool getButtonState()
{
return !digitalRead(BTN);
}
void setup() {
pinMode(BTN, INPUT);
digitalWrite(BTN, HIGH);
pinMode(IN, OUTPUT);
pinMode(CP, OUTPUT);
pinMode(RS, OUTPUT);
digitalWrite(RS, HIGH);
timeStart = millis();
timeSinceStart = timeStart;
}
void loop() {
buttonStateOld = buttonStateCurrent;
buttonStateCurrent = getButtonState();
if(!buttonStateOld && buttonStateCurrent) {
isCounting = true;
timeStart = millis();
timeSinceStart = 0;
}
if(buttonStateOld && !buttonStateCurrent) {
isCounting = false;
timeSinceStart = 0;
}
if(isCounting) {
timeSinceStart = millis() - timeStart;
if(timeSinceStart >= MAX_SECS) {
isCounting = false;
timeSinceStart = 0;
}
}
displayNumber((MAX_SECS - timeSinceStart)/1000);
delay(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment