11
11
#include <zephyr/sys/util.h>
12
12
#include <zephyr/device.h>
13
13
#include <zephyr/init.h>
14
+ #include <zephyr/sys/byteorder.h>
14
15
#include <zephyr/drivers/sensor.h>
15
16
#include <zephyr/drivers/i2c.h>
16
17
#include <zephyr/logging/log.h>
18
+
17
19
LOG_MODULE_REGISTER (ams_as5600 , CONFIG_SENSOR_LOG_LEVEL );
18
20
19
- #define AS5600_ANGLE_REGISTER_H 0x0E
21
+ #define AS5600_ANGLE_REGISTER_H 0x0E
22
+ #define AS5600_ANGLE_REGISTER_RAW_H 0x0C
23
+ #define AS5600_STATUS_REGISTER 0x0B
20
24
#define AS5600_FULL_ANGLE 360
21
25
#define AS5600_PULSES_PER_REV 4096
22
26
#define AS5600_MILLION_UNIT 1000000
23
27
28
+ #define AS5600_STATUS_MH_BIT (3) /* Magnet too strong */
29
+ #define AS5600_STATUS_ML_BIT (4) /* Magnet too weak */
30
+ #define AS5600_STATUS_MD_BIT (5) /* Magnet detected */
31
+
32
+
24
33
struct as5600_dev_cfg {
25
34
struct i2c_dt_spec i2c_port ;
26
35
};
@@ -35,18 +44,43 @@ static int as5600_fetch(const struct device *dev, enum sensor_channel chan)
35
44
struct as5600_dev_data * dev_data = dev -> data ;
36
45
const struct as5600_dev_cfg * dev_cfg = dev -> config ;
37
46
38
- uint8_t read_data [2 ] = {0 , 0 };
39
- uint8_t angle_reg = AS5600_ANGLE_REGISTER_H ;
47
+ uint8_t status ;
48
+ int err = i2c_reg_read_byte_dt (& dev_cfg -> i2c_port ,
49
+ AS5600_STATUS_REGISTER ,
50
+ & status );
51
+
52
+ if (err != 0 ) {
53
+ LOG_ERR ("Failed to read status register: %d" , err );
54
+ return err ;
55
+ }
56
+
57
+ /* Check if the magnet is present */
58
+ if (!(status & BIT (AS5600_STATUS_MD_BIT ))) {
59
+ LOG_WRN ("Magnet not detected." );
60
+ return - ENODATA ;
61
+ }
62
+
63
+ /* Check if the magnet is too strong or too weak */
64
+ if (status & BIT (AS5600_STATUS_MH_BIT )) {
65
+ LOG_WRN ("Magnet too strong." );
66
+ return - ENODATA ;
67
+ }
68
+
69
+ if (status & BIT (AS5600_STATUS_ML_BIT )) {
70
+ LOG_WRN ("Magnet too weak." );
71
+ return - ENODATA ;
72
+ }
73
+
74
+ uint8_t buffer [2 ] = {0 , 0 };
40
75
41
- int err = i2c_write_read_dt (& dev_cfg -> i2c_port ,
42
- & angle_reg ,
43
- 1 ,
44
- & read_data ,
45
- sizeof (read_data ));
76
+ err = i2c_burst_read_dt (& dev_cfg -> i2c_port ,
77
+ AS5600_ANGLE_REGISTER_RAW_H ,
78
+ (uint8_t * ) & buffer ,
79
+ sizeof (buffer ));
46
80
47
81
/* invalid readings preserves the last good value */
48
82
if (!err ) {
49
- dev_data -> position = (( uint16_t ) read_data [ 0 ] << 8 ) | read_data [ 1 ] ;
83
+ dev_data -> position = sys_get_be16 ( buffer ) ;
50
84
}
51
85
52
86
return err ;
0 commit comments