While this question may seem to be better suited for SE Arduino, I shall, nevertheless, propose a solution. Employ a ready written Arduino library, as this would save a lot of groundwork. Granted, as you mention that you have a main()
, then one can assume that you are not using the Arduino IDE. However, the library (with the .cpp
file and .h
file) can still be used.
Interestingly, I went through the pain of coding up a seven segment display last year, on the Arduino, albeit only a two digit display, an SL-1255 (see Dual Seven Segment display madness). I even came up with an all singing and dancing Arduino library, SevenSegmentSL1255.
However, I do not recommend you using it, as it does not use interrupts and, much to my chagrin, I found another, more fully featured, seven segment display Arduino library, SevenSeg, after having completed mine. The SevenSeg library will work with four digit displays and it also handles interrupt driven displays.
From section 4.4 Using Interrupt Timers of the PDF,
Running the printing functions in an endless loop to perform multiplexing is not always an ideal way to do things. Outputting information to a 7-segment display is not a computationally intensive task, but due to the delay used for multiplexing, the microcontroller just sits there and waits for most of the time. Sure, you can insert commands taking little time in a loop together with the printing functions, but if they are slightly time-consuming, the display will halt or flicker. For this purpose it is possible to use SevenSegalong with interrupt timers. Then, you can do whatever you want inside loop(){...}
, and simply run a high-level printing function only when you want to change what's on the display. The microcontroller will automatically be interrupted just briefly to update the display as needed. You can still change the refresh rate and the duty cycle like normal, the SevenSeg-library will take care of configuring the timers for you.
The library code can be downloaded from here.
An example sketch (again taken from section 4.4 of the PDF) is as follows:
#include <SevenSeg.h>
SevenSeg disp(11,7,3,5,6,10,2);
const int numOfDigits =4;
int digitPins[numOfDigits]={12,9,8,13};
void setup () {
disp.setDigitPins(numOfDigits ,digitPins);
disp.setTimer(2); disp.startTimer();
}
void loop() {
for(int i=1;i<=10;i++){
disp.write(i);
delay(1000); // Or other time-consuming tasks
}
}
ISR(TIMER2_COMPA_vect) {
disp.interruptAction();
}
Obviously, you will need to modify the sketch for your particular purposes, notably either calling setup()
and loop()
from your main()
, or incorporating the display updates from the loop()
into your main()
.
However, please make particular note of the Interrupt Service Routine (ISR), as this is what you require: ISR(TIMER2_COMPA_vect) {disp.interruptAction();}
. This will ensure that you have a flicker free display, while the processor is performing processor intensive tasks, when controlling your bot.