Files

59 lines
1.7 KiB
C

/**
* @file adc.c
* @brief ADC reading task for joystick channels and battery voltage
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/adc.h"
#include "app_main.h"
static const char *TAG = "adc";
/* ADC channel to GPIO mapping for ESP32S3 */
static const adc2_channel_t adc_channels[] = {
ADC2_CHANNEL_0, /* GPIO 4 - CH1 */
ADC2_CHANNEL_1, /* GPIO 5 - CH2 */
ADC2_CHANNEL_2, /* GPIO 6 - CH3 */
ADC2_CHANNEL_3, /* GPIO 7 - CH4 */
ADC2_CHANNEL_4, /* GPIO 15 - CH5 */
ADC2_CHANNEL_5, /* GPIO 16 - CH6 */
ADC2_CHANNEL_6, /* GPIO 17 - CH7 */
ADC2_CHANNEL_7, /* GPIO 9 - CH8 */
};
void adc_task(void *pvParameters)
{
adc_data_t adc_data;
int adc_raw = 0;
ESP_LOGI(TAG, "ADC task started");
while (1) {
/* Read all 8 joystick channels */
for (int i = 0; i < 8; i++) {
#if CONFIG_IDF_TARGET_ESP32S3
adc2_get_raw(adc_channels[i], ADC_WIDTH_BIT_12, &adc_raw);
#else
/* ESP32 uses ADC1 for these pins */
adc_raw = adc1_get_raw(ADC1_CHANNEL_0 + i);
#endif
adc_data.channels[i] = (uint16_t)adc_raw;
}
/* Read battery voltage (ADC1_CHANNEL_0 = GPIO 8) */
int bat_raw = adc1_get_raw(ADC1_CHANNEL_0);
/* Convert ADC reading to mV: 12-bit, 3.3V reference, voltage divider */
uint32_t bat_mv = (bat_raw * 3300 * 2) / 4096; /* Simple conversion */
adc_data.battery_mv = (uint16_t)bat_mv;
/* Send to queue (non-blocking) */
if (adc_data_queue) {
xQueueOverwrite(adc_data_queue, &adc_data);
}
vTaskDelay(pdMS_TO_TICKS(20)); /* 50Hz sample rate */
}
}