LCA 2008 Z-axis accelerometer demo
[fw/openalt] / sensors / sensors.c
1 //
2 //
3 //
4 #include <stdio.h>
5 #include <string.h>
6 #include <unistd.h>
7 #include <fcntl.h>
8
9 #include "FreeRTOS.h"
10 #include "task.h"
11 #include "semphr.h"
12
13 #include "../main.h"
14 #include "../adc/adc.h"
15 #include "../dac/dac.h"
16 #include "../leds/leds.h"
17 #include "sensors.h"
18
19 //
20 //
21 //
22 static sensorData_t sensorData;
23 static xSemaphoreHandle semaphore;
24
25 //
26 //  Return 1 if got a copy, 0 if not.
27 //
28 int sensorsCopyData (sensorData_t *dst)
29 {
30   if (xSemaphoreTake (semaphore, 100 / portTICK_RATE_MS) == pdTRUE)
31   {
32     memcpy (dst, &sensorData, sizeof (sensorData));
33     xSemaphoreGive (semaphore);
34     return 1;
35   }
36
37   memset (dst, 0, sizeof (sensorData_t));
38   return 0;
39 }
40
41 //
42 //
43 //
44 portTASK_FUNCTION (vSensorsTask, pvParameters __attribute__ ((unused)))
45 {
46   portTickType xTickCount;
47   int adcValue;
48   int adcLastValue = -1;
49   int adcChanged = -1;
50   int dacValue = 0;
51   int dacDirection = -16;
52
53   memset (&sensorData, 0, sizeof (sensorData));
54
55   vSemaphoreCreateBinary (semaphore);
56
57   xTickCount = xTaskGetTickCount ();
58
59   adcStartXYZ();
60
61   for (;;)
62   {
63     vTaskDelayUntil (&xTickCount, 100 / portTICK_RATE_MS);
64
65     printf("tick\n");
66
67     //
68     //  Adjust the DAC value so we output a slow sine wave
69     //
70     if ((dacValue <= 0) || (dacValue >= (1024 - dacDirection)))
71       dacDirection = 0 - dacDirection;
72
73     dacSet (dacValue);
74     dacValue += dacDirection;
75
76     //
77     //  Read the current ADC value, keep only top 2 bits.  If it changes,
78     //  tell the LED task to change the blink rate.
79     //
80     if ((adcValue = (adcRead0_3 () >> 8)) != adcLastValue)
81     {
82       xQueueSend (xLEDQueue, &adcValue, (portTickType) 0);
83       adcLastValue = adcValue;
84       adcChanged++;
85     }
86
87     //
88     //  Update the sensors data
89     //
90     if (xSemaphoreTake (semaphore, portMAX_DELAY) == pdTRUE)
91     {
92       sensorData.sensorCount++;
93       sensorData.adcChanges = adcChanged;
94
95       xSemaphoreGive (semaphore);
96     }
97
98     //
99     //  get and display last X, Y, and Z accelerometer readings,
100     //  the start another conversion
101     //
102     printf("%04x %04x %04x\n", adcReadX(), adcReadY(), adcReadZ());
103
104   }
105 }