In this section, we are going to develop a Contiki-NG application called virtual-sensor. We will use the general library for the sensor, which will be used for temperature and humidity readings. We will create a virtual sensor in a header file that exposes two functions, read_temperature() and read_humidity().
mysensor.h
mysensor.c
demo-sensor.c
Makefile
$$ Demo-sensor.c \begin{cases} &read_temperature()\ &read_humidity() \end{cases} $$
1 2 3 4 5 6 7 8 9 #ifndef MYSENSOR_H #define MYSENSOR_H struct Sensor { char name[15 ]; float value; }; struct Sensor read_temperature () ;struct Sensor read_humidity () ;#endif
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include "mysensor.h" #include <string.h> #include <stdlib.h> float random value (float min, float max) { float scale = rand() / (float ) RAND MAX; return min + scale * (max - min); } struct Sensor read temperature () { struct Sensor temp ; strncpy (temp.name, "Temperature" , 15 ); temp.value = random_value(o, 35 ); return temp; } struct Sensor read humidity () { struct Sensor humdidty ; strncpy (humdidty.name, "Humidity" , 15 ); humdidty.value = random_value(40 , 80 ); return humdidty; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include "contiki.h" #include "mysensor.h" #include "sys/etimer.h" #include <stdio.h> PROCESS(sensor_process, "Sensor process" ); AUTOSTART PROCESSES (&sensor_process) ; static struct etimer timer ; PROCESS THREAD (sensor_process, ev, data) { PROCESS BEGIN () ; printf ("Demo Virtual Sensor\n" ); while (1 ) { etimer_set(&timer, 3 * CLOCK_SECOND); PROCESS WAIT EVENT UNTIL (etimer_expired(ftimer)) ; struct Sensor temp = read_temperature(); printf ("%s: %.2f\n" , temp.name, temp.value); struct Sensor hum = read humidity () ; printf ("%s: %.2f\n" , hum.name, hum.value); printf ("\n" ); } PROCESS END () ; }
1 2 3 4 5 CONTIKI PROJECT = demo-sensor all: $(CONTIKI_PROJECT) PROJECT SOURCEFILES += mysensor.c CONTIKI = /home/user/Documents/book/contiki include $(CONTIKI) /Makefile.include
1 2 make TARGET=native ./demo-sensor.native