#pragma config MCLRE=ON            // Master Clear desabilitado
#pragma config FOSC=INTOSC_XT      // Oscilador c/ cristal externo HS
#pragma config WDT=OFF             // Watchdog controlado por software
#pragma config LVP=OFF             // Sem programação em baixa tensão
#pragma config DEBUG=OFF           // Desabilita debug
#pragma config XINST=OFF


//funções de bit
#define BitSet(arg,bit) ((arg) |= (1<<bit))
#define BitClr(arg,bit) ((arg) &= ~(1<<bit)) 
#define BitFlp(arg,bit) ((arg) ^= (1<<bit)) 
#define BitTst(arg,bit) ((arg) & (1<<bit)) 


//defines para registros especiais
#define PORTC	(*(volatile __near unsigned char*)0xF82)
#define PORTD	(*(volatile __near unsigned char*)0xF83)

#define TRISC	(*(volatile __near unsigned char*)0xF94)
#define TRISD	(*(volatile __near unsigned char*)0xF95)

#define TRISA	(*(volatile __near unsigned char*)0xF92)
#define ADCON2	(*(volatile __near unsigned char*)0xFC0)
#define ADCON1	(*(volatile __near unsigned char*)0xFC1)
#define ADCON0	(*(volatile __near unsigned char*)0xFC2)
#define ADRESL	(*(volatile __near unsigned char*)0xFC3)
#define ADRESH	(*(volatile __near unsigned char*)0xFC4)


//also disp1
#define RS  6
#define EN  7

void delayMicroseconds(int ms) {
    int i;
    for (; ms > 0; ms--) {
        for (i = 0; i < 30; i++);
    }
}

//pulse the Enable pin high (for a microsecond).
//This clocks whatever command or data is in DB4~7 into the LCD controller.

void pulseEnablePin() {
    BitClr(PORTC, EN);
    delayMicroseconds(1);
    // send a pulse to enable
    BitSet(PORTC, EN);
    delayMicroseconds(1);
    BitClr(PORTC, EN);
    //delay(1);  // pause 1 ms.  TODO: what delay, if any, is necessary here?
}

//push a nibble of data through the the LCD's DB4~7 pins, clocking with the Enable pin.
//We don't care what RS and RW are, here.

void pushNibble(int value, int rs) {
    //  int val_nibble= value & 0x0F;  //clean the value.  (unnecessary)
    PORTD = value;
    //delay(1);
    if (rs) {
        BitSet(PORTC, RS);
    } else {
        BitClr(PORTC, RS);
    }
    pulseEnablePin();
}

//push a byte of data through the LCD's DB4~7 pins, in two steps, clocking each with the enable pin.

void pushByte(int value, int rs) {
    int val_lower = (value << 4) &0xf0;
    int val_upper = value & 0xF0;
    pushNibble(val_upper, rs);
    pushNibble(val_lower, rs);
}

void commandWriteNibble(int nibble) {
    //BitClr(PORTC, RS);
    //if (USING_RW) { digitalWrite(RW, LOW); }
    pushNibble(nibble<<4, 0);
}

void lcdCommand(int value) {
    // BitClr(PORTC, RS);
    //if (USING_RW) { digitalWrite(RW, LOW); }
    pushByte(value, 0);
    //TODO: perhaps better to add a delay after EVERY command, here.  many need a delay, apparently.
    delayMicroseconds(40);
}

//print the given character at the current cursor position. overwrites, doesn't insert.

void lcdChar(int value) {
    //set the RS and RW pins to show we're writing data
    // BitSet(PORTC, RS);
    // if (USING_RW) { digitalWrite(RW, LOW); }

    //let pushByte worry about the intricacies of Enable, nibble order.
    pushByte(value, 1);
    delayMicroseconds(2);
}


//print the given string to the LCD at the current cursor position.  overwrites, doesn't insert.
//While I don't understand why this was named printIn (PRINT IN?) in the original LiquidCrystal library, I've preserved it here to maintain the interchangeability of the two libraries.

