Arduino干簧管控制RGB LED:从黄渐变至红并熄灭实现求助
解决方案代码及说明
整合后的完整代码
const int reedPin = 2; const int rPin = 11; const int gPin = 10; const int bPin = 9; unsigned long lastUpdate = 0; const int fadeInterval = 30; // 渐变更新间隔(毫秒) const int fadeStep = 5; // 每次渐变的步长 // 当前RGB及亮度状态 int currentG = 255; int currentBrightness = 255; void setup() { pinMode(reedPin, INPUT_PULLUP); pinMode(rPin, OUTPUT); pinMode(gPin, OUTPUT); pinMode(bPin, OUTPUT); // 初始设置为黄色 analogWrite(rPin, 255); analogWrite(gPin, 255); analogWrite(bPin, 0); } void loop() { bool isMagnetNear = (digitalRead(reedPin) == LOW); if (isMagnetNear) { // 靠近磁场:保持恒定黄色,重置渐变状态 currentG = 255; currentBrightness = 255; analogWrite(rPin, 255); analogWrite(gPin, 255); analogWrite(bPin, 0); } else { // 远离磁场:渐变至红色并同时熄灭 unsigned long now = millis(); if (now - lastUpdate > fadeInterval) { lastUpdate = now; // 逐步降低G值(从黄转红) if (currentG > 0) { currentG -= fadeStep; currentG = max(currentG, 0); } // 逐步降低整体亮度(实现熄灭) if (currentBrightness > 0) { currentBrightness -= fadeStep; currentBrightness = max(currentBrightness, 0); } // 计算实际输出值:亮度按比例缩放RGB int outputR = map(currentBrightness, 0, 255, 0, 255); int outputG = map(currentBrightness, 0, 255, 0, currentG); analogWrite(rPin, outputR); analogWrite(gPin, outputG); analogWrite(bPin, 0); } } }
关键逻辑说明
- 干簧管检测:使用
INPUT_PULLUP模式,无需额外上拉电阻,磁场靠近时干簧管闭合,引脚输出LOW;远离时输出HIGH。 - 恒定黄色状态:当检测到磁场时,直接将RGB设置为纯黄色(R=255, G=255, B=0),同时重置渐变变量,确保下次远离时从正确状态开始。
- 渐变逻辑:远离磁场时,每30ms执行一次渐变操作:
- 逐步降低G值(从255到0),实现从黄色到红色的色调过渡。
- 同步降低整体亮度(从255到0),实现熄灭效果,两者同步完成,符合“渐变至红色并同时熄灭”的需求。
- 非阻塞设计:使用
millis()替代delay(),确保干簧管状态检测始终灵敏,不会因渐变延迟错过磁场靠近的信号。
代码整合思路
- 保留了你原代码中干簧管的
INPUT_PULLUP配置和非阻塞渐变的时间控制逻辑。 - 移除了第二段代码中无意义的循环渐变逻辑,替换为针对黄色→红色→熄灭的定向渐变逻辑。
- 将普通LED的单通道控制扩展为RGB三通道控制,针对黄色和红色的RGB特性(黄色是红+绿,红色是纯红)设计了G值递减的过渡方案。
内容的提问来源于stack exchange,提问作者Igne
相关产品推荐
相关产品推荐

