light_sensor.c 1.48 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "FreeRTOS.h"
#include "timers.h"
#include "led.h"
#include "mxc_config.h"
#include "adc.h"
#include "gpio.h"
#include <errno.h>

#define READ_FREQ pdMS_TO_TICKS(100)

static uint16_t last_value;
static TimerHandle_t poll_timer;
static StaticTimer_t poll_timer_buffer;

int epic_light_sensor_init()
{
	const sys_cfg_adc_t sys_adc_cfg =
		NULL; /* No system specific configuration needed. */
	if (ADC_Init(0x9, &sys_adc_cfg) != E_NO_ERROR) {
		return -EINVAL;
	}
	GPIO_Config(&gpio_cfg_adc7);
	return 0;
}

void readAdcCallback()
{
	ADC_StartConvert(ADC_CH_7, 0, 0);
	ADC_GetData(&last_value);
}

int epic_light_sensor_run()
{
	epic_light_sensor_init();

	if (!poll_timer) {
		poll_timer = xTimerCreateStatic(
			"light_sensor_adc",
			READ_FREQ,
			pdTRUE,
			NULL,
			readAdcCallback,
			&poll_timer_buffer
		);
		// since &poll_timer_buffer is not NULL, xTimerCreateStatic should allways succeed, so
		// we don't need to check for poll_timer being NULL.
	}
	if (xTimerIsTimerActive(poll_timer) == pdFALSE) {
		if (xTimerStart(poll_timer, 0) != pdPASS) {
			return -EBUSY;
		}
	}
	return 0;
}

int epic_light_sensor_stop()
{
	if (!poll_timer || xTimerIsTimerActive(poll_timer) == pdFALSE) {
		// timer wasn't running (or never started), just silently pass
		return 0;
	}

	if (xTimerStop(poll_timer, 0) != pdPASS) {
		return -EBUSY;
	}
	return 0;
}

int epic_light_sensor_get(uint16_t *value)
{
	if (!poll_timer || !xTimerIsTimerActive(poll_timer)) {
		return -ENODATA;
	}
	*value = last_value;
	return 0;
}