const int swPins[] { 9, 10, 11, 12 };
const int dataPin = 2;
const int latchPin = 3;
const int clockPin = 4;
// Each bit from left to right addresses respectively segments A, B, C, D, E, F, G and DP
// Segments A to G are digit segments and DP is the dot
// starting with top segment = A, then going round clockwise and ending with the center segment = G
// for instance, 3 has all segments lit except for E, F and the dot, so the byte value is 1 1 1 1 0 0 1 0
// A ^ ^ ^ ^ ^ ^ ^ ^
// ----- A B C D E F G DP
// | |
// F | | B
// | G |
// -----
// | |
// E | | C
// | |
// ----- • DP
// D
const byte hexaValues[] = {
B11111100, // 0
B01100000, // 1
B11011010, // 2
B11110010, // 3
B01100110, // 4
B10110110, // 5
B10111110, // 6
B11100000, // 7
B11111110, // 8
B11110110, // 9
B11101110, // 10 / A
B00111110, // 11 / B
B10011100, // 12 / C
B01111010, // 13 / D
B10011110, // 14 / E
B10001110, // 15 / F
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
for (int i = 0; i < 4; i++) {
pinMode(swPins[i], INPUT);
Serial.print("Pin ");
Serial.print(swPins[i]);
Serial.println(" set to INPUT");
}
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
}
void loop() {
int inputResult = getInputResult();
sevenSegmentWrite(inputResult);
delay(250);
}
int getInputResult() {
int result = 0;
Serial.print("User input : ");
for (int i = 3; i >= 0; i--) {
if (digitalRead(swPins[i]) == HIGH) {
result += exponent(2, i);
Serial.print("1");
} else {
Serial.print("0");
}
}
Serial.print(" | Decimal value : ");
Serial.println(result);
return result;
}
int exponent(int base, int power) {
int result = 1;
for (int i = 0; i < power; i++) {
result *= base;
}
return result;
}
void sevenSegmentWrite(int valueIndex) {
// set the latch pin on low to notify the 74HC595 chip it is receiving data
digitalWrite(latchPin, LOW);
// send the data of the digit at the index corresponding to the user's input (from 0 to 15)
shiftOut(dataPin, clockPin, LSBFIRST, hexaValues[valueIndex]);
// set the latch pin on high to notify the 74HC595 chip that it is no longer receiving data
digitalWrite(latchPin, HIGH);
}