You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Arduino项目:8路LED循环4色的数组索引编程计算方案

Arduino LED循环颜色索引计算方案

你的核心问题是计算结果未对颜色数量(4)取模,导致超出了颜色数组的合法索引范围(0-3)。这里有两个简洁的数学解法:

解法1:基础修正版

把原公式的结果再对4取模,确保输出始终落在0-3之间:

(loop + (pixel % 4)) % 4

解法2:简化优化版

因为pixel % 4和pixel在模4运算中是等价的,所以可以进一步简化成:

(loop + pixel) % 4

验证示例

  • Loop 1时,LED3的计算:(1 + 3) % 4 = 4 % 4 = 0,符合期望
  • Loop 1时,LED7的计算:(1 + 7) % 4 = 8 % 4 = 0,符合期望
  • Loop 2时,LED2的计算:(2 + 2) % 4 = 4 % 4 = 0,符合期望
  • Loop 2时,LED3的计算:(2 + 3) % 4 = 5 % 4 = 1,符合期望

这个公式会直接生成你需要的索引序列:

  • Loop 0: 0,1,2,3,0,1,2,3
  • Loop 1: 1,2,3,0,1,2,3,0
  • Loop 2: 2,3,0,1,2,3,0,1
  • Loop 3: 3,0,1,2,3,0,1,2

Arduino代码示例

// 定义4种颜色(可根据实际需求修改)
const uint32_t colorArray[] = {0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00};
const int totalLEDs = 8;
const int totalColors = sizeof(colorArray) / sizeof(colorArray[0]);

void setup() {
  // 初始化LED驱动(比如FastLED库)
  // FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, totalLEDs);
}

void loop() {
  static int currentCycle = 0;

  for (int ledIndex = 0; ledIndex < totalLEDs; ledIndex++) {
    int colorIdx = (currentCycle + ledIndex) % totalColors;
    // 设置对应LED的颜色
    // leds[ledIndex] = colorArray[colorIdx];
  }
  
  // FastLED.show();
  currentCycle = (currentCycle + 1) % totalColors;
  delay(1000); // 控制循环切换速度
}

内容的提问来源于stack exchange,提问作者Robbert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:50:56