1 /*
2 * Copyright (c) 2025 Microchip Technology Inc.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/ztest.h>
8 #include <zephyr/drivers/i2c.h>
9
10 #define EEPROM_NODE DT_NODELABEL(eeprom0)
11 #define EEPROM_I2C_ADDR DT_REG_ADDR(EEPROM_NODE)
12 #define I2C_NODE DT_PARENT(EEPROM_NODE)
13 #define TEST_DATA_LEN 8
14
15 static const struct device *i2c_dev = DEVICE_DT_GET(I2C_NODE);
16 static uint8_t write_data[TEST_DATA_LEN] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80};
17 static uint8_t read_data[TEST_DATA_LEN];
18
19 /* Callback function for I2C operations */
i2c_async_callback(const struct device * dev,int status,void * user_data)20 static void i2c_async_callback(const struct device *dev, int status, void *user_data)
21 {
22 if (status == 0) {
23 printk("I2C operation completed successfully\n");
24 } else {
25 printk("I2C operation failed with error: %d\n", status);
26 }
27
28 /* Signal completion if needed */
29 struct k_sem *sem = (struct k_sem *)user_data;
30
31 k_sem_give(sem);
32 }
33
34 /* write data to EEPROM */
35 uint8_t eeprom_addr = 1;
36
37 struct i2c_msg tx_msg[2] = {{.buf = &eeprom_addr, .len = 1, .flags = I2C_MSG_WRITE},
38 {.buf = write_data, .len = sizeof(write_data), .flags = I2C_MSG_WRITE}};
39
40 /* Read data back from the EEPROM */
41 struct i2c_msg rx_msg[2] = {{.buf = &eeprom_addr, .len = 1, .flags = I2C_MSG_WRITE},
42 {.buf = read_data, .len = sizeof(read_data), .flags = I2C_MSG_READ}};
43
ZTEST(i2c_async,test_eeprom_async)44 ZTEST(i2c_async, test_eeprom_async)
45 {
46 /* Semaphore for signaling completion */
47 static struct k_sem async_sem;
48
49 k_sem_init(&async_sem, 0, 1);
50 k_timeout_t timeout = K_MSEC(500);
51
52 int ret = i2c_transfer_cb(i2c_dev, tx_msg, 2, EEPROM_I2C_ADDR, i2c_async_callback,
53 &async_sem);
54 zassert_equal(ret, 0, "EEPROM write failed: %d", ret);
55
56 /* Wait for transfer to complete */
57 k_sem_take(&async_sem, timeout);
58
59 ret = i2c_transfer_cb(i2c_dev, rx_msg, 2, EEPROM_I2C_ADDR, i2c_async_callback, &async_sem);
60 zassert_equal(ret, 0, "EEPROM read failed: %d", ret);
61
62 /* Wait for transfer to complete */
63 k_sem_take(&async_sem, timeout);
64
65 for (int i = 0; i < TEST_DATA_LEN; i++) {
66 zassert_equal(read_data[i], write_data[i],
67 "Data mismatch at index %d: expected 0x%02X, got 0x%02X", i,
68 write_data[i], read_data[i]);
69 }
70 }
71
72 /* Test Setup */
i2c_test_setup(void)73 void *i2c_test_setup(void)
74 {
75 zassert_true(device_is_ready(i2c_dev), "I2C device is not ready");
76 return NULL;
77 }
78
79 ZTEST_SUITE(i2c_async, NULL, i2c_test_setup, NULL, NULL, NULL);
80