STC15W204是8PIN的宽电压版,驱动WS2812的时候单片机可以用5V电压,也可以用3.3V的电源。
RGB灯条的电源应该是4-7V之间,目前驱动的是8颗粒的灯条,原则上应该可以驱动更多颗粒的,不过手头没有那么长的,没试过,有兴趣的朋友可以自己试验,看看最多可以驱动多少个。按理论来讲驱动8颗和80颗应该是一样的。
硬件环境:
单片机:STC15W204S(SOP8)
灯带:WS2812(8颗粒)
非必需品:开关,USB转接板,面包板,跳线若干。
使用片内R/C振荡器,连外部晶振都不需要,工作频率为11.0592MHz
STC15W204S可以用其他其他STC 1T的MCU。
代码也非常简单,只用到1个IO口,不需要进行任何初始化。
如果使用其他工作频率时,请相应调整DELAY_LONG和DELAY_SHORT的宏定义,适当增减_nop()_的个数,直到能正确驱动灯条为止。
单片机源程序如下:
- #include <reg51.h>
- #include <intrins.h>
- // 使用的IO口,无需初始化
- sbit DOUT = P3^3;
- #define DELAY_LONG {_nop_();_nop_();_nop_();}
- #define DELAY_SHORT {_nop_();_nop_();}
- #define SEND_1 {DOUT=1;DELAY_LONG;DOUT=0;DELAY_SHORT;}
- #define SEND_0 {DOUT=1;DELAY_SHORT;DOUT=0;DELAY_LONG;}
- #define SEND_BIT(x) {if(x) {SEND_1;} else {SEND_0;}}
- // WS2812灯带颗粒数
- #define PIXEL_CNT (8)
- // RGB颗粒结构
- typedef struct {
- unsigned int next_pixel; // 下一颗粒的index
- unsigned char green; // 绿色值
- unsigned char red; // 红色值
- unsigned char blue; // 蓝色值
- unsigned char brightness; // 亮度值
- } Pixel;
- void send_p(Pixel _p); // 发送1个颗粒的值
- void send_pixels(Pixel *_p_list, unsigned int _start, unsigned int _cnt); // 发送所有颗粒的值
- // 各颗粒值的初始值
- Pixel pixels[PIXEL_CNT] = {
- {1, 31, 255, 127, 255},
- {2, 31, 255, 127, 127},
- {3, 31, 255, 127, 31},
- {4, 31, 255, 127, 7},
- {5, 31, 255, 127, 1},
- {6, 31, 255, 127, 0},
- {7, 31, 255, 127, 0},
- {0, 31, 255, 127, 0},
- };
- // 通用计数器
- unsigned int cnt = 0;
- // 指定毫秒数Delay
- void delay_ms(unsigned int x) //@11.0592MHz
- {
- unsigned char i, j;
- do {
- _nop_();
- _nop_();
- _nop_();
- i = 11;
- j = 190;
- do
- {
- while (--j);
- } while (--i);
- } while (--x);
- }
- // 主函数
- void main() {
- // 初始化段
-
- // 循环处理段
- while(1) {
- // 等待50ms
- delay_ms(50);
- cnt %= 0x100;
- send_pixels(pixels, cnt % PIXEL_CNT, PIXEL_CNT);
- cnt++;
- }
- }
- void Delay50us() //@11.0592MHz
- {
- unsigned char i, j;
- _nop_();
- i = 1;
- j = 134;
- do
- {
- while (--j);
- } while (--i);
- }
- // RESET信号
- void reset() {
- DOUT = 0;
- Delay50us();
- }
- void send_p(Pixel _p) {
- unsigned char p_v;
- p_v = (_p.green * _p.brightness) >> 8;
- SEND_BIT(p_v & 0x80);
- SEND_BIT(p_v & 0x40);
- SEND_BIT(p_v & 0x20);
- SEND_BIT(p_v & 0x10);
- SEND_BIT(p_v & 0x08);
- SEND_BIT(p_v & 0x04);
- SEND_BIT(p_v & 0x02);
- SEND_BIT(p_v & 0x01);
- p_v = (_p.red * _p.brightness) >> 8;
- SEND_BIT(p_v & 0x80);
- SEND_BIT(p_v & 0x40);
- SEND_BIT(p_v & 0x20);
- SEND_BIT(p_v & 0x10);
- SEND_BIT(p_v & 0x08);
- SEND_BIT(p_v & 0x04);
- SEND_BIT(p_v & 0x02);
- SEND_BIT(p_v & 0x01);
- p_v = (_p.blue * _p.brightness) >> 8;
- SEND_BIT(p_v & 0x80);
- SEND_BIT(p_v & 0x40);
- SEND_BIT(p_v & 0x20);
- SEND_BIT(p_v & 0x10);
- SEND_BIT(p_v & 0x08);
- SEND_BIT(p_v & 0x04);
- SEND_BIT(p_v & 0x02);
- SEND_BIT(p_v & 0x01);
- }
- void send_pixels(Pixel *_p_list, unsigned int _start, unsigned int _cnt) {
- Pixel *_p = &_p_list[_start % _cnt];
- reset();
- while(_cnt--) {
- send_p(*_p);
- ……………………
- …………限于本文篇幅 余下代码请从51黑下载附件…………
复制代码
所有资料51hei提供下载:
WS2812B.zipWS2812B.zip
(29.26 KB, 下载次数: 493)
|