Skip to content

Instantly share code, notes, and snippets.

@HadrienMP
Last active October 13, 2018 18:45
Show Gist options
  • Save HadrienMP/0768fdf84aa10b5925013628c22d6ea0 to your computer and use it in GitHub Desktop.
Save HadrienMP/0768fdf84aa10b5925013628c22d6ea0 to your computer and use it in GitHub Desktop.
An arduino sketch to count up to 99 with two common cathode 7 segments displays and 2 cd4511 digit decoders
#include <Arduino.h>
class PinWriter {
public:
void writeToPins(const uint8_t *values, uint8_t *pins, int size) {
for (int i = 0; i < size; ++i) {
writeToPin(pins[i], values[i]);
}
}
protected:
virtual void writeToPin(uint8_t pin, uint8_t on) = 0;
};
class NormalWriter : public PinWriter {
private:
void writeToPin(uint8_t pin, uint8_t on) {
digitalWrite(pin, on);
}
};
class DigitDisplay {
public:
virtual void number(int number) = 0;
protected:
uint8_t size = 0;
PinWriter *pinWriter;
virtual uint8_t* getPins() = 0;
void setOutputPins(const uint8_t *source) {
uint8_t *pins = getPins();
for (int i = 0; i < size; ++i) {
pins[i] = source[i];
pinMode(pins[i], OUTPUT);
}
}
void lightSegments(const uint8_t *segments) {
uint8_t *pins = getPins();
pinWriter->writeToPins(segments, pins, size);
}
};
class CD4511 : DigitDisplay {
private:
const uint8_t NUMBERS[10][4] = {
// A B C D
{0, 0, 0, 0},
{1, 0, 0, 0},
{0, 1, 0, 0},
{1, 1, 0, 0},
{0, 0, 1, 0},
{1, 0, 1, 0},
{0, 1, 1, 0},
{1, 1, 1, 0},
{0, 0, 0, 1},
{1, 0, 0, 1},
};
uint8_t pins[4];
public:
CD4511(uint8_t p_pins[4]) {
size = 4;
pinWriter = new NormalWriter;
setOutputPins(p_pins);
}
uint8_t* getPins() {return pins;};
void number(int number) {
lightSegments(NUMBERS[number]);
}
};
DigitDisplay *firstDigit = NULL;
DigitDisplay *secondDigit = NULL;
void setup() {
uint8_t pins1[4] = {0,1,2,3};
firstDigit = (DigitDisplay *) new CD4511(pins1);
uint8_t pins2[4] = {4,5,6,7};
secondDigit = (DigitDisplay *) new CD4511(pins2);
}
void loop() {
for (int i = 0; i <= 99; ++i) {
firstDigit->number(i / 10);
secondDigit->number(i % 10);
delay(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment