/*  
 *                          FUNZIONA
 * File:   main.c
 * Author: Lello Guidi
 * Lettura di una 24LC256
 * MPLABX IDE v4.05 e XC8 v1.45
 * LTlib v4.0.4 
 * PIC18F4550
 * clock: 20MHz
 * Freedom II
 * Created on February 14, 2018, 12:06 PM
 */

#include <xc.h>
#include <LTlib_delay.h>
#include <LTlib_delay.c>
#include "module_I2C.h"
#include "module_I2C.c"
#include <module_IO.h>
#include <module_IO.c>
#include <LCD_44780.h>
#include <LCD_44780.c>
#include "I2C_EEPROM.h"
#include "I2C_EEPROM.c"

#define LEDrosso PORTDbits.RD0
#define BTN_UP PORTBbits.RB4	// pulsante incremento btn1
#define BTN_DN PORTBbits.RB5	// pulsante decremento btn2

void main(void) {
    
unsigned char EEPROM_address = 0xA0;        // Indirizzo della 24LC256 esterna
int memory_addressMax=0x7FF0;	// numero massimo di memorizzazioni
int memory_address = 0x00; 		// Indirizzo della cella da leggere       
unsigned char read_data=0;	// dato
unsigned char datoLO=0;	// byte basso
unsigned char datoHI=0;	// byte alto
    
    IO_set_all_ports_as_inputs();
    IO_set_port_direction(IO_PORTD, IO_ALL_PORT_OUTPUT);
    IO_set_port_direction(IO_PORTC, IO_BIT0_OUT);
    IO_set_port_direction(IO_PORTB, IO_BIT4_IN + IO_BIT5_IN);
    IO_enable_pull_up_resistors (IO_PORTB, IO_BIT4 + IO_BIT5 + IO_BIT6 + IO_BIT7);
    
    LCD_initialize(20);
    LCD_backlight(LCD_TURN_ON_LED);
    LCD_cursor(LCD_TURN_OFF_CURSOR, LCD_BLINKING_OFF);
    
    LCD_write_message ("Lettura 24LC256");
	LCD_goto_line(2);
    LCD_write_message ("14 febbraio 2018");
    delay_s(2);  
    LCD_clear();
    
    I2C_EEPROM_initialize (100);
    
    while(1){   
        
        if(BTN_UP == 0){
            memory_address++;
            datoLO = I2C_EEPROM_read_byte (EEPROM_address, memory_address, &read_data);
            delay_ms(5);
            memory_address++;
            datoHI = I2C_EEPROM_read_byte (EEPROM_address, memory_address, &read_data);
            delay_ms(5); 
           }
    
        if(BTN_DN == 0){
            memory_address--;
            memory_address--;
            memory_address--;
            datoLO = I2C_EEPROM_read_byte (EEPROM_address, memory_address, &read_data);
            delay_ms(5);
            memory_address++;
            datoHI = I2C_EEPROM_read_byte (EEPROM_address, memory_address, &read_data);
            delay_ms(5);
          } 
       
     LCD_goto_line(1);   
     LCD_write_message ("cella: ");   
     LCD_goto_xy(8,1); 
     LCD_write_integer (memory_address, 4, LCD_ZERO_CLEANING_OFF);
     LCD_goto_line(2);
     LCD_write_message ("dato: "); 
     LCD_goto_xy(7,2); 
     read_data = datoLO + (datoHI<<8);
     LCD_write_integer (read_data, 4, LCD_ZERO_CLEANING_OFF);
     LEDrosso = 1;
     delay_ms(500);
     LEDrosso = 0;
     }   
   } 

