源代码
时间: 2023-08-03 17:03:02 浏览: 120
PythonWeb开发案例教程_源代码.zip
5星 · 资源好评率100%
以下是一个基于Arduino单片机的LED彩灯控制器的例程代码,您可以根据自己的需求进行修改和优化:
```C++
#include <FastLED.h>
//定义LED灯的数量和引脚
#define LED_COUNT 8
#define DATA_PIN 6
//定义彩灯的4种花样
#define PATTERN_1 0
#define PATTERN_2 1
#define PATTERN_3 2
#define PATTERN_4 3
//定义彩灯花样变换的快慢节拍
#define MANUAL_MODE_TIME 50
#define AUTO_MODE_TIME 15000
//定义控制器的复位清零开关引脚
#define RESET_PIN 7
//定义彩灯的颜色
CRGB leds[LED_COUNT];
//定义当前彩灯花样和变换模式
int currentPattern = PATTERN_1;
int currentMode = AUTO_MODE;
//定义彩灯花样变换的计时器和标记
unsigned long patternTimer = 0;
bool patternChanged = false;
//定义彩灯花样变换的节拍标记
bool tick = false;
//初始化LED灯
void setup() {
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, LED_COUNT);
pinMode(RESET_PIN, INPUT_PULLUP);
}
//循环控制程序
void loop() {
//检测复位清零开关是否按下
if (digitalRead(RESET_PIN) == LOW) {
resetController();
}
//根据当前模式选择花样变换的方式
if (currentMode == MANUAL_MODE) {
manualPatternChange();
} else {
autoPatternChange();
}
//根据当前花样和标记设置LED灯的颜色
switch(currentPattern) {
case PATTERN_1:
if (tick) {
for (int i = 0; i < LED_COUNT; i++) {
leds[i] = CRGB::Red;
}
} else {
for (int i = 0; i < LED_COUNT; i++) {
leds[i] = CRGB::Green;
}
}
break;
case PATTERN_2:
if (tick) {
for (int i = 0; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Red;
leds[i+1] = CRGB::Green;
}
} else {
for (int i = 0; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Green;
leds[i+1] = CRGB::Red;
}
}
break;
case PATTERN_3:
if (tick) {
for (int i = 0; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Red;
}
for (int i = 1; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Green;
}
} else {
for (int i = 0; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Green;
}
for (int i = 1; i < LED_COUNT; i+=2) {
leds[i] = CRGB::Red;
}
}
break;
case PATTERN_4:
if (tick) {
for (int i = 0; i < LED_COUNT; i++) {
leds[i] = CRGB::White;
}
} else {
for (int i = 0; i < LED_COUNT; i++) {
leds[i] = CRGB::Black;
}
}
break;
}
//设置LED灯的颜色
FastLED.show();
//根据当前节拍标记更新计时器
if (tick) {
patternTimer += MANUAL_MODE_TIME;
} else {
patternTimer += AUTO_MODE_TIME;
}
//根据计时器的值更新节拍标记
if (patternTimer >= AUTO_MODE_TIME || patternChanged) {
patternTimer = 0;
tick = !tick;
patternChanged = false;
}
}
//手动模式下的花样变换
void manualPatternChange() {
//检测手动按键是否按下
if (digitalRead(MANUAL_BUTTON_PIN) == LOW) {
patternChanged = true;
currentPattern++;
if (currentPattern > PATTERN_4) {
currentPattern = PATTERN_1;
}
delay(50);
}
}
//自动模式下的花样变换
void autoPatternChange() {
patternChanged = true;
currentPattern++;
if (currentPattern > PATTERN_4) {
currentPattern = PATTERN_1;
}
}
//控制器复位清零
void resetController() {
currentPattern = PATTERN_1;
currentMode = AUTO_MODE;
patternTimer = 0;
patternChanged = false;
tick = false;
}
```
请注意,这只是一个简单的例程,您可能需要根据自己的具体需求进行修改和优化。此外,您还需要根据自己的硬件电路和接线情况进行相应调整。
阅读全文