void lcdString(char msg[]) {
    unsigned char i = 0; //fancy int.  avoids compiler warning when comparing i with strlen()'s uint8_t
    while (msg[i]) {
        lcdChar(msg[i]);
        i++;
    }
}

void lcdDefconLogo(void) {
    int i;
    unsigned char defcon[] = {
        0x0, 0x1, 0x3, 0x3, 0x3, 0x3, 0x1, 0x4,
        0xe, 0x1f, 0x4, 0x4, 0x1f, 0xe, 0x11, 0x1f,
        0x0, 0x10, 0x18, 0x18, 0x18, 0x18, 0x10, 0x4,
        0xc, 0x3, 0x0, 0x0, 0x0, 0x3, 0xc, 0x4,
        0x0, 0x0, 0x1b, 0x4, 0x1b, 0x0, 0x0, 0x0,
        0x6, 0x18, 0x0, 0x0, 0x0, 0x18, 0x6, 0x2
    };
    lcdCommand(0x40);
    for (i = 0; i < 8 * 6; i++) {
        lcdChar(~defcon[i]);
    }

}

// initiatize lcd after a short pause
//while there are hard-coded details here of lines, cursor and blink settings, you can override these original settings after calling .init()

void lcdInit() {
    BitClr(TRISC, EN);
    BitClr(TRISC, RS);
    TRISD = 0x0f;

    delayMicroseconds(50);

    //The first 4 nibbles and timings are not in my DEM16217 SYH datasheet, but apparently are HD44780 standard...
    commandWriteNibble(0x03);
    delayMicroseconds(5);
    commandWriteNibble(0x03);
    delayMicroseconds(100);
    commandWriteNibble(0x03);
    delayMicroseconds(5);

    // needed by the LCDs controller
    //this being 2 sets up 4-bit mode.
    commandWriteNibble(0x02);
    delayMicroseconds(10);

    //configura o display
    lcdCommand(0x28); //8bits, 2 linhas, 5x8
    lcdCommand(0x06); //modo incremental
    lcdCommand(0x0c); //display e cursor on, com blink
    lcdCommand(0x03); //zera tudo
    lcdCommand(0x80); //posição inicial
    lcdCommand(0x01); //limpar display
    delayMicroseconds(2);
}

void adInit(void) {
    BitSet(TRISA, 0); //pin setup
    ADCON0 = 0b00000001; //channel select
    ADCON1 = 0b00001110; //ref = source
    ADCON2 = 0b10101010; //t_conv = 12 TAD
}

unsigned int adRead(void) {
    unsigned int ADvalue;
    BitSet(ADCON0, 1); //start conversion
    while (BitTst(ADCON0, 1)); //wait
    ADvalue = ADRESH; //read result
    ADvalue <<= 8;
    ADvalue += ADRESL;
    return ADvalue;
}

void main(void) {
    unsigned int i;
    unsigned int ad;
    TRISD = 0x00;
    adInit();

    lcdInit();
    lcdDefconLogo();
    lcdCommand(0x80);
    lcdChar(0);
    lcdChar(1);
    lcdChar(2);
    lcdString(" Defcon");
    lcdCommand(0xC0);
    lcdChar(3);
    lcdChar(4);
    lcdChar(5);
    lcdString("mBed workshop");
    adInit();

    for (;;) {

//        lcdCommand(0x8B);
//        lcdChar((adRead() / 1000) % 10 + 48);
//        lcdChar((adRead() / 100) % 10 + 48);
//        lcdChar((adRead() / 10) % 10 + 48);
//        lcdChar((adRead() / 1) % 10 + 48);
        ad = adRead();
        PORTD = 0xff;
        for (i = 0; i < ad; i++);
        PORTD = 0xff;
        for (i = ad; i < 1024;i ++);
    }
}
