0
0
Embedded Cprogramming~5 mins

I2C acknowledge and NACK behavior in Embedded C

Choose your learning style9 modes available
Introduction

I2C acknowledge (ACK) and not acknowledge (NACK) signals help devices talk clearly. They tell the sender if the receiver got the data or not.

When checking if a device on the I2C bus is ready to communicate.
When sending data bytes and confirming the receiver accepted them.
When ending communication to signal no more data will be sent.
When debugging communication problems between microcontrollers and sensors.
Syntax
Embedded C
void I2C_SendAck(void);
void I2C_SendNack(void);

ACK means the receiver says 'I got your data'.

NACK means the receiver says 'I did not get your data' or 'stop sending'.

Examples
This tells the sender to continue sending data.
Embedded C
I2C_SendAck(); // Send ACK after receiving a byte
This tells the sender to stop sending data.
Embedded C
I2C_SendNack(); // Send NACK after last byte
Sample Program

This program simulates receiving three bytes over I2C. It sends ACK after the first two bytes to say 'keep sending'. After the last byte, it sends NACK to say 'stop'.

Embedded C
#include <stdio.h>

// Simulated functions for ACK and NACK
void I2C_SendAck(void) {
    printf("ACK sent\n");
}

void I2C_SendNack(void) {
    printf("NACK sent\n");
}

int main() {
    // Simulate receiving 3 bytes
    for (int i = 0; i < 2; i++) {
        printf("Byte %d received\n", i+1);
        I2C_SendAck(); // Acknowledge each byte except last
    }
    printf("Byte 3 received\n");
    I2C_SendNack(); // NACK after last byte to stop
    return 0;
}
OutputSuccess
Important Notes

Always send ACK after receiving data if you want more data.

Send NACK to signal the end of data or if an error occurs.

Missing ACK or NACK can cause the I2C bus to hang or misbehave.

Summary

ACK means 'I received your data, send more.'

NACK means 'Stop sending, I am done or there is a problem.'

Use ACK and NACK to control smooth communication on the I2C bus.