oled 1.0
OLED Graphics Control Library
Loading...
Searching...
No Matches
twi.h File Reference

Header file with declarations and macros for hardware TWI/I2C. More...

Include dependency graph for twi.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define F_CPU   12000000UL
 System clock frequency definition.
#define F_TWI   100000UL
 TWI clock frequency definition.
#define TWI_PRESCALER   0
 TWI clock prescaler setting.
#define TWI_BITRATE   ((F_CPU/F_TWI) - 16UL) / (2 * (1<<TWI_PRESCALER) * (1<<TWI_PRESCALER))
 Calculation of the TWI bus clock bitrate value.
#define TWI_ADDRESS   0x42
 Slave address of the TWI controller.
#define TWI_BROADCAST   0x00
 Enable or disable listening to general call addresses on the TWI bus.
#define TWI_STATUS_START   0x08
 Status code indicating START condition has been transmitted.
#define TWI_STATUS_REPEATED_START   0x10
 Status code indicating a repeated START condition has been transmitted.
#define TWI_STATUS_ADDRESS_WRITE_NACK   0x18
 Status code indicating SLA+W has been transmitted and NOT acknowledged.
#define TWI_STATUS_ADDRESS_WRITE_ACK   0x20
 Status code indicating SLA+W has been transmitted and acknowledged.
#define TWI_STATUS_DATA_WRITE_NACK   0x28
 Status code indicating data byte has been transmitted and NOT acknowledged.
#define TWI_STATUS_DATA_WRITE_ACK   0x30
 Status code indicating data byte has been transmitted and acknowledged.
#define TWI_STATUS_ARBITRATION_LOST   0x38
 Status code indicating arbitration has been lost in SLA+W or data bytes.
#define TWI_STATUS_ADDRESS_READ_ACK   0x40
 Status code indicating SLA+R has been transmitted and acknowledged.
#define TWI_STATUS_ADDRESS_READ_NACK   0x48
 Status code indicating SLA+R has been transmitted and NOT acknowledged.
#define TWI_STATUS_DATA_READ_ACK   0x50
 Status code indicating data byte has been received and acknowledged.
#define TWI_STATUS_DATA_READ_NACK   0x58
 Status code indicating data byte has been received and NOT acknowledged.

Functions

unsigned char twi_init (void)
 Initialize the TWI (I2C) hardware interface in master mode.
void twi_disable (void)
 Disable the TWI (I2C) interface.
unsigned char twi_status (void)
 Retrieves the current TWI status byte.
TWI_Error twi_start (void)
 Initiates a TWI (I2C) (repeated) start condition on the bus.
void twi_stop (void)
 Stop the TWI (I2C) transmission by generating a stop condition.
TWI_Error twi_address (unsigned char address, TWI_Operation operation)
 Send a TWI (I2C) slave address combined with the read/write operation bit.
TWI_Error twi_set (unsigned char data)
 Transmit a data byte over the TWI (I2C) bus.
TWI_Error twi_get (unsigned char *data, TWI_Acknowledge acknowledge)
 Receive a data byte from the TWI (I2C) bus.

Detailed Description

Header file with declarations and macros for hardware TWI/I2C.

This file provides function prototypes, type definitions, and constants for hardware-based TWI (I2C) communication on AVR microcontrollers.

Author
g.raf
Date
2025-09-01
Version
1.0 Release
Note
This file is part of a larger project and subject to the license specified in the repository. For updates and the complete revision history, see the GitHub repository.
See also
https://github.com/0x007e/avr "AVR ATmega GitHub Repository"

Macro Definition Documentation

◆ F_CPU

#define F_CPU   12000000UL

System clock frequency definition.

This macro defines the operating frequency of the microcontroller's clock in Hertz. It is used by delay functions and timing calculations. The value should match the actual hardware clock frequency to ensure correct timing behavior in the software.

◆ F_TWI

#define F_TWI   100000UL

TWI clock frequency definition.

This macro defines the clock frequency used by the TWI (I2C) bus in Hertz. It sets the speed at which the hardware generates clock pulses for data transfer. Modifying this value affects timing and the overall bus speed.

◆ TWI_ADDRESS

#define TWI_ADDRESS   0x42

Slave address of the TWI controller.

This macro defines the 7-bit address of the TWI (I2C) controller when operating as a slave device on the bus. The address is used by other devices (masters) to communicate with this slave.

Attention
it must be unique on the bus to avoid address conflicts.

◆ TWI_BITRATE

#define TWI_BITRATE   ((F_CPU/F_TWI) - 16UL) / (2 * (1<<TWI_PRESCALER) * (1<<TWI_PRESCALER))

Calculation of the TWI bus clock bitrate value.

This macro calculates the value for the TWI bitrate register used to set the clock frequency on the TWI bus. The calculation is based on the CPU clock frequency (F_CPU), the desired TWI clock frequency (F_TWI), and the prescaler value (TWI_PRESCALER).

