1 /*
2  * Copyright (c) 2017 Intel Corporation
3  * Copyright (c) 2018 Phytec Messtechnik GmbH
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/kernel.h>
9 #include <zephyr/drivers/sensor.h>
10 #include <zephyr/device.h>
11 #include <stdio.h>
12 #include <zephyr/sys/printk.h>
13 
14 #ifdef CONFIG_APDS9960_TRIGGER
15 K_SEM_DEFINE(sem, 0, 1);
16 
trigger_handler(const struct device * dev,const struct sensor_trigger * trigger)17 static void trigger_handler(const struct device *dev,
18 			    const struct sensor_trigger *trigger)
19 {
20 	ARG_UNUSED(dev);
21 	ARG_UNUSED(trigger);
22 
23 	k_sem_give(&sem);
24 }
25 #endif
26 
main(void)27 int main(void)
28 {
29 	const struct device *dev;
30 	struct sensor_value intensity, pdata;
31 
32 	printk("APDS9960 sample application\n");
33 	dev = DEVICE_DT_GET_ONE(avago_apds9960);
34 	if (!device_is_ready(dev)) {
35 		printk("sensor: device not ready.\n");
36 		return 0;
37 	}
38 
39 #ifdef CONFIG_APDS9960_TRIGGER
40 	struct sensor_value attr = {
41 		.val1 = 127,
42 		.val2 = 0,
43 	};
44 
45 	if (sensor_attr_set(dev, SENSOR_CHAN_PROX,
46 			    SENSOR_ATTR_UPPER_THRESH, &attr)) {
47 		printk("Could not set threshold\n");
48 		return 0;
49 	}
50 
51 	struct sensor_trigger trig = {
52 		.type = SENSOR_TRIG_THRESHOLD,
53 		.chan = SENSOR_CHAN_PROX,
54 	};
55 
56 	if (sensor_trigger_set(dev, &trig, trigger_handler)) {
57 		printk("Could not set trigger\n");
58 		return 0;
59 	}
60 #endif
61 
62 	while (true) {
63 #ifdef CONFIG_APDS9960_TRIGGER
64 		printk("Waiting for a threshold event\n");
65 		k_sem_take(&sem, K_FOREVER);
66 #else
67 		k_sleep(K_MSEC(5000));
68 #endif
69 		if (sensor_sample_fetch(dev)) {
70 			printk("sensor_sample fetch failed\n");
71 		}
72 
73 		sensor_channel_get(dev, SENSOR_CHAN_LIGHT, &intensity);
74 		sensor_channel_get(dev, SENSOR_CHAN_PROX, &pdata);
75 
76 		printk("ambient light intensity %d, proximity %d\n",
77 		       intensity.val1, pdata.val1);
78 
79 #ifdef CONFIG_PM_DEVICE
80 		pm_device_action_run(dev, PM_DEVICE_ACTION_SUSPEND);
81 		printk("set low power state for 2s\n");
82 		k_sleep(K_MSEC(2000));
83 		pm_device_action_run(dev, PM_DEVICE_ACTION_RESUME);
84 #endif
85 	}
86 }
87