#include <16F1827.h>
#FUSES NOMCLR, NOBROWNOUT, NOFCMEN, NOSTVREN, NOLVP, NOIESO
#use delay(internal=4MHz)
#ifndef EEPROM_SELECT
#define EEPROM_SELECT PIN_B3
#define EEPROM_CLK PIN_B4
#define EEPROM_DI PIN_B2
#define EEPROM_DO PIN_B1
#endif
#define LED PIN_B7
#define EEPROM_ADDRESS long int
#define EEPROM_SIZE 2048
void init_ext_eeprom()
{
output_high(EEPROM_SELECT);
output_low(EEPROM_DI);
output_low(EEPROM_CLK);
}
BOOLEAN ext_eeprom_ready()
{
BYTE cmd[1], i, data;
cmd[0] = 0x05; //rdsr opcode
output_low(EEPROM_SELECT);
for(i=1; i<=8; ++i) {
output_bit(EEPROM_DI, shift_left(cmd,1,0));
output_high(EEPROM_CLK); //data latches
output_low(EEPROM_CLK); //back to idle
}
for(i=1; i<=8; ++i) {
output_high(EEPROM_CLK); //data latches
shift_left(&data,1,input(EEPROM_DO));
output_low(EEPROM_CLK); //back to idle
}
output_high(EEPROM_SELECT);
return !bit_test(data, 0);
}
void write_ext_eeprom(EEPROM_ADDRESS address, BYTE data)
{
BYTE cmd[4];
BYTE i;
BYTE wren;
wren=0x06;
cmd[0]=data;
cmd[1]=address;
cmd[2]=(address>>8);
cmd[3]=0x02;
// Wait until the eeprom is done with a previous write
while(!ext_eeprom_ready());
output_low(EEPROM_SELECT);
for(i=0; i<8; ++i)
{
output_bit(EEPROM_DI, shift_left(&wren,1,0));
output_high(EEPROM_CLK);
output_low(EEPROM_CLK);
}
output_high(EEPROM_SELECT);
output_low(EEPROM_SELECT);
for(i=0; i<32; ++i)
{
output_bit(EEPROM_DI, shift_left(cmd,4,0));
output_high(EEPROM_CLK);
output_low(EEPROM_CLK);
}
output_high(EEPROM_SELECT);
}
BYTE read_ext_eeprom(EEPROM_ADDRESS address)
{
BYTE cmd[3];
BYTE i,data;
cmd[0]=address;
cmd[1]=(address>>8);
cmd[2]=0x03;
// Wait until the eeprom is done with a previous write
while(!ext_eeprom_ready());
output_low(EEPROM_SELECT);
for(i=0; i<24; ++i)
{
output_bit(EEPROM_DI, shift_left(cmd,3,0));
output_high(EEPROM_CLK);
output_low(EEPROM_CLK);
}
for(i=0; i<8; ++i)
{
shift_left(&data,1,input(EEPROM_DO));
output_high(EEPROM_CLK);
output_low(EEPROM_CLK);
}
output_high(EEPROM_SELECT);
return(data);
}
void main()
{
delay_ms(100);
init_ext_eeprom();
for(long int i = 0; i < EEPROM_SIZE; i++)
{
write_ext_eeprom(i, 0x30); // Fill the 0s
delay_ms(1);
}
for(;;)
{
delay_ms(100);
output_toggle(LED);
}
}