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 
12 #define EEPROM_SAMPLE_OFFSET 0
13 #define EEPROM_SAMPLE_MAGIC  0xEE9703
14 
15 struct perisistant_values {
16 	uint32_t magic;
17 	uint32_t boot_count;
18 };
19 
20 /*
21  * Get a device structure from a devicetree node with alias eeprom-0
22  */
get_eeprom_device(void)23 static const struct device *get_eeprom_device(void)
24 {
25 	const struct device *const dev = DEVICE_DT_GET(DT_ALIAS(eeprom_0));
26 
27 	if (!device_is_ready(dev)) {
28 		printk("\nError: Device \"%s\" is not ready; "
29 		       "check the driver initialization logs for errors.\n",
30 		       dev->name);
31 		return NULL;
32 	}
33 
34 	printk("Found EEPROM device \"%s\"\n", dev->name);
35 	return dev;
36 }
37 
main(void)38 int main(void)
39 {
40 	const struct device *eeprom = get_eeprom_device();
41 	size_t eeprom_size;
42 	struct perisistant_values values;
43 	int rc;
44 
45 	if (eeprom == NULL) {
46 		return 0;
47 	}
48 
49 	eeprom_size = eeprom_get_size(eeprom);
50 	printk("Using eeprom with size of: %zu.\n", eeprom_size);
51 
52 	rc = eeprom_read(eeprom, EEPROM_SAMPLE_OFFSET, &values, sizeof(values));
53 	if (rc < 0) {
54 		printk("Error: Couldn't read eeprom: err: %d.\n", rc);
55 		return 0;
56 	}
57 
58 	if (values.magic != EEPROM_SAMPLE_MAGIC) {
59 		values.magic = EEPROM_SAMPLE_MAGIC;
60 		values.boot_count = 0;
61 	}
62 
63 	values.boot_count++;
64 	printk("Device booted %d times.\n", values.boot_count);
65 
66 	rc = eeprom_write(eeprom, EEPROM_SAMPLE_OFFSET, &values, sizeof(values));
67 	if (rc < 0) {
68 		printk("Error: Couldn't write eeprom: err:%d.\n", rc);
69 		return 0;
70 	}
71 
72 	printk("Reset the MCU to see the increasing boot counter.\n\n");
73 	return 0;
74 }
75