/* 手动定义：GPIO 端口（nRF5340 默认 gpio0）和引脚号 */
#define MY_GPIO_PORT_cs DEVICE_DT_GET(DT_NODELABEL(gpio0))  // 获取 gpio0 端口指针
#define MY_GPIO_PIN_cs ((gpio_pin_t)15U)  // 自定义引脚 P0.14（uint32_t 类型）

/* 手动定义：GPIO 端口（nRF5340 默认 gpio0）和引脚号 */
#define MY_GPIO_PORT_sclk DEVICE_DT_GET(DT_NODELABEL(gpio0))  // 获取 gpio0 端口指针
#define MY_GPIO_PIN_sclk ((gpio_pin_t)14U)  // 自定义引脚 P0.14（uint32_t 类型）

/* 手动定义：GPIO 端口（nRF5340 默认 gpio0）和引脚号 */
#define MY_GPIO_PORT_mosi DEVICE_DT_GET(DT_NODELABEL(gpio0))  // 获取 gpio0 端口指针
#define MY_GPIO_PIN_mosi ((gpio_pin_t)16U)  // 自定义引脚 P0.14（uint32_t 类型）

/* 手动定义：GPIO 端口（nRF5340 默认 gpio0）和引脚号 */
#define MY_GPIO_PORT_miso DEVICE_DT_GET(DT_NODELABEL(gpio0))  // 获取 gpio0 端口指针
#define MY_GPIO_PIN_miso ((gpio_pin_t)17U)// 自定义引脚 P0.14（uint32_t 类型）


#define SPI_CS_1    nrf_gpio_pin_set( MY_GPIO_PIN_cs)            /* SCK = 1 */
#define SPI_CS_0    nrf_gpio_pin_clear(MY_GPIO_PIN_cs)   

#define SPI_SCK_1    nrf_gpio_pin_set(MY_GPIO_PIN_sclk)            /* SCK = 1 */
#define SPI_SCK_0    nrf_gpio_pin_clear(MY_GPIO_PIN_sclk)        /* SCK = 0 */


#define SPI_MOSI_1     nrf_gpio_pin_set(MY_GPIO_PIN_mosi)           /* MOSI = 1 */
#define SPI_MOSI_0     nrf_gpio_pin_clear(MY_GPIO_PIN_mosi)        /* MOSI = 0 */

#define SPI_READ_MISO    nrf_gpio_pin_read( MY_GPIO_PIN_miso)    /* 读MISO口线状态 */

void SPI_IoInit(void)
{
   
    /* 配置输出引脚：CS, SCK, MOSI 为输出，默认高电平 */
    nrf_gpio_cfg_output(MY_GPIO_PIN_cs);
    nrf_gpio_cfg_output(MY_GPIO_PIN_sclk);
    nrf_gpio_cfg_output(MY_GPIO_PIN_mosi);

    /* 配置输入引脚：MISO 为输入，无上拉/下拉 */
    nrf_gpio_cfg_input(MY_GPIO_PIN_miso, NRF_GPIO_PIN_NOPULL);
    SPI_CS_1;
    SPI_SCK_1;
    k_sleep(K_MSEC(10));
    SPI_MOSI_0;
}
static volatile uint32_t spi_tx_data = 0;
static volatile uint32_t spi_rx_data = 0;
static volatile uint8_t spi_bit_pos = 0;
static volatile bool spi_state = false;  // false: prep (falling), true: sample (rising)
static volatile bool spi_transfer_complete = false;



