知识点:
WS2812矩阵灯带
本课内容:
大家好,欢迎来到谷雨课堂,
灯是我们生活中最普通的事物之一,
由多个灯组成的灯条、灯带或点阵灯面,
也是生活常用的发光方式,
而你看到的这些灯,
很有可能是类似WS2812这样的灯珠组合而成,
WS2812B-5050是一个
集控制电路与发光电路于一体的智能外控LED光源;
其外型采用最新的molding封装工艺,
将IC与发光芯片封装在一个5050的封装尺寸中,
每个元件即为一个像素点;
像素点内部包含了智能数字接口数据锁存信号整形放大驱动电路,
还包含有高精度的内部振荡器和可编程定电流控制部分,
有效保证了像素点光的颜色高度一致。
首先,
我们还是打开VSCode,
使用PlatformIO平台,
本节我们使用“NeoPixelBus”这个库,
点击右边的Add Project就可以把库安装到相应的工程里了,
在下面的例程里,
就可以直接把源代码复制下来进行测试了,
不过在使用之前,
需要把WS2812灯带的电源、地和控制引脚安装正确
尤其是电源,
千万不要接反了
这个芯片的驱动需要使用严格的时序,
好在已经有很多成熟的库帮我们完成了这些工作
以下代码就是使用PlatformIO中自带的示例代码:
//谷雨课堂 No.10 控制WS2812灯带
const uint16_t PixelCount = 3; // 灯的数量
const uint8_t PixelPin = 2; // 连接的引脚
const uint8_t AnimationChannels = 1; // we only need one as all the pixels are animated at once
NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(PixelCount, PixelPin);
NeoPixelAnimator animations(AnimationChannels); // NeoPixel animation management object
boolean fadeToColor = true;
struct MyAnimationState
{
RgbColor StartingColor;
RgbColor EndingColor;
};
MyAnimationState animationState[AnimationChannels];
// 随机数
void SetRandomSeed()
{
uint32_t seed;
seed = analogRead(0);
delay(1);
for (int shifts = 3; shifts < 31; shifts += 3)
{
seed ^= analogRead(0) << shifts;
delay(1);
}
randomSeed(seed);
}
// simple blend function
void BlendAnimUpdate(const AnimationParam& param)
{
RgbColor updatedColor = RgbColor::LinearBlend(
animationState[param.index].StartingColor,
animationState[param.index].EndingColor,
param.progress);
for (uint16_t pixel = 0; pixel < PixelCount; pixel++)
{
strip.SetPixelColor(pixel, updatedColor);
}
}
void FadeInFadeOutRinseRepeat(float luminance)
{
if (fadeToColor)
{
RgbColor target = HslColor(random(360) / 360.0f, 1.0f, luminance);
uint16_t time = random(800, 2000);
animationState[0].StartingColor = strip.GetPixelColor(0);
animationState[0].EndingColor = target;
animations.StartAnimation(0, time, BlendAnimUpdate);
}
else
{
uint16_t time = random(600, 700);
animationState[0].StartingColor = strip.GetPixelColor(0);
animationState[0].EndingColor = RgbColor(0);
animations.StartAnimation(0, time, BlendAnimUpdate);
}
fadeToColor = !fadeToColor;
}
void setup()
{
strip.Begin();
strip.Show();
SetRandomSeed();
}
void loop()
{
if (animations.IsAnimating())
{
animations.UpdateAnimations();
strip.Show();
}
else
{
FadeInFadeOutRinseRepeat(0.2f);
}
}
这个库的使用方法很多,
可以实现非常多的效果,
甚至画出图片、播放动画也不在话下,
小伙伴们一定要多学多用,
看文档,动手实践!
完整的源代码可以登录【华纳网】下载。
https://www.worldwarner.com/
免责声明:本文仅代表作者个人观点,与华纳网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。