|
/*
|
|
* File: I2C_slave.c
|
|
* Author: Cl?ment
|
|
*
|
|
* Created on 14 octobre 2022, 13:57
|
|
*/
|
|
|
|
#include "mcc_generated_files/mcc.h"
|
|
#include <xc.h>
|
|
|
|
int z;
|
|
|
|
void I2C_Slave_Initialization(char address)
|
|
{
|
|
|
|
TRISCbits.TRISC4 = 1; // Set SDA as a input pin
|
|
TRISCbits.TRISC3 = 1; // Set SCL pins as a input pin
|
|
|
|
SSPADD = address; // store the address of slave in SSPADD register
|
|
|
|
SSPSTAT = 0x80; // set default slew rate
|
|
SSPCON1 = 0x36; // Select & Enable I2C (Slave Mode)
|
|
SSPCON2 = 0x01; // Enable Clock Stretching
|
|
|
|
PIR1bits.SSPIF = 0; // Enbable Interrupts
|
|
PIE1bits.SSPIE = 1; // Enable PICI2C module interrrupt
|
|
INTCONbits.PEIE = 1; // Enable peripheral interrupt
|
|
INTCONbits.GIE = 1; // Enable global interrupt
|
|
|
|
__delay_ms(100); //wait initialization
|
|
|
|
}
|
|
|
|
void __interrupt() ISR(void) {
|
|
if(PIR1bits.SSPIF) {
|
|
CKP = 0; // strecth the clock signal to low
|
|
if (SSPCON1bits.SSPOV || SSPCON1bits.WCOL){ // check errors such as collision and buffer overrflow
|
|
char receiver = SSPBUF; // read the value from SSPBUF to clear it
|
|
SSPCON1bits.SSPOV = 0; // reset overflow detection flag bit
|
|
SSPCON1bits.WCOL = 0; // eset collision detection flag bit
|
|
SSPCON1bits.CKP = 1; // Release Clock from low
|
|
}
|
|
if(!(SSPSTATbits.R_nW)){ // Read
|
|
char receiver = SSPBUF; // read the value from SSPBUF to clear it
|
|
while(!BF);
|
|
RX_Data = SSPBUF; // Read The Received Data Byte
|
|
CKP = 1; // Release Clock Line SCL
|
|
}
|
|
SSPIF = 0; // clear I2C interrupt flag
|
|
}
|
|
}
|