//7 segment display from 0-f
/* Example code with timer interrupt that will create an interruption each
* 1ms using timer1 and prescalar of 64.
Calculations (for 1ms):
System clock 16 Mhz and Prescalar 64;
Timer 1 speed = 16Mhz/64 = 250 Khz
Pulse time = 1/250 Khz = 4us
Count up to = 1ms / 4us = 250 (so this is the value the OCR register should have)*/
#define LED_BLUE 13
#define LED_RED 12
#define LED_GREEN 11
unsigned char LED_STATE_10ms = HIGH;
unsigned char LED_STATE_40ms = HIGH;
unsigned char LED_STATE_100ms = HIGH;
unsigned char COUNT_10ms=0;
unsigned char COUNT_40ms=0;
unsigned char COUNT_100ms=0;
void Task_10ms();
void Task_40ms();
void Task_100ms();
void Timer_init();
void digitalpin_init();
void count();
unsigned char num=0;
unsigned char counter=0;
unsigned char display_digit_array[] = {~0x3F,~0x6,~0x5B,~0x4F ,~0x66, ~0x6D,~0x7D,~0x7,~0x7F,~0x6F,0x8,0x00,0x46,~0x3F,0x06,0x0E} ;
void setup()
{
digitalpin_init();
Timer_init(); //Set the pin to be OUTPUT
}
void loop() {
// put your main code here, to run repeatedly:
if(COUNT_10ms >= 10)
{
COUNT_10ms = 0;
Task_10ms();
}
if(COUNT_40ms >= 40)
{
COUNT_40ms = 0;
Task_40ms();
}
if(COUNT_100ms >= 100)
{
COUNT_100ms = 0;
Task_100ms();
}
}
//With the settings above, this IRS will trigger each 500ms.
ISR(TIMER1_COMPA_vect)
{
TCNT1 = 0; //First, set the timer back to 0 so it resets for next interrupt
//Increment count
COUNT_10ms++;
COUNT_40ms++;
COUNT_100ms++;
}
void digitalpin_init()
{
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void Timer_init()
{
cli(); //stop interrupts for till we make the settings
/*1. First we reset the control register to amke sure we start with everything disabled.*/
TCCR1A = 0; // Reset entire TCCR1A to 0
TCCR1B = 0; // Reset entire TCCR1B to 0
/*2. We set the prescalar to the desired value by changing the CS10 CS12 and CS12 bits. */
TCCR1B |= B00000011; //Set CS12 to 1 so we get prescalar 64
/*3. We enable compare match mode on register A*/
TIMSK1 |= B00000010; //Set OCIE1A to 1 so we enable compare match A
/*4. Set the value of register A to 31250*/
OCR1A = 250; //Finally we set compare register A to this value
sei(); //Enable back the interrupts
}
void Task_10ms()
{
LED_STATE_10ms = !LED_STATE_10ms;
digitalWrite(LED_BLUE,LED_STATE_10ms);
}
void Task_40ms()
{
LED_STATE_40ms = !LED_STATE_40ms;
digitalWrite(LED_RED,LED_STATE_40ms);
}
void Task_100ms()
{
display_on(display_digit_array[num]);
count();
}
void display_on(byte num) // This function turns on the correct pins to display numbers passed to it // through the variable “num”.
{
for(int i=0;i<7;i++)
{
unsigned char result = bitRead(num, i);
if (result == 1) // Check to see if this segment should be on.
{
digitalWrite(i+2, HIGH);
} // Turns on the segment.
else // Otherwise, it turns it off.
{
digitalWrite(i+2, LOW);
}
}
}
void count()
{
if(counter>=10 )
{
counter=0;
num=num+1;
if(num>15)
{
num=0;
}
}
else
{
counter++;
}
}