#include <Arduino_FreeRTOS.h>
#include <queue.h>
#include <LiquidCrystal_I2C.h>   

 
LiquidCrystal_I2C lcd(0x27, 16, 2);  // Replace with your LCD settings

 
#define QUEUE_SIZE 10 // selon notre queue size
QueueHandle_t data_queue;

// Function prototypes
void AdcTask(void *pvParameters);
void LcdTask(void *pvParameters);

void setup() {
  // Initialize serial communication (optional for debugging)
  Serial.begin(9600);

  // Initialize LCD
  lcd.init();
  lcd.backlight();

  // Create queue for communication between tasks
  data_queue = xQueueCreate(QUEUE_SIZE, sizeof(int));
  if (data_queue == NULL) {
    Serial.println("Failed to create queue!");
    while (1);
  }

  // Start FreeRTOS tasks
  xTaskCreate(AdcTask, "ADC Task", 128, NULL, 1, NULL);
  xTaskCreate(LcdTask, "LCD Task", 128, NULL, 2, NULL);

  // Start scheduler (should not return)
  vTaskStartScheduler();
}

void loop() {
   
}

void AdcTask(void *pvParameters) {
  while (1) {
    // Read ADC value from A4
    int adc_val = analogRead(A4);

    // Send ADC value to queue
    if (xQueueSend(data_queue, &adc_val, portMAX_DELAY) != pdPASS) {
      Serial.println("Failed to send data to queue!");
    }

    // Delay between readings (adjust as needed)
    vTaskDelay( 100);
  }
}

void LcdTask(void *pvParameters) {
  while (1) {
    // Receive data from queue
    int received_val;
    if (xQueueReceive(data_queue, &received_val, portMAX_DELAY) != pdPASS) {
      Serial.println("Failed to receive data from queue!");
    }

    // Display ADC value on LCD (adjust formatting as needed)
    lcd.clear();
    lcd.print("ADC Value: ");
    lcd.println(received_val);

    // Delay between updates (adjust as needed)
    vTaskDelay(200);
  }    
}