#include <p18F4620.h>
#include <delays.h>
#include <spi.h>
#include <usart.h>
#include <stdio.h>
#pragma config WDT = OFF
#pragma config MCLRE = ON
#pragma config LVP = OFF
#pragma config XINST=OFF
#pragma config OSC=INTIO67
#define CLOCK_FREQ (40000000ul) // Hz
#define CSEE PORTCbits.RC0 // select line for Serial EEPROM
#define SEE_WRSR 1 // write status register
#define SEE_WRITE 2 // write command
#define SEE_READ 3 // read command
#define SEE_WRDI 4 // write disable
#define SEE_STAT 5 // read status register
#define SEE_WREN 6 // write enable
void SPIEEPROMInit();
void UARTInit();
void writeSPI()
{
CSEE = 0;
SSPBUF = SEE_WREN; // write to buffer for TX
while( !SSPSTATbits.BF ); // wait for transfer to complete
CSEE = 1; // brought high to set write enable latch
Delay1TCY(); // 100ns delay. minimum delay is 50ns.
CSEE = 0;
SSPBUF = SEE_WRITE;
while( !SSPSTATbits.BF ); // wait for transfer to complete
SSPBUF = 0b00000000; // First address byte
while( !SSPSTATbits.BF ); // wait for transfer to complete
SSPBUF = 0b00000010; // Second address byte
while( !SSPSTATbits.BF ); // wait for transfer to complete
SSPBUF = 0b10101010; // Write data
while( !SSPSTATbits.BF ); // wait for transfer to complete
CSEE = 1; // To start writing
Delay10KTCYx(5); // Internal write cycle time of 5ms
CSEE = 0;
SSPBUF = SEE_WRDI;
while( !SSPSTATbits.BF ); // wait for transfer to complete
CSEE = 1;
}//writeSPI
int readSPI()
{
CSEE = 0;
SSPBUF = SEE_READ;
while( !SSPSTATbits.BF ); // wait for transfer to complete
SSPBUF = 0b00000000; // First address byte
while( !SSPSTATbits.BF ); // wait for transfer to complete
SSPBUF = 0b00000010; // Second address byte
while( !SSPSTATbits.BF ); // wait for data received
Delay1TCY();
SSPBUF = 0b00000000; // Send dummy byte
while( !SSPSTATbits.BF ); // wait for data received
SSPBUF=getcSPI();
CSEE = 1; // Stop receiving
return SSPBUF;
}//readSPI
void main()
{
int data1, data2, i;
SPIEEPROMInit();
TRISCbits.TRISC0 = 0;
while (1)
{
writeSPI();
i=1000;
while (i>0)
{
// Delay10KTCYx(100); //Delay 1ms
i=i-1;
}
data1 = readSPI();
Delay10KTCYx(200); //Delay 1ms
}
}
void SPIEEPROMInit()
{
SSPSTAT = 0xC0; //SPI Bus mode 0,0
SSPCON1 = 0x21; //Enable SSP,Fosc/16
DDRCbits.RC7 = 0; //Define CS as Output
DDRCbits.RC3 = 0; //Define SCK as Output
DDRCbits.RC4 = 1; //Define SDI as Input
DDRCbits.RC5 = 0; //Define SDO as Output
CSEE = 1; //
}