zephyr_zcu102_iicps_samples_drivers_eeprom.c

 1/*
 2 * Copyright (c) 2021 Thomas Stranger
 3 *
 4 * SPDX-License-Identifier: Apache-2.0
 5 */
 6
 7#include <zephyr/kernel.h>
 8#include <zephyr/sys/printk.h>
 9#include <zephyr/drivers/eeprom.h>
10#include <zephyr/device.h>
11#include <zephyr/drivers/i2c.h>
12
13/* I2C Mux - nxp,pca9548 */
14#define MUX_SLAVE_ADDR	    0x74U
15#define EEPROM_CHANNEL_NO   0x01U
16
17#define EEPROM_SAMPLE_OFFSET 0
18#define EEPROM_SAMPLE_MAGIC  0xEE9703
19
20struct perisistant_values {
21	uint32_t magic;
22	uint32_t boot_count;
23};
24
25/*
26 * Get a device structure from a devicetree node with alias eeprom-0
27 */
28static const struct device *get_eeprom_device(void)
29{
30	const struct i2c_dt_spec i2c = I2C_DT_SPEC_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(vnd_i2c_mux));
31	const struct device *const dev = DEVICE_DT_GET(DT_ALIAS(eeprom_0));
32	int32_t ret;
33	uint8_t datas[3];
34
35	datas[0] = EEPROM_CHANNEL_NO;
36	ret = i2c_write(i2c.bus, datas, 1, MUX_SLAVE_ADDR);
37	if(ret != 0) {
38		printk("Failed to select mux channel connected to pca9548\n");
39		return NULL;
40	}
41
42	if (!device_is_ready(dev)) {
43		printk("\nError: Device \"%s\" is not ready; "
44		       "check the driver initialization logs for errors.\n",
45		       dev->name);
46		return NULL;
47	}
48
49	printk("Found EEPROM device \"%s\"\n", dev->name);
50	return dev;
51}
52
53int main(void)
54{
55	const struct device *eeprom = get_eeprom_device();
56	size_t eeprom_size;
57	struct perisistant_values values;
58	int rc;
59
60	if (eeprom == NULL) {
61		return 0;
62	}
63
64	eeprom_size = eeprom_get_size(eeprom);
65	printk("Using eeprom with size of: %zu.\n", eeprom_size);
66
67	rc = eeprom_read(eeprom, EEPROM_SAMPLE_OFFSET, &values, sizeof(values));
68	if (rc < 0) {
69		printk("Error: Couldn't read eeprom: err: %d.\n", rc);
70		return 0;
71	}
72
73	if (values.magic != EEPROM_SAMPLE_MAGIC) {
74		values.magic = EEPROM_SAMPLE_MAGIC;
75		values.boot_count = 0;
76	}
77
78	values.boot_count++;
79	printk("Device booted %d times.\n", values.boot_count);
80
81	rc = eeprom_write(eeprom, EEPROM_SAMPLE_OFFSET, &values, sizeof(values));
82	if (rc < 0) {
83		printk("Error: Couldn't write eeprom: err:%d.\n", rc);
84		return 0;
85	}
86
87	printk("Reset the MCU to see the increasing boot counter.\n\n");
88	return 0;
89}