#include <VariableTimedAction.h>
const uint8_t SEGMENT_PINS[] = { 13, 12, 11, 10, 9, 8, 7 };
const uint8_t PS_PINS[] = { A2, A3, A4, A5, 0, 1, 2, 3, 4, 5, 6 };
const uint8_t SEGMENTS_COUNT = sizeof(SEGMENT_PINS);
const uint8_t DISPLAYS_COUNT = sizeof(PS_PINS);
/* Digit table for the 7-segment display */
const bool digitTable[][7] = {
{ 1, 1, 1, 1, 1, 1, 0 }, // 0
{ 0, 1, 1, 0, 0, 0, 0 }, // 1
{ 1, 1, 0, 1, 1, 0, 1 }, // 2
{ 1, 1, 1, 1, 0, 0, 1 }, // 3
{ 0, 1, 1, 0, 0, 1, 1 }, // 4
{ 1, 0, 1, 1, 0, 1, 1 }, // 5
{ 1, 0, 1, 1, 1, 1, 1 }, // 6
{ 1, 1, 1, 0, 0, 0, 0 }, // 7
{ 1, 1, 1, 1, 1, 1, 1 }, // 8
{ 1, 1, 1, 1, 0, 1, 1 }, // 9
{ 0, 0, 0, 0, 0, 0, 1 } // -
};
int32_t currentNumber = 0;
void displayNumber()
{
// Processing the number
int32_t tempCurrentNumber = currentNumber;
uint8_t digitCount = tempCurrentNumber == 0 ? 1 : floor(log10(abs(tempCurrentNumber))) + 1;
if (currentNumber < 0)
{
digitCount++;
tempCurrentNumber = abs(tempCurrentNumber);
}
uint16_t numArr[digitCount] = { };
if (currentNumber < 0)
{
numArr[digitCount - 1] = 10;
}
int8_t i = 0, j = 0, r = 0;
while (tempCurrentNumber != 0)
{
// Extract the last digit of tempCurrentNumber
r = tempCurrentNumber % 10;
// Put the digit in numArr[]
numArr[i] = r;
i++;
// Update tempCurrentNumber to (tempCurrentNumber / 10) to extract
// next last digit
tempCurrentNumber = tempCurrentNumber / 10;
}
// Traversing numArr[] in reverse
for (j = digitCount; j >= 0; j--)
{
for (uint8_t z = 0; z < SEGMENTS_COUNT; z++)
{
bool currentSegment = digitCount > DISPLAYS_COUNT ? digitTable[10][z] : digitTable[numArr[j]][z];
digitalWrite(SEGMENT_PINS[z], !currentSegment);
}
digitalWrite(PS_PINS[j], HIGH);
digitalWrite(PS_PINS[j], LOW);
}
}
class DisplayHandler : public VariableTimedAction
{
private:
unsigned long run()
{
displayNumber();
return 0;
}
};
class Counter : public VariableTimedAction
{
private:
unsigned long run()
{
currentNumber = currentNumber >= 20 ? -2147483647 : ++currentNumber;
return 0;
}
};
void regPins()
{
// 7-segment LED pins
for(uint8_t i = 0; i < SEGMENTS_COUNT; i++)
{
pinMode(SEGMENT_PINS[i], OUTPUT);
}
// 7-segment power supply pins
for(uint8_t i = 0; i < DISPLAYS_COUNT; i++)
{
pinMode(PS_PINS[i], OUTPUT);
}
}
const DisplayHandler displayHandler;
const Counter counter;
void regActions()
{
displayHandler.start(100);
counter.start(200);
}
void setup()
{
regPins();
regActions();
}
void loop()
{
VariableTimedAction::updateActions();
}