#include <Arduino.h>
#include "soc/rtc.h"

// ICC register address for communication
#define ICC_REG_ADDR 0x3ff48000

// Define the LED pin
#define LED_PIN 2

// Task handles
TaskHandle_t Task0Handle = NULL;

// Task 0 function (Core 0)
void Task0(void *parameter) {
  while (1) {
    // Generate random number
    uint32_t randomNum = random(1000);

    // Write random number to ICC register
    WRITE_PERI_REG(ICC_REG_ADDR, randomNum);

    delay(2000);
  }
}

// Task 1 function (Core 1)
void Task1(void *parameter) {
  // Initialize LED pin
  pinMode(LED_PIN, OUTPUT);

  while (1) {
    // Read data from ICC register
    uint32_t delayTime = READ_PERI_REG(ICC_REG_ADDR);

    // Blink LED with delayTime
    digitalWrite(LED_PIN, HIGH);
    delay(delayTime);
    digitalWrite(LED_PIN, LOW);
    delay(delayTime);
  }
}

void setup() {
  // Enable ICC register write access for both cores
  CLEAR_PERI_REG_MASK(RTC_CNTL_ANA_CONF_REG, RTC_CNTL_DIG_PWC_REG);

  // Create Task 0 (Core 0)
  xTaskCreatePinnedToCore(
    Task0,            // Task function
    "Task0",          // Task name
    10000,            // Stack size
    NULL,             // Task parameter
    1,                // Task priority
    &Task0Handle,     // Task handle
    0                 // Run on core 0
  );

  // Create Task 1 (Core 1)
  xTaskCreatePinnedToCore(
    Task1,            // Task function
    "Task1",          // Task name
    10000,            // Stack size
    NULL,             // Task parameter
    1,                // Task priority
    NULL,             // Task handle (not used)
    1                 // Run on core 1
  );
}

void loop() {
  // Empty loop
}