#include <xc.h> #define _XTAL_FREQ 4000000 #define cs LATA5
void spi_Initial() { TRISCbits.TRISC4 = 1;
/* RC4 configurer comme entrée (SDI) */
TRISCbits.TRISC3 = 0;
/* RC3 configurer comme sortie (SCK) */
TRISAbits.TRISA5 = 0;
/* RA5 configurer comme sortie */
TRISCbits.TRISC5 = 0;
/* RC5 configurer comme sortie (SDO) */
/*Pour initialiser la communication SPI,configurez le registre suivant */
SSPSTAT=0x42;
/* Changement de données sur le front montant de clk, BF = 0 */
SSPCON1=0x20;
/*Mode esclave, activation de la série, état de veille élevé pour clk*/
PIR1bits.SSPIF=0; ADCON1=0x0F;
/* This makes all pins as digital I/O */
cs=1; }
void spi_write(unsigned char data) { SSPBUF=data;
/*COPIE DATA DANS LE REGISTRE SSPBUF*/
}
unsigned char spi_read() { unsigned char c; c=SSPBUF; while(!PIR1bits.SSPIF)
PIR1bits.SSPIF = 0; return(c); }
unsigned char read_data_eep(unsigned long addr) { unsigned char data; cs=0; spi_write(0X03);
/*Read data from memory array beginning at selected addres*/
spi_write(addr>>16); spi_write(addr>>8); /*read address*/ spi_write((unsigned char)addr); data=spi_read();
/*read data*/
cs=1; return data; } void write_data_eep(unsigned char data,unsigned long addr) { cs=0; spi_write(0X06);
/*Set the write enable latch (enable write operations)*/
cs=1;
cs=0; /*envoyer l'adresse suivi par le message */ spi_write(0X02); /* L'instruction de l'écriture*/ spi_write(addr>>16); spi_write(addr>>8); spi_write((unsigned char)addr); spi_write(data); cs=1; }
void main(void) { unsigned char out; TRISB=0X00; spi_Initial(); cs=0; write_data_eep(03,0X0000); out=read_data_eep(0X0000); while(1); LATB=out; }