From 3e886c502a4cf8b670d60c838cc6f6cf06cc3968 Mon Sep 17 00:00:00 2001
From: Rahix <rahix@rahix.de>
Date: Tue, 20 Aug 2019 14:04:03 +0200
Subject: [PATCH] feat(light-sensor): Add ADC locking

Signed-off-by: Rahix <rahix@rahix.de>
---
 epicardium/modules/light_sensor.c | 32 +++++++++++++++++++++++++------
 epicardium/modules/modules.h      |  1 +
 2 files changed, 27 insertions(+), 6 deletions(-)

diff --git a/epicardium/modules/light_sensor.c b/epicardium/modules/light_sensor.c
index acf8585e..ff2cd81c 100644
--- a/epicardium/modules/light_sensor.c
+++ b/epicardium/modules/light_sensor.c
@@ -1,10 +1,14 @@
-#include "FreeRTOS.h"
-#include "timers.h"
-#include "led.h"
+#include "epicardium.h"
+#include "modules/log.h"
+#include "modules/modules.h"
+
 #include "mxc_config.h"
+#include "led.h"
 #include "adc.h"
 #include "gpio.h"
-#include <errno.h>
+
+#include "FreeRTOS.h"
+#include "timers.h"
 
 #define READ_FREQ pdMS_TO_TICKS(100)
 
@@ -25,12 +29,25 @@ static int light_sensor_init()
 
 static void readAdcCallback()
 {
+	if (hwlock_acquire(HWLOCK_ADC, 0) != 0) {
+		/* Can't do much about this here ... Retry next time */
+		return;
+	}
+
 	ADC_StartConvert(ADC_CH_7, 0, 0);
 	ADC_GetData(&last_value);
+
+	hwlock_release(HWLOCK_ADC);
 }
 
 int epic_light_sensor_run()
 {
+	int ret = 0;
+
+	if (hwlock_acquire(HWLOCK_ADC, pdMS_TO_TICKS(500)) != 0) {
+		return -EBUSY;
+	}
+
 	light_sensor_init();
 
 	if (!poll_timer) {
@@ -47,10 +64,12 @@ int epic_light_sensor_run()
 	}
 	if (xTimerIsTimerActive(poll_timer) == pdFALSE) {
 		if (xTimerStart(poll_timer, 0) != pdPASS) {
-			return -EBUSY;
+			ret = -EBUSY;
 		}
 	}
-	return 0;
+
+	hwlock_release(HWLOCK_ADC);
+	return ret;
 }
 
 int epic_light_sensor_stop()
@@ -63,6 +82,7 @@ int epic_light_sensor_stop()
 	if (xTimerStop(poll_timer, 0) != pdPASS) {
 		return -EBUSY;
 	}
+
 	return 0;
 }
 
diff --git a/epicardium/modules/modules.h b/epicardium/modules/modules.h
index abf1c770..ccd8a900 100644
--- a/epicardium/modules/modules.h
+++ b/epicardium/modules/modules.h
@@ -42,6 +42,7 @@ void hwlock_init(void);
 
 enum hwlock_periph {
 	HWLOCK_I2C = 0,
+	HWLOCK_ADC,
 	_HWLOCK_MAX,
 };
 
-- 
GitLab