The user wants C code to interface with an external EEPROM using bit-banging I2C.
1. Understand the Goal:
The objective is to provide a complete, readable, and portable C implementation for communicating with an I2C EEPROM (like the common 24Cxx series) without using hardware I2C peripherals. This is known as "bit-banging."
2. Key Components Required:
- GPIO Control: Functions to set SCL (Clock) and SDA (Data) lines high/low and to read SDA.
- Timing/Delays: I2C has specific timing requirements (setup/hold times). Since this is bit-banging, simple delay loops or HAL delay functions are needed.
- I2C Primitives:
- Start Condition
- Stop Condition
- Write Bit
- Read Bit
- I2C Transactions:
- Write Byte (sends byte, gets ACK/NACK)
- Read Byte (reads byte, sends ACK/NACK)
- EEPROM Specific Functions:
- Write Byte to Address
- Read Byte from Address
- (Optional but good) Page Write / Sequential Read.
3. Platform Abstraction (The "Hardware" Layer):
Since I don't know the specific microcontroller (AVR, STM32, PIC, ESP32, etc.), I must write the code to be generic. I will define macros or placeholder functions for:
set_sda_high(), set_sda_low()
set_scl_high(), set_scl_low()
read_sda()
delay_us()
4. I2C Protocol Logic:
- Idle State: Both SCL and SDA are High.
- Start: SDA goes Low while SCL is High.
- Stop: SDA goes High while SCL is High.
- Data Transmission:
- SCL Low.
- Change SDA (if writing).
- SCL High (Data is valid).
- Read SDA (if reading).
- Acknowledge (ACK): Receiver pulls SDA Low during the 9th clock pulse.
5. EEPROM Specifics (Standard 24Cxx):
- Device Address: Usually
1010 + [A0 A1 A2] + [R/W].
- Write Addr:
0xA0 (assuming pins grounded).
- Read Addr:
0xA1.
- Write Cycle: EEPROMs take time (usually 5ms) to actually write the data to non-volatile memory. A write function needs a delay or a polling mechanism (Ack Polling) afterwards.
6. Drafting the Code Structure:
- Header: Includes, Macros for GPIO.
- Low-Level HAL:
I2C_Init, I2C_Delay.
- Bit-Banging Primitives:
I2C_Start, I2C_Stop, I2C_WriteBit, I2C_ReadBit.
- Byte-Level:
I2C_WriteByte, I2C_ReadByte.
- High-Level EEPROM:
EEPROM_Write, EEPROM_Read.
7. Refinement and Edge Cases:
- Clock Stretching: Some slaves hold SCL low. A robust implementation should check if SCL actually went high before proceeding. For a basic example, simple delays usually suffice, but checking is better. I'll stick to simple delays for clarity but mention it.
- Input/Output Switching: SDA is open-drain (bi-directional).
- To send '0': Drive Low.
- To send '1' (or read): Release (Float/High-Z).
- I need a function
SetSDA_Input() and SetSDA_Output(), or rely on the specific hardware behavior (writing '1' to an open-drain output often acts as input). I will assume explicit direction control or "write high to read" logic.
8. Writing the Code (Mental Draft & Iteration):
-
Start: SDA Low -> SCL Low.
-
Stop: SCL Low -> SDA Low -> SCL High -> SDA High. (Wait, Start is SDA High->Low with SCL High).
- Correction Start: SDA High, SCL High. SDA Low. SCL Low.
- Correction Stop: SCL Low. SDA Low. SCL High. SDA High.
-
Write Byte:
- Loop 8 bits (MSB first).
- Set SDA.
- Toggle SCL.
- Read ACK.
9. Structuring the Explanation:
- Disclaimer: Mention this is platform-agnostic.
- The Hardware Layer: Explain what needs to be defined (GPIOs, Delays).
- The I2C Layer: The bit-banging implementation.
- The Driver Layer: EEPROM specific commands.
- Usage Example: How to call it in
main.
10. Self-Correction/Refinement during drafting:
- Issue: How to handle the SDA line switching direction?
- Solution: In the
I2C_ReadByte function, SDA must be set to input (or output open-drain high) before toggling the clock to read the bit.
- Timing:
delay_us is crucial. I'll define a dummy DELAY_US macro.
11. Final Code Assembly:
(Proceeding to generate the C code based on these steps. I will ensure standard 24Cxx addressing is used).
- Addressing:
0xA0 is the standard base address for 24LC series.
- Page Write: Usually limited to page size (e.g., 8 or 64 bytes). I'll stick to Single Byte Write for simplicity, maybe add a sequential read buffer function as it's common.
12. Final Review of the generated code:
Does I2C_Start follow the spec? SDA High, SCL High. SDA Low. SCL Low. Yes.
Does I2C_Stop follow the spec? SCL Low. SDA Low. SCL High. SDA High. Yes.
Is ACK handling correct? Master releases SDA, generates clock, reads SDA. 0 = ACK, 1 = NACK.
Let's write the response.
Bit-banging I2C involves manually toggling General Purpose Input/Output (GPIO) pins to mimic the I2C hardware protocol. This is useful on microcontrollers that lack dedicated I2C hardware or when the hardware has bugs.
Below is a generic, portable C implementation designed for an EEPROM (like the common 24Cxx series).
1. The Hardware Abstraction Layer
Since C does not know about your specific microcontroller's registers, you must implement the HAL section to match your hardware (e.g., STM32 HAL, Arduino registers, AVR, PIC).
2. The Code
/*
* File: i2c_bitbang.c
* Description: Generic Bit-Banging I2C Driver for EEPROM (e.g., 24Cxx)
*/
#include <stdint.h>
// ============================================================================
// 1. CONFIGURATION & HAL (Hardware Abstraction Layer)
// ============================================================================
// YOU MUST IMPLEMENT THESE FUNCTIONS FOR YOUR SPECIFIC MICROCONTROLLER
// Define your pin states
#define HIGH 1
#define LOW 0
// Define your I2C Address (Usually 0xA0 for 24Cxx series, shifted left)
// Note: The functions below expect an 8-bit address (Read/Write bit included).
#define EEPROM_ADDR_W 0xA0
#define EEPROM_ADDR_R 0xA1
// Placeholder for microsecond delay.
// I2C requires strict timing (Standard mode: 100kHz, Fast: 400kHz).
// For 100kHz, toggle every ~5us.
// TODO: Replace this with your MCU's specific delay function (e.g., HAL_Delay, _delay_us)
static void delay_us(uint32_t us) {
// volatile int i;
// for(i=0; i<us*10; i++); // Simple busy wait example
}
// TODO: Implement these to set pin directions and states
void I2C_GPIO_Init(void) {
// Configure SDA and SCL pins as Open-Drain Outputs (or Input/Output switching)
// Initial state is HIGH (Idle)
}
void SCL_set(uint8_t state) {
// Set SCL pin to state (HIGH or LOW)
}
void SDA_set(uint8_t state) {
// Set SDA pin to state (HIGH or LOW)
}
uint8_t SDA_read(void) {
// Read the current logic level of the SDA pin
return 0;
}
// Helper to switch SDA to Input mode (for reading ACK/NACK)
void SDA_Input_Mode(void) {
// Change SDA GPIO direction to INPUT
}
// Helper to switch SDA to Output mode
void SDA_Output_Mode(void) {
// Change SDA GPIO direction to OUTPUT
}
// ============================================================================
// 2. I2C LOW-LEVEL PRIMITIVES
// ============================================================================
// I2C Start Condition: SDA goes LOW while SCL is HIGH
void I2C_Start(void) {
SDA_Output_Mode();
SDA_set(HIGH);
SCL_set(HIGH);
delay_us(5); // tSU;STA (Setup time)
SDA_set(LOW);
delay_us(5); // tHD;STA (Hold time)
SCL_set(LOW); // Clamp clock low to start data transmission
delay_us(5);
}
// I2C Stop Condition: SDA goes HIGH while SCL is HIGH
void I2C_Stop(void) {
SDA_Output_Mode();
SCL_set(LOW);
SDA_set(LOW);
delay_us(5);
SCL_set(HIGH);
delay_us(5); // tSU;STO
SDA_set(HIGH);
delay_us(5); // tBUF (Bus free time)
}
// Write a single bit to the bus
void I2C_WriteBit(uint8_t bit) {
SDA_Output_Mode();
SDA_set(bit ? HIGH : LOW);
delay_us(2); // tSU;DAT
SCL_set(HIGH); // Clock Pulse
delay_us(5); // tHIGH
SCL_set(LOW);
delay_us(2);
}
// Read a single bit from the bus
uint8_t I2C_ReadBit(void) {
uint8_t bit;
SDA_Input_Mode(); // Release SDA line (Pull-up resistors pull it high)
SDA_set(HIGH); // Optional: Ensure high if using push-pull temporarily
delay_us(2);
SCL_set(HIGH); // Clock Pulse
delay_us(5);
bit = SDA_read(); // Read data while SCL is high
SCL_set(LOW);
delay_us(2);
SDA_Output_Mode();
return bit;
}
// Write a byte and check for ACK
// Returns: 0 if ACK received, 1 if NACK
uint8_t I2C_WriteByte(uint8_t data) {
uint8_t i;
// Send 8 bits, MSB first
for (i = 0; i < 8; i++) {
I2C_WriteBit(data & 0x80); // Mask for MSB
data <<= 1; // Shift left
}
// Read ACK bit (9th clock pulse)
// ACK = 0 (Line pulled low by slave), NACK = 1
uint8_t ack = I2C_ReadBit();
return ack;
}
// Read a byte from the bus
// nack: If 1, send NACK (end of read), if 0, send ACK (continue reading)
uint8_t I2C_ReadByte(uint8_t nack) {
uint8_t i, data = 0;
SDA_Input_Mode(); // Ensure SDA is high-Z
for (i = 0; i < 8; i++) {
data <<= 1;
if (I2C_ReadBit()) {
data |= 1;
}
}
// Send ACK/NACK bit
if (nack) {
I2C_WriteBit(HIGH); // Send NACK
} else {
I2C_WriteBit(LOW); // Send ACK
}
return data;
}
// ============================================================================
// 3. EEPROM HIGH-LEVEL FUNCTIONS
// ============================================================================
// Writes a single byte to a specific memory address
// Returns: 0 Success, 1 Fail
uint8_t EEPROM_WriteByte(uint16_t mem_addr, uint8_t data) {
I2C_Start();
// 1. Send Device Address + Write Bit
if (I2C_WriteByte(EEPROM_ADDR_W)) {
I2C_Stop();
return 1; // Error: No ACK
}
// 2. Send Memory Address
// Note: Some EEPROMs use 16-bit addresses, some 8-bit.
// Here we assume 16-bit (2 bytes) for chips like 24C32/64/256
if (I2C_WriteByte((mem_addr >> 8) & 0xFF)) { // High byte
I2C_Stop();
return 1;
}
if (I2C_WriteByte(mem_addr & 0xFF)) { // Low byte
I2C_Stop();
return 1;
}
// 3. Send Data
if (I2C_WriteByte(data)) {
I2C_Stop();
return 1;
}
I2C_Stop();
// 4. Write Cycle Delay
// EEPROMs need time (typically 5ms) to internally burn the data.
// A robust implementation uses "Ack Polling" here.
// For simplicity, we just delay.
delay_us(5000);
return 0; // Success
}
// Reads a single byte from a specific memory address
uint8_t EEPROM_ReadByte(uint16_t mem_addr, uint8_t *data_out) {
I2C_Start();
// 1. Set Memory Pointer (Dummy Write)
if (I2C_WriteByte(EEPROM_ADDR_W)) {
I2C_Stop();
return 1;
}
if (I2C_WriteByte((mem_addr >> 8) & 0xFF)) {
I2C_Stop();
return 1;
}
if (I2C_WriteByte(mem_addr & 0xFF)) {
I2C_Stop();
return 1;
}
// 2. Send Repeated Start
I2C_Start();
// 3. Send Device Address + Read Bit
if (I2C_WriteByte(EEPROM_ADDR_R)) {
I2C_Stop();
return 1;
}
// 4. Read Data with NACK (indicating end of transmission)
*data_out = I2C_ReadByte(1);
I2C_Stop();
return 0;
}
// ============================================================================
// 4. USAGE EXAMPLE
// ============================================================================
/*
int main(void) {
uint8_t read_val;
// Initialize your hardware GPIOs here
I2C_GPIO_Init();
// Write value 0xAB to address 0x0010
if(EEPROM_WriteByte(0x0010, 0xAB) == 0) {
// Success
}
// Read value back from address 0x0010
if(EEPROM_ReadByte(0x0010, &read_val) == 0) {
// Success, check read_val
if(read_val == 0xAB) {
// Verified
}
}
while(1);
}
*/
Key Implementation Details
- SDA Direction Switching: I2C is half-duplex. The SDA line changes direction constantly.
- When writing bits, SDA is an Output.
- When waiting for an ACK (the 9th clock pulse) or reading data, the Master must release the line. This means setting SDA to Input (High-Z) and relying on the pull-up resistor to keep it high (unless the slave pulls it low).
- Delays: The
delay_us function defines your bus speed.
SCL_set(HIGH); delay_us(5); SCL_set(LOW);
- 5 microseconds high + 5 microseconds low = 10 microseconds period = 100kHz.
- Addressing:
- Most 24Cxx chips use an 8-bit address format
1010 A1 A0 R/W.
- If you are using a chip larger than 256 bytes (e.g., 24C32), the memory address requires 2 bytes (16-bits) as shown in the code. If you are using a smaller 24C02 (256 bytes), you only need to send 1 byte for the memory address.
- Write Cycle Polling: The
EEPROM_WriteByte function includes a fixed 5ms delay. In production code, it is better to use "Ack Polling": you keep sending START + DeviceAddr+W until the EEPROM returns an ACK (meaning it finished writing).