#include <Arduino_FreeRTOS.h>
#include <semphr.h>
SemaphoreHandle_t xSerialSemaphore;
void TaskDigitalRead( void *pvParameters );
void TaskAnalogRead( void *pvParameters );
int sensorValue = -1, sensorValueOld = -1;
bool semaphore = false;
bool boutonState = true;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
if ( xSerialSemaphore == NULL ) {
xSerialSemaphore = xSemaphoreCreateMutex();
if ( ( xSerialSemaphore ) != NULL )
xSemaphoreGive( ( xSerialSemaphore ) );
}
sensorValue = analogRead(A3);
sensorValueOld = sensorValue;
xTaskCreate(
TaskDigitalRead
, "DigitalRead"
, 128
, NULL
, 2
, NULL );
xTaskCreate(
TaskAnalogRead
, "AnalogRead"
, 128
, NULL
, 1
, NULL );
}
void loop()
{
// Empty. Things are done in Tasks.
}
/*---------------------- Tasks ---------------------*/
void TaskDigitalRead( void *pvParameters __attribute__((unused)) ) // This is a Task.
{
uint8_t pushButton1 = 2;
// make the pushbutton's pin an input:
pinMode(pushButton1, INPUT);
for (;;) // A Task shall never return or exit.
{
// read the input pin:
if (boutonState != digitalRead(pushButton1)){
boutonState = digitalRead(pushButton1);
semaphore = boutonState;
Serial.print("Semaphore: ");Serial.println(semaphore);
}
if (semaphore) {
if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ){
if( sensorValueOld != sensorValue) {
Serial.print("value task1:");Serial.println(sensorValue);
}
xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others.
}
} else {
if( sensorValueOld != sensorValue) {
Serial.print("value task1:");Serial.println(sensorValue);
}
}
vTaskDelay(1);
}
}
void TaskAnalogRead( void *pvParameters __attribute__((unused)) ) // This is a Task.
{
for (;;)
{
// read the input on analog pin 0:
sensorValue = analogRead(A3);
if (semaphore) {
if ( xSemaphoreTake( xSerialSemaphore, ( TickType_t ) 5 ) == pdTRUE ){
if( sensorValueOld != sensorValue) {
Serial.print("value task2:");Serial.println(sensorValue);
}
xSemaphoreGive( xSerialSemaphore ); // Now free or "Give" the Serial Port for others.
}
} else {
if( sensorValueOld != sensorValue) {
Serial.print("value task2:");Serial.println(sensorValue);
}
}
vTaskDelay(1);
sensorValueOld = sensorValue;
}
}