Attention
This value defines the timing for clock pulses for the hardware TWI bus to achieve the target bus speed.

◆ TWI_BROADCAST

#define TWI_BROADCAST   0x00

Enable or disable listening to general call addresses on the TWI bus.

This macro configures whether the TWI controller, when acting as a slave, responds to general call addresses.

Setting this to 1 enables the controller to listen and respond to general call messages (address 0x00). Setting to 0 disables general call response, so the controller only reacts to its specific slave address.

◆ TWI_PRESCALER

#define TWI_PRESCALER   0

TWI clock prescaler setting.

This macro defines the prescaler value for the TWI hardware clock. It sets the division factor applied to the TWI clock frequency (F_TWI) by configuring the prescaler bits (TWPS) in the TWSR register.

Note
Valid prescaler values are 0, 1, 2, and 3, representing division factors of 1, 4, 16, and 64 respectively.
Attention
Adjusting this value changes the effective SCL clock speed on the TWI bus by scaling down the base clock frequency.

Function Documentation

◆ twi_address()

TWI_Error twi_address ( unsigned char address,
TWI_Operation operation )
inline

Send a TWI (I2C) slave address combined with the read/write operation bit.

Parameters
address7-bit slave address to be transmitted.
operationSpecifies the operation type: 0 for write, 1 for read.
Returns
Returns the status code from the twi_set function indicating the result of address transmission:
  • TWI_None if the address was acknowledged by the slave.
  • TWI_Ack if an acknowledgement error (NACK) occurred.
  • TWI_Arbitration if arbitration was lost in multi-master mode.
  • TWI_General if a general error occurred.

This inline function constructs the address byte by shifting the 7-bit slave address left by one and combining it with the least significant bit representing the operation (read/write). It then calls twi_set to transmit this address byte over the TWI bus and returns the transmission status.

Note
The function relies on twi_set for the actual data transmission and error checking.
Parameters
address7-bit slave address to be transmitted.
operationSpecifies the operation type: 0 for write, 1 for read.
Returns
Returns the status code from the twi_set function indicating the result of address transmission:
  • TWI_None if the address was acknowledged by the slave.
  • TWI_Ack if an acknowledgement error (NACK) occurred.
  • TWI_Arbitration if arbitration was lost in multi-master mode.
  • TWI_General if a general error occurred.

This inline function constructs the address byte by shifting the 7-bit slave address left by one and combining it with the least significant bit representing the operation (read/write). It then calls twi_set to transmit this address byte over the TWI bus and returns the transmission status.

◆ twi_disable()

void twi_disable ( void )
inline

Disable the TWI (I2C) interface.

This function disables the hardware TWI module. This effectively releases control of the TWI lines and sets the pins to reset state. Use this function to safely deactivate the TWI bus when it is no longer needed.

This inline function disables the hardware TWI module. This effectively releases control of the TWI lines and sets the pins to reset state. Use this function to safely deactivate the TWI bus when it is no longer needed.

◆ twi_get()

TWI_Error twi_get ( unsigned char * data,
TWI_Acknowledge acknowledge )

Receive a data byte from the TWI (I2C) bus.

Parameters
dataPointer to a variable where the received data byte will be stored.
acknowledgeSpecifies whether the master should send an ACK or NACK after receiving the byte:
  • TWI_ACK to acknowledge receipt and request more data.
  • TWI_NACK to signal no more data is requested.
Returns
Returns one of the following status codes:
  • TWI_None: Data was successfully received and the expected ACK/NACK was sent.
  • TWI_Ack: Wrong or unexpected ACK/NACK parameter or status received.
  • TWI_Arbitration: Arbitration was lost in multi-master mode.

This function configures the TWI hardware to receive a byte from the bus and decides whether to send an ACK or NACK based on the acknowledge parameter.

Note
The function waits until the reception is complete by polling the TWINT flag. The received data is then read from the TWDR register and stored at the provided pointer.

The function checks the TWI status register (TWSR) for arbitration loss or to verify that the appropriate ACK/NACK status was received. If the received status matches the expected acknowledge mode, it returns success; otherwise, it indicates an acknowledgment error.

Parameters
dataPointer to a variable where the received data byte will be stored.
acknowledgeSpecifies whether the master should send an ACK or NACK after receiving the byte:
  • TWI_ACK to acknowledge receipt and request more data.
  • TWI_NACK to signal no more data is requested.
Returns
Returns one of the following status codes:
  • TWI_None: Data was successfully received and the expected ACK/NACK was sent.
  • TWI_Ack: Wrong or unexpected ACK/NACK parameter or status received.
  • TWI_Arbitration: Arbitration was lost in multi-master mode.
  • TWI_General: A general error occurred during transmission.

This function configures the TWI hardware to receive a byte from the bus and decides whether to send an ACK or NACK based on the acknowledge parameter.