//SPI可以同时读取和写入数据，因此一个函数即可满足要求
uint32_t SPI_ReadWriteByte(uint32_t txData)
{
  // 初始化状态
    spi_rx_data = 0;
    spi_bit_pos = 0;
    spi_state = false;
    spi_transfer_complete = false;
    spi_tx_data=txData;
    
    // CS low, initial SCK low, MOSI idle (will be set in first prep)
    SPI_CS_0;
    SPI_SCK_0;
    SPI_MOSI_0;  // Idle low

    NRF_TIMER2->EVENTS_COMPARE[0] = 0UL;  // 手动清事件（必须！）
    NRF_TIMER2->SHORTS = 0UL;             // 先清 SHORTS，避免预触发

  // 手动寄存器：设置 CC[0]=1 + SHORTS（自动清零）+ 中断使能 + 启动
    NRF_TIMER2->CC[0] = 15;                         // CC[0]=1 (125ns interval, 8 MHz events)
    NRF_TIMER2->SHORTS = (1UL << 0);               // SHORTS_COMPARE0_CLEAR (位0: 清零计数器)
    NRF_TIMER2->INTENSET = (1UL << 0);             // INTENSET_COMPARE0 (位0: 启用中断)
    NRF_TIMER2->TASKS_CLEAR = 1UL;                 // 清零计数器
    NRF_TIMER2->TASKS_START = 1UL;                 // 启动定时器

    // 等待传输完成（添加超时调试：避免无限挂）
    uint32_t timeout = 0;
    while (!spi_transfer_complete && timeout < 1000000) {  // ~1s 超时（调试用）
        __NOP();
        timeout++;
        if (timeout % 100000 == 0) {  // 每 10w 次检查
        }
    }
    if (timeout >= 1000000) {
        printk("SPI timeout! bit_pos=%d\n", spi_bit_pos);  // 调试：检查 ISR 执行
    }

  // 手动寄存器：停止定时器 + 清除
    NRF_TIMER2->TASKS_STOP = 1UL;                  // 停止
    NRF_TIMER2->TASKS_CLEAR = 1UL;                 // 清零
    NRF_TIMER2->INTENCLR = (1UL << 0);             // 禁用中断
  

    // CS high, SCK low, MOSI low
    SPI_SCK_0;
    SPI_CS_1;
    SPI_MOSI_0;

    return spi_rx_data;
    }

void TIMER2_IRQHandler(void)
{
    if (NRF_TIMER2->EVENTS_COMPARE[0]) {
        NRF_TIMER2->EVENTS_COMPARE[0] = 0;  // 清除事件

        if (spi_bit_pos < 32) {
            if (!spi_state) {
                // Prep phase (falling edge): Set MOSI for next bit, SCK low
                SPI_SCK_0;
                uint32_t tx_bit = (spi_tx_data >> (31 - spi_bit_pos)) & 1UL;
                if (tx_bit) {
                    SPI_MOSI_1;
                } else {
                    SPI_MOSI_0;
                }
                spi_bit_pos++;
                spi_state = true;  // Next: rising
            } else {
                // Sample phase (rising edge): Sample MISO, SCK high
                SPI_SCK_1;
                uint32_t miso_bit = SPI_READ_MISO;
                spi_rx_data |= (miso_bit << (31 - (spi_bit_pos - 1)));  // Shift into MSB first
                spi_state = false;  // Next: prep
            }
        } else if (spi_bit_pos == 32) {
            // Transfer done: extra tick to finalize
            SPI_SCK_0;
            spi_transfer_complete = true;
            spi_bit_pos++;  // Prevent re-entry
        }
    }
}

uint32_t SPI_ReadByte(uint32_t rxData)
{
    uint32_t answer;
    answer=SPI_ReadWriteByte(rxData);
    return answer;
}

void SPI_WriteByte(uint32_t txData)
{
    (void)SPI_ReadWriteByte(txData);
}

int main(void)
{

// 强制启动 HFCLK（Zephyr 默认管理，但 BLE 前确保）
NRF_CLOCK->TASKS_HFCLKSTART = 1UL;
while (!(NRF_CLOCK->EVENTS_HFCLKSTARTED));  // 等待 ~100us
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0UL;  // 清事件
k_sleep(K_USEC(500));  // 额外稳定 (XTAL 需 200-500 μs)

// 验证
uint32_t hfstat = NRF_CLOCK->HFCLKSTAT;
printk("HFCLKSTAT=0x%08X, Source=%u (expect 3=XTAL)\n", hfstat, (hfstat >> 16) & 0xFF);

// 手动初始化 TIMER2（全局，一次性：无 nRFx 依赖）
NRF_TIMER2->MODE = 0;                          // TIMER_MODE_TIMER (0)
NRF_TIMER2->PRESCALER = 0;                     // No prescaling, 16 MHz counter
NRF_TIMER2->BITMODE = 3;                       // TIMER_BITMODE_32Bit (3)

NRF_TIMER2->TASKS_CLEAR = 1UL;
NRF_TIMER2->TASKS_START = 1UL;

IRQ_CONNECT(TIMER2_IRQn, 6, TIMER2_IRQHandler, NULL, 0);  // 优先级6（中），flags=0
irq_enable(TIMER2_IRQn);  // 全局启用（代替NVIC_EnableIRQ）

}