/*
 * File:   DIA.c
 * Author: Vojta
 *
 * Created on 24. zá?í 2022, 18:00
 */




#include "hlava.h"

void load_dia(void) //nacti hodnoty z dia table (pro temp_senzor)
{    
    NVMCON1bits.NVMREGS = 1; //Access EEPROM, DIA, DCI, Configuration, User ID and Device ID Registers
    NVMADR = DIA_FVRA2X; //point to adress FVRA2X (pro temp sensor)
    NVMCON1bits.RD = 1; //nitiates a read at address = NVMADR1, and loads data to NVMDAT Read takes one instruction cycle and the bit is cleared when the operation is complete. The bit can only be set (not cleared) in software
    FVRA2X = NVMDAT; //nacti hodnotu do promenne 
   
    NVMADR = DIA_TSHR2; //point to adress TSHR2 (pro temp sensor)  
    NVMCON1bits.RD = 1; //nitiates a read at address = NVMADR1, and loads data to NVMDAT Read takes one instruction cycle and the bit is cleared when the operation is complete. The bit can only be set (not cleared) in software
    TSHR2 = NVMDAT; //nacti hodnotu do promenne 
  
}

//****************** rozsah eeprom adres je od 0x7000 do 0x70FF.*********
//***************** pro EEPROM se vyuzije jenom NVMDATL (jenom 8 bitu na kazde adrese)

void write_char_eeprom(unsigned char hodnota,  unsigned int adresa)
{
    GIE = 0; //disable global interrupts
    NVMCON1bits.NVMREGS = 1; //Access EEPROM, DIA, DCI, Configuration, User ID and Device ID Registers
    NVMCON1bits.WREN = 1; //Allows program/erase cycles
    NVMADR = adresa; 
    NVMDATL = hodnota;
    NVMCON2 = 0x55; //unlock sekvence pro write/erase
    NVMCON2 = 0xAA; //unlock sekvence pro write/erase
    NVMCON1bits.WR = 1; //spust zapisovaci cyklus
    while(NVMCON1bits.WR); //dokud neni cyklus dokoncen
    NVMCON1bits.WREN = 0; //disable program/erase cycles
    GIE = 1; //enable global interrupts
    
}

unsigned char read_char_eeprom(unsigned int adresa)
{
    NVMCON1bits.NVMREGS = 1; //stejne jak u load dia
    NVMADR = adresa;
    NVMCON1bits.RD = 1;
    while(NVMCON1bits.RD);
    return NVMDATL;
}

void write_int_eeprom(unsigned int hodnota, unsigned int adresaL)
{
    unsigned int adresaL1 = adresaL; 
    write_char_eeprom((char)hodnota,adresaL1); //zapis LOW byte z int hodnoty do první adresy eeprom
    adresaL1++;
    write_char_eeprom((char)(hodnota >> 8),adresaL1);  //zapis HIGH byte z int hodnoty do druhe adresy eeprom
}

unsigned int read_int_eeprom(unsigned int adresaL)
{
    unsigned int int_data=0;
    unsigned int adresaL1 = adresaL;
    int_data |= read_char_eeprom(adresaL1); // nacti LOW byte z prvni adresy eeprom do int promenne
    adresaL1++;
    int_data |= (unsigned int)( 0xFF & read_char_eeprom(adresaL1) ) << 8 ; //nacti HIGH byte z druhe adresy eeprom do int promenne
    
    return int_data;
}

void load_EEPROM_data(void) //nacti hodnoty vykonu a teploty z poslednich nastavenych hodnot nez se vypnul vape
{
    vykon = read_char_eeprom(adr_vykon);
    tc_teplota = read_int_eeprom(adr_teplota);
}