#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/spi.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/sys/printk.h>

#define SPI_DEV_NODE    DT_NODELABEL(spi00)

static struct spi_cs_control cs_ctrl = {
    .gpio = SPI_CS_GPIOS_DT_SPEC_GET(DT_NODELABEL(spi00)),
    .delay = 0,
};

void main(void)
{
    const struct device *spi_dev = DEVICE_DT_GET(SPI_DEV_NODE);

    if (!device_is_ready(spi_dev)) {
        printk("SPI device not ready\n");
        return;
    }

    struct spi_config spi_cfg = {
        .frequency = 4000000,
        .operation = SPI_WORD_SET(8) | SPI_TRANSFER_MSB | SPI_OP_MODE_MASTER  ,
        .cs = &cs_ctrl,
    };

    // Prepare buffers: [register | 0x80 for read], [0x00 dummy]
    uint8_t tx_buf[2] = { 0x0F | 0x80, 0x00 }; // 0x0F WHO_AM_I
    uint8_t rx_buf[2] = { 0, 0 };

    struct spi_buf tx = { .buf = tx_buf, .len = 2 };
    struct spi_buf rx = { .buf = rx_buf, .len = 2 };
    struct spi_buf_set tx_set = { .buffers = &tx, .count = 1 };
    struct spi_buf_set rx_set = { .buffers = &rx, .count = 1 };

printk("Before spi_transceive\n");
int ret = spi_transceive(spi_dev, &spi_cfg, &tx_set, &rx_set);
printk("After spi_transceive: %d\n", ret);
    if (ret == 0) {
        printk("SPI WHO_AM_I read: 0x%02x\n", rx_buf[1]); // Data is in rx_buf[1]
    } else {
        printk("SPI read failed: %d\n", ret);
    }

    while (1) {
        k_sleep(K_MSEC(1000));
    }


}