/* 
 * File:   main.c
 * Author: topicchi
 *
 * Created on 12 maggio 2013, 15.38
 *
 * PIC16F874A
 *
 */

#pragma config FOSC = HS, WDTE = OFF, CP = OFF, PWRTE = OFF, LVP = OFF, DEBUG = ON

/* Definizione della frequenza di funzionamento */


#include <stdio.h>
#include <stdlib.h>
#include <xc.h>
#include "main.h"
#include "lcd_hd44780.h"

#define BAUD 9600
#define FOSC _XTAL_FREQ

#define RX_PIN TRISC7
#define TX_PIN TRISC6

void init_comms(void)
{
	RX_PIN = 1;
	TX_PIN = 1;

	// compute the divider for speed (see page 161)
	SPBRG = ((int)(FOSC/(16UL * BAUD) -1));
	// Asynchronous mode (TXSTA)
	SYNC = 0;
	// 8 bits reception (RCSTA)
	RX9 = 0;
	// enable the receiver (RCSTA)
	CREN = 1;
	// High baud rate select (TXSTA)
	BRGH = 1;
	// 8 bits transmission (TXTSA)
	TX9 = 0;
	// enable transmission (TXTSA)
	TXEN = 1;
	// enable the Serial Port (RCSTA)
	SPEN = 1;
}

void uart_putc(unsigned char byte)
{
	/* output one byte */
	while(!TXIF)	/* set when register is empty */
		continue;
	TXREG = byte;
}

unsigned char uart_getc() {
	/* retrieve one byte */
	while(!RCIF)	/* set when register is not empty */
		continue;
	return RCREG;
}

unsigned char uart_getce(void)
{
	unsigned char c;
	putch(c = getch());
	return c;
}
/* uart_puts(): scrive una stringa sulla porta seriale*/
void uart_puts(char *s)
{
    while (*s) {
        uart_putc(*s);
        s++;
    }
}

/*
 * Programma principale
 */
int main(int argc, char** argv) {
    char i;

    // No interrupts.
    INTCON=0;
   
    TRISB = 0x00;
    PORTB = 0x00;
    TRISD = 0x00;
    PORTD = 0x00;

    // Get LCD ready
    lcd_init();
    lcd_goto(0x00);
    lcd_puts("* Love *");
    lcd_goto(0x40);
    lcd_puts(" Silvia");

    // Get the UART ready
    init_comms();

    while(1) // Run Forever
    {
        for (i = 0; i<8; i++) {
            PORTB=15-i;
            __delay_ms(50);
        }
        uart_putc('a');
    }
    return (EXIT_SUCCESS);
}

