/*

	Copyright Christophe Jacquet, 2009.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/


#include <p18f2455.h>

#pragma config FOSC = HSPLL_HS    // mode oscillateur extérieur HS, PLL activée, HS utilisé pour l'USB
#pragma config PLLDIV = 5         // en entrée de la PLL il FAUT TOUJOURS du 4 MHz. Quartz à 20 MHz => PLLDIV = 5 (prescaler)
#pragma config CPUDIV = OSC4_PLL6 // division par 6 de la fréquence en sortie de la PLL (postscaler) => Fcpu = 16 MHz
#pragma config PBADEN = OFF

#pragma config MCLRE = OFF
#pragma config WDT = OFF

void uart_bit_delay();
void uart_putc(char chr);
void uart_puts_rom(rom char *str);


void uart_bit_delay() {
	unsigned char i;
	_asm
	movlw 59
	movwf i, 0
uart_bit_delay_loop:
	decfsz i, 1, 0
	bra uart_bit_delay_loop
	_endasm
}


void uart_putc(char chr) {
	unsigned char i;
	PORTBbits.RB7 = 0;
	uart_bit_delay();
	for(i = 0; i<8; i++) {
		PORTBbits.RB7 = chr & 1;
		uart_bit_delay();
		chr >>= 1;
	}
	PORTBbits.RB7 = 1;
	uart_bit_delay();
	PORTBbits.RB7 = 0;
}


void uart_puts_rom(rom char *str) {
	while(*str) {
		uart_putc(*str);
		str++;
	}
}


void main() {
	unsigned char a = 'a', b = 0;

	TRISB = 0b01000000;

	for(;;) {
		unsigned char c;
		int i;


		uart_putc(a);

		a++;
		if(a > 'Z' + b) {
			b++;
			uart_putc(13);
			uart_putc(10);

			if(b > 10) {
				b = 0;
				uart_puts_rom("Hello, PIC world.\r\n");
			}

			a = '0' + b;
		}
	}
}
