1 /*
2  * Copyright (c) 2021 metraTec GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file Header file for the MCP23Xxx driver.
9  */
10 
11 #ifndef ZEPHYR_DRIVERS_GPIO_GPIO_MCP23XXX_H_
12 #define ZEPHYR_DRIVERS_GPIO_GPIO_MCP23XXX_H_
13 
14 #include <zephyr/kernel.h>
15 
16 #include <zephyr/drivers/gpio.h>
17 #ifdef CONFIG_GPIO_MCP230XX
18 #include <zephyr/drivers/i2c.h>
19 #endif /* CONFIG_GPIO_MCP230XX */
20 #ifdef CONFIG_GPIO_MCP23SXX
21 #include <zephyr/drivers/spi.h>
22 #endif /* CONFIG_GPIO_MCP23SXX */
23 
24 /* Register definitions */
25 #define REG_IODIR 0x00
26 #define REG_IPOL 0x01
27 #define REG_GPINTEN 0x02
28 #define REG_DEFVAL 0x03
29 #define REG_INTCON 0x04
30 #define REG_IOCON 0x05
31 #define REG_GPPU 0x06
32 #define REG_INTF 0x07
33 #define REG_INTCAP 0x08
34 #define REG_GPIO 0x09
35 #define REG_OLAT 0x0A
36 
37 #define REG_IOCON_MIRROR BIT(6)
38 
39 #define MCP23SXX_ADDR 0x40
40 #define MCP23SXX_READBIT 0x01
41 
42 typedef int (*mcp23xxx_read_port_regs)(const struct device *dev, uint8_t reg, uint16_t *buf);
43 typedef int (*mcp23xxx_write_port_regs)(const struct device *dev, uint8_t reg, uint16_t value);
44 typedef int (*mcp23xxx_bus_is_ready)(const struct device *dev);
45 /** Configuration data */
46 struct mcp23xxx_config {
47 	/* gpio_driver_config needs to be first */
48 	struct gpio_driver_config config;
49 
50 	/** I2C device */
51 	union {
52 #ifdef CONFIG_GPIO_MCP230XX
53 		struct i2c_dt_spec i2c;
54 #endif /* CONFIG_GPIO_MCP230XX */
55 #ifdef CONFIG_GPIO_MCP23SXX
56 		struct spi_dt_spec spi;
57 #endif /* CONFIG_GPIO_MCP23SXX */
58 	} bus;
59 
60 	struct gpio_dt_spec gpio_int;
61 	struct gpio_dt_spec gpio_reset;
62 
63 	uint8_t ngpios;
64 	mcp23xxx_read_port_regs read_fn;
65 	mcp23xxx_write_port_regs write_fn;
66 	mcp23xxx_bus_is_ready bus_fn;
67 };
68 
69 /** Runtime driver data */
70 struct mcp23xxx_drv_data {
71 	/* gpio_driver_data needs to be first */
72 	struct gpio_driver_data data;
73 
74 	struct k_sem lock;
75 	sys_slist_t callbacks;
76 	const struct device *dev;
77 	struct gpio_callback int_gpio_cb;
78 	struct k_work work;
79 
80 	uint16_t rising_edge_ints;
81 	uint16_t falling_edge_ints;
82 
83 	struct {
84 		uint16_t iodir;
85 		uint16_t ipol;
86 		uint16_t gpinten;
87 		uint16_t defval;
88 		uint16_t intcon;
89 		uint16_t iocon;
90 		uint16_t gppu;
91 		uint16_t intf;
92 		uint16_t intcap;
93 		uint16_t gpio;
94 		uint16_t olat;
95 	} reg_cache;
96 };
97 
98 extern const struct gpio_driver_api gpio_mcp23xxx_api_table;
99 
100 int gpio_mcp23xxx_init(const struct device *dev);
101 
102 #endif /* ZEPHYR_DRIVERS_GPIO_GPIO_MCP23XXX_H_ */
103