#include "main.h"
#include "hardware/gpio.h"
#include "pico/stdlib.h"
#include "pico/time.h"
#include "tft.h"

// lcd configuration
const struct tft_config lcd_config = {
	.pio = pio0,
	.sm = 0,
	.gpio_din = 18,
	.gpio_clk = 17,
	.gpio_cs = 21,
	.gpio_dc = 19,
	.gpio_rst = 20,
	.gpio_bl = 16,
	.width = 320,
	.height = 480
};

int main()
{
	set_sys_clock_khz(200 * 1000, true);

    uint offset = pio_add_program(lcd_config.pio, &tft_program);
    tft_program_init(lcd_config.pio, lcd_config.sm, offset, lcd_config.gpio_din, lcd_config.gpio_clk, 1.f);
	
	int dma_chan = dma_claim_unused_channel(true);
	dma_channel_config c = dma_channel_get_default_config(dma_chan);
	channel_config_set_transfer_data_size(&c, DMA_SIZE_32);
	channel_config_set_read_increment(&c, true);
	channel_config_set_dreq(&c, DREQ_PIO0_TX0);
	dma_channel_configure(
		dma_chan,
		&c,
		&pio0->txf[lcd_config.sm],
		NULL,
		320*480/4,
		false
	);
	dled_start(25);	
	tft_init(&lcd_config, dma_chan);
	sleep_ms(100);
	tft_start_pixels(lcd_config.pio, lcd_config.sm);
	while (true){
		for(size_t i = 0; i < 8; i++) {
			tft_fill(0);
			dma_channel_wait_for_finish_blocking(dma_chan);
		}
		for(size_t i = 0; i < 8; i++) {
			tft_fill(31807);
			dma_channel_wait_for_finish_blocking(dma_chan);
		}
	}
	return 0;
}
void dled_start(uint pin){
	gpio_init(pin);
    gpio_set_dir(pin, GPIO_OUT);
	gpio_put(pin, 1);
}
void dled_end(uint pin){
	gpio_put(pin, 0);
}
