PIC16F-6-I2C-I2C-Master-Functions

by Marwen Maghrebi
void I2C_Master_Init(void) {
    SSPCON = 0x28;              // SSPEN = 1, I2C Master mode
    SSPCON2 = 0x00;
    SSPSTAT = 0x00;
    SSPADD = ((_XTAL_FREQ / 4) / I2C_BAUD_RATE) - 1;  // Baud rate formula
    TRISC3 = 1;                // SCL (clock) as input
    TRISC4 = 1;                // SDA (data) as input
}

void I2C_Wait(void) {
    while ((SSPSTAT & 0x04) || (SSPCON2 & 0x1F));  // Wait until SSPBUF is clear
}

void I2C_Start(void) {
    I2C_Wait();
    SEN = 1;  // Initiate I2C start condition
}

void I2C_Stop(void) {
    I2C_Wait();
    PEN = 1;  // Initiate I2C stop condition
}

void I2C_ACK(void) {
    I2C_Wait();
    ACKDT = 0;  // 0 -> ACK
    ACKEN = 1;  // Send ACK signal
}

void I2C_NACK(void) {
    I2C_Wait();
    ACKDT = 1;  // 1 -> NACK
    ACKEN = 1;  // Send NACK signal
}

unsigned char I2C_Write(unsigned char data) {
    I2C_Wait();
    SSPBUF = data;  // Load data into buffer
    I2C_Wait();
    return ACKSTAT;  // Return ACK/NACK status
}

unsigned char I2C_Read(void) {
    unsigned char data;
    I2C_Wait();
    RCEN = 1;  // Enable receive mode
    I2C_Wait();
    data = SSPBUF;  // Read data from buffer
    I2C_NACK();     // Send NACK signal
    return data;
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00