/*****************************************************************************
 *
 * Basic access to SPI EEPROM 25LC256.
 *
 *****************************************************************************
 * FileName:        25LC256.c
 * Dependencies:    MainDemo.h
 * Processor:       PIC24
 * Compiler:       	MPLAB C30 V3.00
 * Linker:          MPLAB LINK30
 * Company:         Microchip Technology Incorporated
 *
 * Software License Agreement
 *
 * Copyright © 2007 Microchip Technology Inc.  All rights reserved.
 * Microchip licenses to you the right to use, modify, copy and distribute
 * Software only when embedded on a Microchip microcontroller or digital
 * signal controller, which is integrated into your product or third party
 * product (pursuant to the sublicense terms in the accompanying license
 * agreement).  
 *
 * You should refer to the license agreement accompanying this Software
 * for additional information regarding your rights and obligations.
 *
 * SOFTWARE AND DOCUMENTATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY
 * OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR
 * PURPOSE. IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR
 * OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION,
 * BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT
 * DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL,
 * INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
 * COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY
 * CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF),
 * OR OTHER SIMILAR COSTS.
 *
 * Author               Date        Comment
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * Anton Alkhimenok		07/10/07	...
 *****************************************************************************/

/*
******************************************************************************
* Modify from SPI2 to SPI1
* Author: John Leung
* Hardware: PIC24-Eval-B2 Rev A with TY320T-240320-BO Rev 2C
* 			Change the original SPI2 to SPI1 for EEPROM aliases
* Date: 22 Feb 2008
******************************************************************************
*/

#include "AN1136Demo.h"

/************************************************************************
* Function: EEPROMInit                                                  
*                                                                       
* Overview: this function setup SPI and IOs connected to EEPROM
*                                                                       
* Input: none                                                          
*                                                                       
* Output: none
*                                                                       
************************************************************************/
void EEPROMInit()
{
    // Initialize SPI
    SPI1STAT = 0;
    SPI1CON1 = 0b0000000000011011; 
    SPI1CON1bits.MSTEN = 1; 
    SPI1CON2 = 0;
    SPI1CON1bits.MODE16 = 0;
    SPI1CON1bits.CKE = 0;
    SPI1CON1bits.CKP = 1;
    SPI1CON1bits.SMP = 1;
    SPI1STATbits.SPIEN = 1;

    // Set IOs directions for EEPROM SPI
    EEPROM_SS_PORT = 1;
    EEPROM_SS_TRIS = 0;
    EEPROM_SCK_TRIS = 0;
    EEPROM_SDO_TRIS = 0;
    EEPROM_SDI_TRIS = 1;
}

/************************************************************************
* Function SPIPut(BYTE data)                                                       
*                                                                       
* Overview:  this function sends a byte                     
*                                                                       
* Input: byte to be sent
*                                                                       
* Output: none
*                                                                       
************************************************************************/           
void SPIPut(BYTE data)
{
    // Wait for free buffer
    while(SPI1STATbits.SPITBF);
    SPI1BUF = data;
    // Wait for a data byte reception
    while(SPI1STATbits.SPIRBF == 0);
}

/************************************************************************
* Macros SPIGet()                                                       
*                                                                       
* Overview:  this macros gets a byte from SPI                      
*                                                                       
* Input: none
*                                                                       
* Output: none
*                                                                       
************************************************************************/           
#define SPIGet() SPI1BUF

/************************************************************************
* Function: void EEPROMWriteByte(BYTE data, WORD address)                                           
*                                                                       
* Overview: this function writes a byte to the address specified
*                                                                       
* Input: data to be written and address
*                                                                       
* Output: none                                 
*                                                                       
************************************************************************/
void EEPROMWriteByte(BYTE data, WORD address)
{
    EEPROMWriteEnable();
    EEPROMSSLow();

    SPIPut(EEPROM_CMD_WRITE);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[1]);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[0]);
    SPIGet();

    SPIPut(data);
    SPIGet();

    EEPROMSSHigh();

    // Wait for write end
    while(EEPROMReadStatus().Bits.WIP);
}

/************************************************************************
* Function: BYTE EEPROMReadByte(WORD address)             
*                                                                       
* Overview: this function reads a byte from the address specified         
*                                                                       
* Input: address                                                     
*                                                                       
* Output: data read
*                                                                       
************************************************************************/
BYTE EEPROMReadByte(WORD address){
BYTE temp;
    EEPROMSSLow();

    SPIPut(EEPROM_CMD_READ);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[1]);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[0]);
    SPIGet();

    SPIPut(0);
    temp = SPIGet();

    EEPROMSSHigh();
    return temp;
}