Note
The function waits until the reception is complete by polling the TWI status function for completion. The received data is then read from the MDATA register and stored at the provided pointer.

Depending on the acknowledge mode, the function sets the MCTRLB register to either send an ACK and prepare for more data reception or send a NACK and stop the communication.

Finally, the function returns the status code from the reception process.

◆ twi_init()

unsigned char twi_init ( void )

Initialize the TWI (I2C) hardware interface in master mode.

Returns
Returns the current TWI status byte after initialization.

This function configures the TWI hardware registers to initialize the bus in master mode.

In master mode, it sets the bitrate and prescaler according to predefined macros.

Note
If TWI interrupt processing is enabled (TWI_TWIE), interrupts are activated.

The function returns the initial TWI status for further status checking after initialization.

Returns
Returns the current TWI status byte after initialization.

This function configures the TWI hardware registers to initialize the bus exclusively in master mode.

It sets the bitrate and activates the TWI controller using the predefined macros.

Note
If interrupt processing is enabled (TWI_TWIE), relevant interrupts are configured.

The function returns the initial TWI status for further status checking after initialization.

◆ twi_set()

TWI_Error twi_set ( unsigned char data)

Transmit a data byte over the TWI (I2C) bus.

Parameters
dataThe data byte to be transmitted to the bus.
Returns
Returns one of the following status codes:
  • TWI_None: Data was transmitted successfully and acknowledged by the slave.
  • TWI_Ack: Acknowledgement error occurred (NACK received).
  • TWI_Arbitration: Arbitration lost in multi-master mode.
  • TWI_General: A general error occurred during transmission.

This function writes the provided data byte into the TWI data register and triggers the transmission by setting the TWINT and TWEN bits in the control register.

Note
The function waits for the transmission to complete by polling the TWINT flag.

After transmission, the function reads the TWI status register (TWSR) to determine the outcome of the transmission and returns the corresponding status code.

Parameters
dataThe data byte to be transmitted to the bus.
Returns
Returns one of the following status codes:
  • TWI_None: Data was transmitted successfully and acknowledged by the slave.
  • TWI_Ack: Acknowledgement error occurred (NACK received).
  • TWI_Arbitration: Arbitration lost in multi-master mode.
  • TWI_General: A general error occurred during transmission.

This function writes the provided data byte into the TWI data register. It then waits for the transmission to complete by repeatedly checking the TWI status.

The function returns the final TWI status code indicating the result of the transmission.

◆ twi_start()

TWI_Error twi_start ( void )
inline

Initiates a TWI (I2C) (repeated) start condition on the bus.

Returns
Returns TWI_None if the start condition was successfully transmitted (including repeated start), or TWI_Start if the start condition failed.

This function triggers the TWI hardware to send a START condition on the bus, signaling the beginning of a new communication frame. It sets the necessary control bits in the TWCR register to initiate the start and enables the TWI interface.

Note
The function then waits for the TWINT flag to indicate completion of the start condition transmission.

After completion, the function checks the TWI status register (TWSR) to verify if the start or repeated start condition was acknowledged by the bus. If successful, it returns TWI_None; otherwise, it returns TWI_Start indicating failure to send the (repeated) start condition.

Deprecated
This function is obsolete on newer AVR microcontrollers and is retained only for backward compatibility.

It does not perform any operation.

Returns
Always returns TWI_None as the function is effectively a no-op.

On modern AVR hardware, start conditions are managed internally by the TWI module, so this function is no longer necessary and does not initiate any bus activity.

◆ twi_status()

unsigned char twi_status ( void )
inline

Retrieves the current TWI status byte.

Reads and returns the TWI status byte from the TWSR register, including the write collision flag.

  • Bits 7 to 3 (masked with 0xF8) contain the TWI status code which indicates the current state of the TWI hardware (see TWI_STATUS_* defines).
  • Bit 2 indicates a write collision error.
Returns
A byte where:
  • Bits [7:3] represent the TWI status code.
  • Bit [2] indicates a write collision (1 if collision occurred, 0 otherwise).

◆ twi_stop()

void twi_stop ( void )

Stop the TWI (I2C) transmission by generating a stop condition.

This function initiates the TWI stop condition on the bus, signaling the end of the current communication frame. It sets the appropriate bits in the TWCR register to transmit the stop signal and keeps the TWI hardware enabled.

Note
The function waits until the stop condition has been executed by checking the TWSTO bit in the control register. After this, the bus returns to the idle state, ready for the next communication cycle.

This function initiates the TWI stop condition on the bus, signaling the end of the current communication frame. It sets the appropriate bits in the MCTRLB register to transmit the stop signal.

Note
The function waits until the stop condition has been executed by checking the BUSSTATE bits in the MSTATUS register. After this, the bus returns to the idle state, ready for the next communication cycle.