1 /*
2  * Copyright (c) 2024 SILA Embedded Solutions GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT maxim_max31790
8 
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/i2c.h>
11 #include <zephyr/drivers/mfd/max31790.h>
12 #include <zephyr/sys/util.h>
13 #include <zephyr/kernel.h>
14 #include <zephyr/logging/log.h>
15 
16 
17 LOG_MODULE_REGISTER(max_max31790, CONFIG_MFD_LOG_LEVEL);
18 
19 struct max31790_config {
20 	struct i2c_dt_spec i2c;
21 };
22 
max31790_set_globalconfiguration_i2cwatchdog(uint8_t * destination,uint8_t value)23 static void max31790_set_globalconfiguration_i2cwatchdog(uint8_t *destination, uint8_t value)
24 {
25 	uint8_t length = MAX37190_GLOBALCONFIGURATION_I2CWATCHDOG_LENGTH;
26 	uint8_t pos = MAX37190_GLOBALCONFIGURATION_I2CWATCHDOG_POS;
27 
28 	*destination &= ~GENMASK(pos + length - 1, pos);
29 	*destination |= FIELD_PREP(GENMASK(pos + length - 1, pos), value);
30 }
31 
max31790_init(const struct device * dev)32 static int max31790_init(const struct device *dev)
33 {
34 	const struct max31790_config *config = dev->config;
35 	int result;
36 	uint8_t reg_value;
37 
38 	if (!i2c_is_ready_dt(&config->i2c)) {
39 		LOG_ERR("I2C device not ready");
40 		return -ENODEV;
41 	}
42 
43 	reg_value = 0;
44 	reg_value &= ~MAX37190_GLOBALCONFIGURATION_STANDBY_BIT;
45 	reg_value |= MAX37190_GLOBALCONFIGURATION_RESET_BIT;
46 	reg_value |= MAX37190_GLOBALCONFIGURATION_BUSTIMEOUT_BIT;
47 	reg_value &= ~MAX37190_GLOBALCONFIGURATION_OSCILLATORSELECTION_BIT;
48 	max31790_set_globalconfiguration_i2cwatchdog(&reg_value, 0);
49 	reg_value &= ~MAX37190_GLOBALCONFIGURATION_I2CWATCHDOGSTATUS_BIT;
50 
51 	result = i2c_reg_write_byte_dt(&config->i2c, MAX37190_REGISTER_GLOBALCONFIGURATION,
52 				       reg_value);
53 	if (result != 0) {
54 		return result;
55 	}
56 
57 	k_sleep(K_USEC(MAX31790_RESET_TIMEOUT_IN_US));
58 
59 	result = i2c_reg_read_byte_dt(&config->i2c, MAX37190_REGISTER_GLOBALCONFIGURATION,
60 				      &reg_value);
61 	if (result != 0) {
62 		return result;
63 	}
64 
65 	if ((reg_value & MAX37190_GLOBALCONFIGURATION_STANDBY_BIT) != 0) {
66 		LOG_ERR("PWM controller is still in standby");
67 		return -ENODEV;
68 	}
69 
70 	return 0;
71 }
72 
73 #define MAX31790_INIT(inst)                                                                        \
74 	static const struct max31790_config max31790_##inst##_config = {                           \
75 		.i2c = I2C_DT_SPEC_INST_GET(inst),                                                 \
76 	};                                                                                         \
77                                                                                                    \
78 	DEVICE_DT_INST_DEFINE(inst, max31790_init, NULL, NULL, &max31790_##inst##_config,          \
79 			      POST_KERNEL, CONFIG_MFD_INIT_PRIORITY, NULL);
80 
81 DT_INST_FOREACH_STATUS_OKAY(MAX31790_INIT);
82