const int b0Pin = 2;
const int b1Pin = 3;
const int b2Pin = 4;
const int b3Pin = 5;
const int dataPin = 6;
const int latchPin = 7;
const int clockPin = 8;
// 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:
pinMode(b0Pin, INPUT);
pinMode(b1Pin, INPUT);
pinMode(b2Pin, INPUT);
pinMode(b3Pin, INPUT);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int inputResult = getInputResult();
sevenSegmentWrite(inputResult);
delay(250);
}
int getInputResult() {
int result = 0;
Serial.print("User input : ");
if (digitalRead(b3Pin) == HIGH) {
result += exponent(2, 3);
Serial.print("1");
} else {
Serial.print("0");
}
if (digitalRead(b2Pin) == HIGH) {
result += exponent(2, 2);
Serial.print("1");
} else {
Serial.print("0");
}
if (digitalRead(b1Pin) == HIGH) {
result += exponent(2, 1);
Serial.print("1");
} else {
Serial.print("0");
}
if (digitalRead(b0Pin) == HIGH) {
result += exponent(2, 0);
Serial.print("1");
} else {
Serial.print("0");
}
Serial.println();
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);
}