/*
 * File:   main.c
 * Author: Farhad
 *
 * Created on October 12, 2016, 8:50 PM
 */

#include <xc.h>
#include "pic16f628a.h"

// CONFIG
#pragma config FOSC = INTOSCIO // Oscillator Selection bits (INTOSC oscillator: CLKOUT function on RA6/OSC2/CLKOUT pin, I/O function on RA7/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = ON       // Power-up Timer Enable bit (PWRT enabled)
#pragma config MCLRE = OFF      // RA5/MCLR/VPP Pin Function Select bit (RA5/MCLR/VPP pin function is digital input, MCLR internally tied to VDD)
#pragma config BOREN = OFF      // Brown-out Detect Enable bit (BOD disabled)
#pragma config LVP = OFF        // Low-Voltage Programming Enable bit (RB4/PGM pin has digital I/O function, HV on MCLR must be used for programming)
#pragma config CPD = OFF        // Data EE Memory Code Protection bit (Data memory code protection off)
#pragma config CP = OFF         // Flash Program Memory Code Protection bit (Code protection off)

#pragma warning disable 752

#define _XTAL_FREQ 4000000

const unsigned char led[12] = {0b11000000, 0b11111001, 0b10100100, 0b10110000, 
                               0b10011001, 0b10010010, 0b10000010, 0b11111000, 
                               0b10000000, 0b10010000, 0b10001100, 0b10111111}; // 0..9,P,-
unsigned char i = 0;
unsigned char sec = 16;
bit at_read;

void init(void);

void main(void)
{
    init();
    GIE = 1;
    at_read = 1;
    while (1)
    {
        if (at_read)
        {
            at_read = 0;
            switch (PORTA & 0x1F)
            {
                case 0x0F: i = 0; break;
                case 0x0E: i = 1; break;
                case 0x16: i = 2; break;
                case 0x1C: i = 3; break;
                case 0x15: i = 4; break;
                default: i = 11; break;
            }
// Таймер тикает каждые 256 мкс, до переполнения 65536 мкс.
// 65536*16 = 1 секунда
            sec = 16;
        }
        PORTB = led[i];
    }
}

void interrupt isr()
{
    if ((T0IF) && (T0IE))
    {
        T0IF = 0;
        if (sec) sec--;
            else at_read = 1;
    }
}

void init ()
{
    OPTION_REG = 0b10000111;    // Prescaler 1:256
    TMR0 = 0;
    INTCON = 0b00100000;    // GIE(7), T0IE(5)
    PORTA = 0;
    TRISA = 0b11111111;
    PORTB = 0;
    TRISB = 0b10000000;
    CMCON = 7;
}
