Login
1 branch 0 tags
Ben (Desktop/Arch) Audio stuff a114494 1 month ago 11 Commits
moon / firmware / esp32 / main / esp32_main.c
#include "moon.h"
#include "audio.h"
#include "st7735.h"

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"

static const char *TAG = "moon";

// Forward declarations from shared code
extern void setup(void);
extern void loop(void);

// RGB565 conversion buffer (32 lines × 160 pixels × 2 bytes = 10KB)
#define CHUNK_HEIGHT 32
static uint16_t rgb565_buf[SCREEN_WIDTH * CHUNK_HEIGHT];

// Convert ARGB8888 to RGB565 with byte swap for big-endian SPI
static inline uint16_t argb_to_rgb565(uint32_t argb) {
    uint8_t r = (argb >> 16) & 0xFF;
    uint8_t g = (argb >> 8) & 0xFF;
    uint8_t b = argb & 0xFF;

    uint16_t rgb565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
    // Swap bytes for SPI (big-endian)
    return (rgb565 >> 8) | (rgb565 << 8);
}

// Implementation of blit_buf for ST7735
void blit_buf(const void *buf, int yStart, int yEnd) {
    const uint32_t *src = (const uint32_t *)buf;
    int total_lines = yEnd - yStart;

    for (int chunk_start = 0; chunk_start < total_lines; chunk_start += CHUNK_HEIGHT) {
        int chunk_lines = total_lines - chunk_start;
        if (chunk_lines > CHUNK_HEIGHT) {
            chunk_lines = CHUNK_HEIGHT;
        }

        // Convert chunk from ARGB8888 to RGB565
        int pixel_count = SCREEN_WIDTH * chunk_lines;
        for (int i = 0; i < pixel_count; i++) {
            rgb565_buf[i] = argb_to_rgb565(src[chunk_start * SCREEN_WIDTH + i]);
        }

        // Set window and write pixels
        st7735_set_window(0, yStart + chunk_start,
                          SCREEN_WIDTH - 1, yStart + chunk_start + chunk_lines - 1);
        st7735_write_pixels(rgb565_buf, pixel_count);
    }
}

void app_main(void) {
    ESP_LOGI(TAG, "Initializing ST7735 display...");
    st7735_init();

    ESP_LOGI(TAG, "Running setup...");
    setup();

    ESP_LOGI(TAG, "Initializing audio...");
    audio_init();

    ESP_LOGI(TAG, "Entering main loop...");
    while (1) {
        loop();
        // audio_update();  // Enable when new PCM5102A arrives
        vTaskDelay(pdMS_TO_TICKS(16));  // ~60 FPS
    }
}