使用定时器驱动WS2812
相当于手动更新CCR的值
特点:
- 定时器连续运行不中断,中间执行代码不影响计时精度
流程: - 重置CNT寄存器
- 启动定时器
- 设置输出高电平
- 计算CCR的值
等待CNT到达当前CCR计数器
/* 定时器频率 250Mhz,则TIMx->CNT每4ns就加一 如果需要延迟0.4us则需要100个定时器时钟 */ #define WS2812_T0H 100 #define WS2812_T1H 200 #define WS2812_T0L 212 #define WS2812_T1L 112 #define WS2812_RESET 12500 void Bsp_Ws2812Write(uint32_t* pdata, int length) { uint16_t count = 0; TIMx->CNT = 0; HAL_TIM_Base_Start(&htimx); PIN = 1; for (int i = 0; i < length; i++) { uint32_t data = *pdata++; for (int d = 0; d < 24; d++) { if (data & 0x800000) { /* 发送1 */ count += WS2812_T1H; while (TIMx->CNT - count > 0); PIN = 0; count += WS2812_T1L; while (TIMx->CNT - count > 0); PIN = 1; } else { /* 发送0 */ count += WS2812_T0H; while (TIMx->CNT - count > 0); PIN = 0; count += WS2812_T0L; while (TIMx->CNT - count > 0); PIN = 1; } data <<= 1; } } /* 复位 */ PIN = 0; count += WS2812_RESET; while (TIMx->CNT - count > 0); HAL_TIM_Base_Stop(&htimx); }