1 /*
2  * Copyright (c) 2020 Laird Connectivity
3  * Based on code by Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdio.h>
9 #include <zephyr/kernel.h>
10 #include <zephyr/device.h>
11 #include <zephyr/drivers/gpio.h>
12 #include <zephyr/drivers/sensor.h>
13 
fetch_and_display(const struct device * sensor)14 static void fetch_and_display(const struct device *sensor)
15 {
16 	static unsigned int count;
17 	struct sensor_value mag;
18 	int rc = sensor_sample_fetch(sensor);
19 
20 	++count;
21 	if (rc == 0) {
22 		rc = sensor_channel_get(sensor,
23 					SENSOR_CHAN_PROX,
24 					&mag);
25 	}
26 	if (rc < 0) {
27 		printf("ERROR: Update failed: %d\n", rc);
28 	} else {
29 		printf("#%u @ %u ms: %d\n",
30 		       count, k_uptime_get_32(), mag.val1);
31 	}
32 }
33 
34 #ifdef CONFIG_SM351LT_TRIGGER
trigger_handler(const struct device * dev,const struct sensor_trigger * trig)35 static void trigger_handler(const struct device *dev,
36 			    const struct sensor_trigger *trig)
37 {
38 	fetch_and_display(dev);
39 }
40 #endif
41 
main(void)42 int main(void)
43 {
44 	const struct device *const sensor = DEVICE_DT_GET_ONE(honeywell_sm351lt);
45 
46 	if (!device_is_ready(sensor)) {
47 		printk("Device %s is not ready\n", sensor->name);
48 		return 0;
49 	}
50 
51 #if CONFIG_SM351LT_TRIGGER
52 	{
53 		struct sensor_trigger trig;
54 		int rc;
55 
56 		trig.type = SENSOR_TRIG_NEAR_FAR;
57 		trig.chan = SENSOR_CHAN_PROX;
58 
59 		struct sensor_value trigger_type = {
60 			.val1 = GPIO_INT_EDGE_BOTH,
61 		};
62 
63 		rc = sensor_attr_set(sensor, trig.chan,
64 				     SENSOR_ATTR_PRIV_START,
65 				     &trigger_type);
66 		if (rc != 0) {
67 			printf("Failed to set trigger type: %d\n", rc);
68 			return 0;
69 		}
70 
71 		rc = sensor_trigger_set(sensor, &trig, trigger_handler);
72 		if (rc != 0) {
73 			printf("Failed to set trigger: %d\n", rc);
74 			return 0;
75 		}
76 
77 		printf("Waiting for triggers\n");
78 		while (true) {
79 			k_sleep(K_MSEC(2000));
80 		}
81 	}
82 #else /* CONFIG_SM351LT_TRIGGER */
83 	printf("Polling at 0.5 Hz\n");
84 	while (true) {
85 		fetch_and_display(sensor);
86 		k_sleep(K_MSEC(2000));
87 	}
88 #endif /* CONFIG_SM351LT_TRIGGER */
89 }
90