//Created by Barbu Vulc!
//FreeRTOS library for Arduino:
#include "freertos/FreeRTOS.h"
//Define variables for HC-SR04:
#define echoPin 4 //Attach pin D2 Arduino to pin Echo of HC-SR04.
#define trigPin 2 //Attach pin D3 Arduino to pin Trig of HC-SR04.
long duration; //Variable for the duration of sound wave travel.
int distance; //Variable for the distance measurement.
//Define variables for photoresistor:
const int sensorMin = 0; //Sensor minimum...
const int sensorMax = 500; //Sensor maximum...
//Variables for LEDs:
const int LED1 = 11, LED2 = 12;
//'LED1' is for HC-SR04 & 'LED2' is for photoresistor.
void setup() {
//Serial communication:
Serial.begin(9600);
//LEDs' initialization:
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
//The created tasks!
xTaskCreate(Task1, "HC-SR04 sensor", 100, NULL, 1, NULL);
xTaskCreate(Task2, "Photoresistor", 100, NULL, 0, NULL);
xTaskCreate(Task3, "Communication", 100, NULL, 2, NULL);
}
//Task for HC-SR04 sensor!
static void Task1(void* pvParameters) {
while (1) {
//Clears the trigPin condition
digitalWrite(trigPin, LOW); delay(100);
//Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH); delay(100);
digitalWrite(trigPin, LOW);
//Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
//Calculating the distance
distance = duration * 0.034 / 2; //Speed of sound wave divided by 2 (go and back)
Serial.println("Distance: ");
Serial.print(distance);
Serial.println(" cm");
digitalWrite(LED1, 1); digitalWrite(LED2, 0);
vTaskDelay(500 / portTICK_PERIOD_MS);
}
}
//Task for photoresistor!
static void Task2(void* pvParameters) {
while (1) {
// read the sensor:
int sensorReading = analogRead(A0);
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
Serial.println("Range: ");
Serial.print(range);
Serial.println(" lux \n");
digitalWrite(LED1, 0); digitalWrite(LED2, 1);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
//Task purely for serial communication!
static void Task3(void* pvParameters) {
while (1) {
Serial.println(F("HC-SR04 sensor - Task1"));
Serial.println(F("Photoresistor - Task2"));
vTaskDelay(4000 / portTICK_PERIOD_MS);
}
}
void loop() {}