Verilog Code for I2C Protocol
An I2C (Inter-Integrated Circuit) controller module implemented in Verilog for facilitating communication between a master device and slave devices using the I2C protocol. This project is designed to handle basic I2C operations, such as sending a slave address, transmitting data, and receiving acknowledgment.
- Slave Address Transmission: Transmits a 7-bit slave address to initiate communication.
- Acknowledgment Handling: Detects acknowledgment (ACK) or no-acknowledgment (NACK) signals from the slave device.
- Clock Generation: Includes an SCL clock generator with configurable frequency.
- Data Transmission: Supports writing an 8-bit data word to the slave device.
- Customizable Parameters: Configurable slave address and data.
The Verilog module consists of the following components:
- Clock Divider: Generates the SCL signal from the input clock.
- State Machine: Controls the flow of operations based on the I2C protocol.
- SDA Control: Manages the bidirectional data line (SDA) based on the current state.
- Acknowledgment Management: Detects and handles ACK or NACK signals.
The controller operates using a finite state machine (FSM) with the following states:
- IDLE: Initial state where the controller waits for a start condition.
- START: Generates a start condition on the SDA line.
- SEND_SLAVE_ADDR: Transmits the 7-bit slave address.
- ACK_WAIT: Waits for an acknowledgment signal from the slave.
- SEND_RW_BIT: Sends the read/write bit.
- SEND_DATA: Transmits the 8-bit data to the slave.
- DATA_ACK_WAIT: Waits for acknowledgment after data transmission.
- STOP: Generates a stop condition on the SDA line.
- DONE: Returns to the IDLE state after completing the operation.
- SCL: Clock signal generated by the controller.
- SDA: Bidirectional data line.
- ack_ready: Ensures acknowledgment handling begins after the slave address is fully transmitted.
SLAVE_ADDR
: Specify the 7-bit address of the slave device (default:7'h13
).DATA
: Specify the 8-bit data to be written (default:8'b10001000
).
clk
: Input clock signal (e.g., 100 kHz).rst
: Reset signal to initialize the controller.
scl
: Clock line for the I2C communication.
sda
: Data line for the I2C communication.
Run a testbench to simulate the behavior of the I2C controller. Ensure the following:
- The
SDA
line transmits the correct slave address. - The acknowledgment is detected accurately.
- The
STOP
condition is generated after the transaction. - Make sure to run the simulation for at least 5us.
SCL: 1, State: 0, SDA: 1
SCL: 0, State: 0, SDA: 1
SCL: 1, State: 1, SDA: 0
SCL: 0, State: 1, SDA: 0
SCL: 1, State: 2, SDA: 0
SCL: 0, State: 2, SDA: 0
SCL: 1, State: 2, SDA: 1
ACK_WAIT: Time=1815000ns, SCL=1, SDA=1, ACK_Received=0
SCL: 1, State: 3, SDA: 1
SCL: 0, State: 3, SDA: 0