/************************************************************************
* Function: void EEPROMWriteWord(WODR data, WORD address)                                           
*                                                                       
* Overview: this function writes a 16-bit word to the address specified
*                                                                       
* Input: data to be written and address
*                                                                       
* Output: none                                                         
*                                                                       
************************************************************************/
void EEPROMWriteWord(WORD data, WORD address)
{
    EEPROMWriteByte(((WORD_VAL)data).v[0],address);
    EEPROMWriteByte(((WORD_VAL)data).v[1],address+1);
}

/************************************************************************
* Function: WORD EEPROMReadWord(WORD address)             
*                                                                       
* Overview: this function reads a 16-bit word from the address specified         
*                                                                       
* Input: address                                                     
*                                                                       
* Output: data read
*                                                                       
************************************************************************/
WORD EEPROMReadWord(WORD address){
WORD_VAL temp;

    temp.v[0] = EEPROMReadByte(address);
    temp.v[1] = EEPROMReadByte(address+1);

    return temp.Val;
}

/************************************************************************
* Function: EEPROMWriteEnable()                                         
*                                                                       
* Overview: this function allows write/erase EEPROM. Must be called  
* before every write/erase command.                                         
*                                                                       
* Input: none                                                          
*                                                                       
* Output: none                                 
*                                                                       
************************************************************************/
void EEPROMWriteEnable(){
    EEPROMSSLow();
    SPIPut(EEPROM_CMD_WREN);
    SPIGet();
    EEPROMSSHigh();
}

/************************************************************************
* Function: EEPROMReadStatus()                                          
*                                                                       
* Overview: this function reads status register
*                                                                       
* Input: none                                                          
*                                                                       
* Output: status register value
*                                                                       
************************************************************************/
union _EEPROMStatus_ EEPROMReadStatus(){
BYTE temp;

    EEPROMSSLow();
    SPIPut(EEPROM_CMD_RDSR);
    SPIGet();

    SPIPut(0);
    temp = SPIGet();
    EEPROMSSHigh();

    return (union _EEPROMStatus_)temp;
}

/************************************************************************
* Function: BYTE EEPROMWriteArray(DWORD address, BYTE* pData, nCount)
*                                                                       
* Overview: this function writes a data array at the address specified
*                                                                       
* Input: flash memory address, pointer to the data array, data number
*                                                                       
* Output: return 1 if the operation was successfull
*                                                                     
************************************************************************/
BYTE EEPROMWriteArray(DWORD address, BYTE* pData, WORD nCount)
{
DWORD_VAL addr;
BYTE*     pD;
WORD      counter;


    addr.Val = address;
    pD       = pData;

    // WRITE

    EEPROMWriteEnable();
    EEPROMSSLow();

    SPIPut(EEPROM_CMD_WRITE);
    SPIGet();

    SPIPut(addr.v[1]);
    SPIGet();
    
    SPIPut(addr.v[0]);
    SPIGet();

    for(counter=0; counter<nCount; counter++)
    {
        SPIPut(*pD++);
        SPIGet();
        addr.Val++;

        // check for page rollover
        if((addr.v[0]&0x7f) == 0){

            EEPROMSSHigh();

            // Wait for completion of the write operation
            while(EEPROMReadStatus().Bits.WIP);
                        
            // Start writing of the next page
    
            EEPROMWriteEnable();
            EEPROMSSLow();

            SPIPut(EEPROM_CMD_WRITE);
            SPIGet();

            SPIPut(addr.v[1]);
            SPIGet();

            SPIPut(addr.v[0]);
            SPIGet();
        }
    }


    EEPROMSSHigh();

    // Wait for write end
    while(EEPROMReadStatus().Bits.WIP);
    
    // VERIFY

    for(counter=0; counter<nCount; counter++)
    {              
        if(*pData != EEPROMReadByte(address))
            return 0;
        pData++;
        address++;
    }

    return 1;
}

/************************************************************************
* Function: void EEPROMReadArray(WORD address, BYTE* pData, nCount)
*                                                                       
* Overview: this function reads data into buffer specified
*                                                                       
* Input: flash memory address, pointer to the data buffer, data number
*                                                                       
************************************************************************/
void EEPROMReadArray(WORD address, BYTE* pData, WORD nCount)
{

    EEPROMSSLow();

    SPIPut(EEPROM_CMD_READ);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[1]);
    SPIGet();

    SPIPut(((WORD_VAL)address).v[0]);
    SPIGet();

    while(nCount--){
        SPIPut(0);
        *pData++ = SPIGet();
    }

    EEPROMSSHigh();
}
