How to: Soil Sensor¶
Soil Moisture sensor measures moisture and temperature. See also About Soil Moisture Sensor article.
Tip
Writing a single sensor values to the console¶
This is the simplest example with single connected sensor to the Sensor Module.
1#include <application.h>
2
3// Soil sensor instance
4twr_soil_sensor_t soil_sensor;
5
6void soil_sensor_event_handler(twr_soil_sensor_t *self, uint64_t device_address, twr_soil_sensor_event_t event, void *event_param)
7{
8 if (event == TWR_SOIL_SENSOR_EVENT_UPDATE)
9 {
10 uint16_t moisture;
11 float temperature;
12
13 twr_soil_sensor_get_cap_raw(self, device_address, &moisture);
14 twr_soil_sensor_get_temperature_celsius(self, device_address, &temperature);
15 twr_log_debug("Moisture: %d\tTemperature %.2f", moisture, temperature);
16 }
17}
18
19void application_init(void)
20{
21 twr_log_init(TWR_LOG_LEVEL_DUMP, TWR_LOG_TIMESTAMP_ABS);
22
23 // Initialize soil sensor
24 twr_soil_sensor_init(&soil_sensor);
25 twr_soil_sensor_set_event_handler(&soil_sensor, soil_sensor_event_handler, NULL);
26 twr_soil_sensor_set_update_interval(&soil_sensor, 1000);
27}
Multiple connected sensors¶
When you connect multiple sensors, you need to initialize them with twr_soil_sensor_init_multiple
.
In the event handler you then get the device_address
in the callback parameter,
or you can get sensor index by calling twr_soil_sensor_get_index_by_device_address()
.
1#define MAX_SOIL_SENSORS 5
2
3// Sensors array
4twr_soil_sensor_sensor_t sensors[MAX_SOIL_SENSORS];
5
6void soil_sensor_event_handler(twr_soil_sensor_t *self, uint64_t device_address, twr_soil_sensor_event_t event, void *event_param)
7{
8 ...
9 if (event == TWR_SOIL_SENSOR_EVENT_UPDATE)
10 {
11 int index = twr_soil_sensor_get_index_by_device_address(self, device_address);
12 ...
13}
14
15void application_init(void)
16{
17 ...
18
19 // Initialize soil sensors
20 twr_soil_sensor_init_multiple(&soil_sensor, sensors, MAX_SOIL_SENSORS);
21 twr_soil_sensor_set_event_handler(&soil_sensor, soil_sensor_event_handler, NULL);
22 twr_soil_sensor_set_update_interval(&soil_sensor, SENSOR_UPDATE_SERVICE_INTERVAL);
23
24 ...
25}