Comprehending the Objective
I'm focused on grasping the user's need for C code to manage an external EEPROM via bit-banging I2C. The goal is clear: create code for this specific interface method. Right now, I'm defining the necessary components and how they will interact within the code.
Outlining the Structure
Now I'm designing the code structure, breaking it into modular functions. These functions will handle the low-level I2C operations, like generating start and stop conditions, writing and reading individual bits, and managing acknowledgements. I'll focus on making these functions as generic as possible to accommodate various microcontrollers. Then I will write the high-level functions, like writing a byte to the EEPROM.
Detailing the Mechanics
My focus is shifting to the implementation details, like creating the specific functions for I2C communication. I am working on the essential primitives: start, stop, write bit, read bit, and ACK/NACK. Considering the timing requirements, I'll need to incorporate a generic delay function for compatibility across different microcontrollers.
Refining the Functions
Now, I'm concentrating on the low-level functions that will form the core of the I2C communication. I am working on i2c_write_bit and i2c_read_bit, ensuring their timing aligns with I2C specifications for correct signal transmission. Following that, I'll integrate ACK/NACK handling to confirm data transmission success.
Formulating the Core Logic
\n\n
My current focus is on translating the conceptual logic into actual C code. I am in the midst of designing the i2c_write function, incorporating ACK/NACK verification to ensure data transmission. Following this, I will move on to the eeprom_write_byte and eeprom_read_byte functions, taking into account the EEPROM's specific requirements, such as internal write times and the proper use of repeated start conditions.
Developing the Core Functions
\n\n
I'm now implementing the i2c_write function, along with i2c_read, after which the focus will move toward the EEPROM-specific functionality. I am paying close attention to data bit transfer, and ack handling for reliability. The goal is to ensure the core I2C functions are as precise and efficient as possible, to guarantee correct EEPROM operation. The design is now focused on handling the EEPROM write cycle and incorporating repeated start conditions for seamless data transfers.
Formalizing the Implementation
\n\n
Now I'm focusing on the final touches, like organizing the code into a clear structure and adding detailed comments. I will create a header file that encapsulates the platform-specific pin definitions and placeholder delay functions. Also, I am focusing on making the code easy to adapt to various microcontrollers by clearly marking the areas needing user configuration and ensuring that the I2C functions are well-commented and explain the required timing considerations. I will include a 'main' function to demonstrate how the functions are to be used, and this will involve both reading and writing to the EEPROM.
Here is a complete, portable C implementation for bit-banging I2C to interface with a standard external EEPROM (like the AT24C series).
Implementation Details
1. Hardware Requirements (Open Drain):
I2C lines (SDA and SCL) are Open Drain.
- To send a 0: The microcontroller drives the pin LOW.
- To send a 1: The microcontroller releases the pin (sets it to Input mode), allowing external pull-up resistors (usually 4.7kΩ) to pull the line HIGH.
- Note: In the code below, you must map the macros to your specific microcontroller's GPIO register operations.
2. The Code Structure:
- Hardware Abstraction Layer: Macros to control pins.
- I2C Primitives: Start, Stop, Write Byte, Read Byte.
- EEPROM Functions: High-level read/write logic.
The C Code
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
// =========================================================
// 1. HARDWARE ABSTRACTION LAYER (Platform Dependent)
// =========================================================
// Replace these mocks with your actual MCU calls (e.g., HAL_GPIO_WritePin, PORTB |= ...)
#define SDA_PIN_NUM 1
#define SCL_PIN_NUM 2
// Delay function: Adjust "10" to achieve ~100kHz (Standard Mode) or ~400kHz
void i2c_delay(void) {
volatile int i = 0;
for (i = 0; i < 100; i++) { __asm("nop"); }
}
// Set SDA Line to specific state
void SDA_WRITE(bool state) {
if (state) {
// Set Pin Direction to INPUT (High-Z) -> Pull-up takes it High
// Example: GPIO_SetDir(SDA_PIN_NUM, INPUT);
} else {
// Set Pin to LOW and Direction to OUTPUT
// Example: GPIO_SetLow(SDA_PIN_NUM); GPIO_SetDir(SDA_PIN_NUM, OUTPUT);
}
}
// Read SDA Line status
bool SDA_READ(void) {
// Set Pin Direction to INPUT
// Return 1 if High, 0 if Low
// Example: return GPIO_Read(SDA_PIN_NUM);
return 1; // Placeholder
}
// Set SCL Line to specific state
void SCL_WRITE(bool state) {
if (state) {
// Set Pin Direction to INPUT (High-Z) or Drive High
// Example: GPIO_SetDir(SCL_PIN_NUM, INPUT);
} else {
// Set Pin to LOW and Direction to OUTPUT
// Example: GPIO_SetLow(SCL_PIN_NUM); GPIO_SetDir(SCL_PIN_NUM, OUTPUT);
}
}
// =========================================================
// 2. I2C BIT-BANGING PRIMITIVES
// =========================================================
void i2c_init(void) {
SDA_WRITE(1);
SCL_WRITE(1);
}
void i2c_start(void) {
SDA_WRITE(1);
SCL_WRITE(1);
i2c_delay();
SDA_WRITE(0); // Start: SDA goes Low while SCL is High
i2c_delay();
SCL_WRITE(0); // Clamp SCL low to prepare for data
}
void i2c_stop(void) {
SDA_WRITE(0);
i2c_delay();
SCL_WRITE(1);
i2c_delay();
SDA_WRITE(1); // Stop: SDA goes High while SCL is High
i2c_delay();
}
// Returns true if slave ACKed, false if NACK
bool i2c_write_byte(uint8_t data) {
uint8_t i;
// Write 8 bits (MSB first)
for (i = 0; i < 8; i++) {
if ((data & 0x80) != 0) {
SDA_WRITE(1);
} else {
SDA_WRITE(0);
}
data <<= 1;
i2c_delay();
SCL_WRITE(1); // Pulse Clock
i2c_delay();
SCL_WRITE(0);
}
// ACK Phase
SDA_WRITE(1); // Release SDA so slave can control it
i2c_delay();
SCL_WRITE(1); // Clock High
i2c_delay();
bool ack = !SDA_READ(); // Slave pulls Low for ACK
SCL_WRITE(0); // Clock Low
return ack;
}
uint8_t i2c_read_byte(bool send_ack) {
uint8_t i;
uint8_t data = 0;
SDA_WRITE(1); // Ensure line is released (Input mode)
// Read 8 bits
for (i = 0; i < 8; i++) {
data <<= 1;
// Pulse Clock
SCL_WRITE(1);
i2c_delay();
if (SDA_READ()) {
data |= 0x01;
}
SCL_WRITE(0);
i2c_delay();
}
// Send ACK or NACK
if (send_ack) {
SDA_WRITE(0); // ACK (Low)
} else {
SDA_WRITE(1); // NACK (High)
}
i2c_delay();
SCL_WRITE(1);
i2c_delay();
SCL_WRITE(0);
SDA_WRITE(1); // Release bus
return data;
}
// =========================================================
// 3. EEPROM DRIVER (e.g., AT24C256)
// =========================================================
#define EEPROM_ADDR 0xA0 // 7-bit address 0x50 shifted left + Write bit (0)
// Write a single byte to specific memory address
bool eeprom_write_byte(uint16_t mem_addr, uint8_t data) {
i2c_start();
// 1. Send Device Address (Write mode)
if (!i2c_write_byte(EEPROM_ADDR)) {
i2c_stop();
return false; // Error: No ACK
}
// 2. Send Memory Address High Byte
if (!i2c_write_byte((uint8_t)(mem_addr >> 8))) {
i2c_stop();
return false;
}
// 3. Send Memory Address Low Byte
if (!i2c_write_byte((uint8_t)(mem_addr & 0xFF))) {
i2c_stop();
return false;
}
// 4. Send Data
if (!i2c_write_byte(data)) {
i2c_stop();
return false;
}
i2c_stop();
// IMPORTANT: EEPROM Self-Timed Write Cycle
// EEPROMs need 5ms - 10ms to physically write data.
// You should use a delay here or polling logic (ACK polling).
for(volatile int k=0; k<50000; k++); // Simple ~5ms delay placeholder
return true;
}
// Read a single byte from specific memory address
uint8_t eeprom_read_byte(uint16_t mem_addr) {
uint8_t data;
i2c_start();
// 1. Dummy Write to set address pointer
// Send Device Address (Write)
if (!i2c_write_byte(EEPROM_ADDR)) {
i2c_stop();
return 0xFF; // Error
}
// Send Memory Address High
i2c_write_byte((uint8_t)(mem_addr >> 8));
// Send Memory Address Low
i2c_write_byte((uint8_t)(mem_addr & 0xFF));
// 2. Repeated Start
i2c_start();
// 3. Send Device Address (Read mode: 0xA1)
if (!i2c_write_byte(EEPROM_ADDR | 0x01)) {
i2c_stop();
return 0xFF;
}
// 4. Read Byte (NACK because we only want one byte)
data = i2c_read_byte(false); // false = NACK
i2c_stop();
return data;
}
// =========================================================
// MAIN USAGE EXAMPLE
// =========================================================
int main(void) {
// Initialize GPIOs
i2c_init();
uint16_t targetAddress = 0x0015;
uint8_t dataToWrite = 0xAB;
// Write
if (eeprom_write_byte(targetAddress, dataToWrite)) {
printf("Write Success\n");
} else {
printf("Write Failed\n");
}
// Read back
uint8_t readData = eeprom_read_byte(targetAddress);
printf("Read Data at 0x%04X: 0x%02X\n", targetAddress, readData);
return 0;
}
Important Considerations
-
Timing:
The i2c_delay() function is critical.
- I2C Standard Mode is 100kHz (10µs period).
- I2C Fast Mode is 400kHz (2.5µs period).
- Ensure your delay loop creates a delay long enough for the frequency you desire. If your microcontroller is very fast (e.g., 100MHz+), a simple
for loop might be optimized away by the compiler; use a hardware timer or wrapper functions provided by your MCU SDK for microsecond delays.
-
ACK Polling (Optimization):
In eeprom_write_byte, I used a hard delay (for loop) at the end. EEPROMs are unavailable while currently writing internally. A robust implementation uses "ACK Polling":
- After sending the Stop condition, send a Start + Address (Write).
- If the EEPROM returns NACK, it is still busy writing.
- If it returns ACK, the write is finished, and you can proceed.
-
Addressing Size:
The code assumes a 16-bit memory address (common for 24C32, 24C64, 24C256, etc.).
- If you are using small EEPROMs (like 24C01 to 24C16), they typically use 8-bit addressing (or embed part of the address into the Device Address byte). You would need to remove the "Send Memory Address High Byte" section.