#include <Arduino_FreeRTOS.h>
#include <task.h>
#include <semphr.h>
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledhijau = 4; // the number of the LED pin
const int ledmerah = 3; // the number of the LED pin
const int trigPin = 6;
const int echoPin = 5;
const int ldrPin = A0;
// Create semaphore
SemaphoreHandle_t sema_v;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
long duration;
int distance;
int intensitas;
String cahaya;
bool stopTasks = false;
TaskHandle_t Handle_aTask; //membaca sensor ultrasonic
TaskHandle_t Handle_bTask; //membaca sensor ldr
// TaskHandle_t Handle_dTask;
//membaca sensor ultrasonic
void aTask(void* pvParameters) {
(void) pvParameters;
for (;;)
{
if (xSemaphoreTake(sema_v, portMAX_DELAY) == pdPASS)
{
digitalWrite(ledhijau, LOW);
digitalWrite(ledmerah, HIGH);
Serial.println("Task A Received Semaphore");
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
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;
// Prints the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.println(distance);
Serial.print("Jarak:");
Serial.println(distance);
}
}
}
//membaca sensor ldr
void bTask(void* pvParameters) {
(void) pvParameters;
for (;;)
{
if (xSemaphoreTake(sema_v, portMAX_DELAY) == pdPASS)
{
digitalWrite(ledmerah, LOW);
digitalWrite(ledhijau, HIGH);
Serial.println("Task B Received Semaphore");
intensitas = analogRead(ldrPin);
if(intensitas <= 200){
cahaya = "Terang";
}else{
cahaya = "gelap";
}
Serial.print("Cahaya: " );
Serial.println(cahaya);
}
}}
void setup() {
pinMode(ledhijau, OUTPUT);
pinMode(ledmerah, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
pinMode(buttonPin, INPUT);
xTaskCreate(aTask, "Task A", 256, NULL,tskIDLE_PRIORITY + 1, &Handle_aTask);
xTaskCreate(bTask, "Task B", 256, NULL,tskIDLE_PRIORITY + 1, &Handle_bTask);
sema_v = xSemaphoreCreateBinary();
if(sema_v !=NULL)
{
attachInterrupt(digitalPinToInterrupt(buttonPin), blinkmerah, HIGH);
}
}
void loop() {
}
void blinkmerah(){
Serial.println("ISR interrupt, Semaphore is Given");
BaseType_t xHigherPriorityTaskWoken pdFALSE;
xSemaphoreGiveFromISR(sema_v, &xHigherPriorityTaskWoken);
}