Skip to content

Instantly share code, notes, and snippets.

@i-khater

i-khater/i2c.h Secret

Created July 5, 2023 16:55
#include <xc.h>
#include <stdint.h>
// I2C Initialization function
void i2c_init() {
// Set I2C pins as inputs
TRISBbits.TRISB4 = 1; // SCL pin
TRISBbits.TRISB5 = 1; // SDA pin
// Configure I2C module
SSP1CON1bits.SSPEN = 0; // Disable MSSP module during configuration
SSP1CON1bits.SSPM = 0b1000; // I2C Master mode, clock = Fosc / (4 * (SSP1ADD+1))
SSP1ADD = 9; // I2C clock = Fosc / (4 * (9+1)) = Fosc / 40
SSP1CON1bits.SSPEN = 1; // Enable MSSP module
}
// I2C Start condition
void i2c_start() {
SSP1CON2bits.SEN = 1; // Initiate Start condition
while (SSP1CON2bits.SEN); // Wait for Start condition to complete
}
// I2C Stop condition
void i2c_stop() {
SSP1CON2bits.PEN = 1; // Initiate Stop condition
while (SSP1CON2bits.PEN); // Wait for Stop condition to complete
}
// I2C Write function
void i2c_write(uint8_t data) {
SSP1BUF = data; // Write data to SSPBUF
while (SSP1STATbits.BF); // Wait for transmission to complete
while (SSP1CON2bits.ACKSTAT); // Wait for ACK/NACK
}
// I2C Read function with ACK
uint8_t i2c_read_ack() {
SSP1CON2bits.RCEN = 1; // Enable receive mode
while (!SSP1STATbits.BF); // Wait for data reception
uint8_t data = SSP1BUF; // Read data from SSPBUF
SSP1CON2bits.ACKDT = 0; // Send ACK
SSP1CON2bits.ACKEN = 1; // Initiate ACK/NACK
while (SSP1CON2bits.ACKEN); // Wait for ACK/NACK to complete
return data;
}
// I2C Read function with NACK
uint8_t i2c_read_nack() {
SSP1CON2bits.RCEN = 1; // Enable receive mode
while (!SSP1STATbits.BF); // Wait for data reception
uint8_t data = SSP1BUF; // Read data from SSPBUF
SSP1CON2bits.ACKDT = 1; // Send NACK
SSP1CON2bits.ACKEN = 1; // Initiate ACK/NACK
while (SSP1CON2bits.ACKEN); // Wait for ACK/NACK to complete
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment