/*
 * Generated by AlSayad Studio from a blocks program. Changes made here are not
 * copied back into the blocks.
 * Board: ESP32-DevKitC V4 (ESP32-WROOM-32E); profile com.alsayad.esp32.esp-idf-6.1.
 * Numbers are 32-bit signed integers that wrap on overflow; division and
 * remainder by zero give 0.
 */
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "driver/gpio.h"
#include "esp_err.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

/* Waits without blocking other tasks; at least one RTOS tick for positive values. */
static void as_delay_ms(int32_t ms)
{
    if (ms <= 0) {
        return;
    }
    TickType_t ticks = pdMS_TO_TICKS(ms);
    vTaskDelay(ticks > 0 ? ticks : 1);
}

/* Lets the idle task and watchdog run at least every 100 ms inside loops. */
static void as_loop_tick(void)
{
    static int64_t last_yield_us = 0;
    int64_t now_us = esp_timer_get_time();
    if (now_us - last_yield_us >= 100000) {
        last_yield_us = now_us;
        vTaskDelay(1);
    }
}

static void as_gpio_init(void)
{
    const gpio_config_t outputs = {
        .pin_bit_mask = (1ULL << GPIO_NUM_23),
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE,
    };
    ESP_ERROR_CHECK(gpio_config(&outputs));
}

void app_main(void)
{
    as_gpio_init();
    /* Runs once when the board starts. */
    puts("Blink started");
    /* Repeats forever. */
    while (true) {
        gpio_set_level(GPIO_NUM_23, 1);
        as_delay_ms(500);
        gpio_set_level(GPIO_NUM_23, 0);
        as_delay_ms(500);
        as_loop_tick();
    }
}
