Thursday, December 11, 2014

Book Light

/*
 * File:   booklightmain.c
 * Author: Hans Mikelson
 *
 * Created on December 10, 2014, 9:13 PM
 */

#if defined(__XC)
    #include <xc.h>         /* XC8 General Include File */
#elif defined(HI_TECH_C)
    #include <htc.h>        /* HiTech General Include File */
#endif

#include <stdint.h>        /* For uint8_t definition */
#include <stdbool.h>       /* For true/false definition */

#pragma config MCLRE=OFF,CP=OFF,WDTE=OFF,FOSC=INTOSCIO
#define _XTAL_FREQ 4000000
uint8_t sGPIO;

void init()
{
    //Configure GPIO Port
    ANSEL =  0b00000000;  //Configure all GPIO pins as digital
    TRISIO = 0b11001001;  //Set GP1-5 as outputs and the rest as inputs
    OPTION_REGbits.nGPPU = 0;
    WPU = 0b00000001;     //Enable weak pullups on GP0
    //Configuer AD Convertor
    ADCON0 = 0x00;        //AD disabled
    ADRESH = 0x00;        //Init the AD Register
    //Configure Comparator
    CMCON0 = 0xFF;   // Comparator is turned off
    CMCON1 = 0x00;   // Comparator is turned off
    //Interrupt configuration
    INTCON = 0x00;   //Disable all interrupts
}

void vdelay(int n)
{
    int i;
    for (i=0;i<=n;i++)
    {
     __delay_us(1);
    }
}

void main()
{
    int i,j;
    int d[8]={1,2,4,8,16,32,64,127};
    init();
    GPIO = 0b00110001;
    i=0;
    while(1)
    {
       if (GPIObits.GP0 == 0)
       {
           i=(i+1)%8;
           vdelay(1000000);
       }
       GPIO = 0b11110000;
       vdelay(128-d[i]);
       GPIO = 0b11000000;
       vdelay(d[i]);
    }
}