为什么这个 Arduino 代码不能正确褪色,而 Python 等效代码可以?

Why does this Arduino code not color-fade correctly, while the Python equivalent does?

我正在尝试为我的 Arduino Uno 编写一个程序,该程序使用 RGB LED 慢慢淡出不同的颜色。问题是,它不是慢慢褪色,而是快速闪烁几种不同的颜色,然后仅淡出几种颜色。然后它重复这种模式,但颜色不同。我写了 Python 等价物,它正常消失。

这是 Arduino 代码:

bool operation[3] = {false, true, false};

const int RLED = 11;
const int BLED = 9;
const int GLED = 10;

int rval = 1000;
int gval = 500;
int bval = 0;

void setup() {
  // Initialize the pins
  pinMode(RLED, OUTPUT);
  pinMode(BLED, OUTPUT);
  pinMode(GLED, OUTPUT);
}

void loop() {
  // Set whether we are adding or subtracting from the val variables
  // true is adding, false is subtracting
  if (rval >= 1000) operation[0] = false;
  else if (rval <= 0) operation[0] = true;
  if (gval >= 1000) operation[1] = false;
  else if (gval <= 0) operation[1] = true;
  if (bval >= 1000) operation[2] = false;
  else if (bval <= 0) operation[2] = true;

  // Add or subtract from the val variables, according to the bools
  if (operation[0]) rval++;
  else rval--;
  if (operation[1]) gval++;
  else gval--;
  if (operation[2]) bval++;
  else bval--;

  // Set the LED's color
  analogWrite(RLED, rval);
  analogWrite(BLED, bval);
  analogWrite(GLED, gval);
  delay(10);
}

这是 Python 等效项(使用 tkinter window 而不是 LED):

import time
import tkinter

root = tkinter.Tk()

rval = 1000
gval = 500
bval = 10
operation = [True, False, True]

def map(x, xmax, xmin, ymax, ymin):
    return ((ymax - ymin) / (xmax - xmin)) * x

while True:
    # Set whether we are adding or subtracting the val variables
    # True is adding, False is subtracting
    if rval >= 1000: operation[0] = False
    elif rval <= 0: operation[0] = True
    if gval >= 1000: operation[1] = False
    elif gval <= 0: operation[1] = True
    if bval >= 1000: operation[2] = False
    elif bval <= 0: operation[2] = True

    # Add or subtract from the val variables, according to the bools
    if operation[0]: rval += 1
    else: rval -= 1
    if operation[1]: gval += 1
    else: gval -= 1
    if operation[2]: bval += 1
    else: bval -= 1

    # Convert from RGB to hex. This is required to set the window's color
    rmapped = int(map(rval, 1000, 0, 255, 0))
    gmapped = int(map(gval, 1000, 0, 255, 0))
    bmapped = int(map(bval, 1000, 0, 255, 0))

    # Set the window's color
    root.config(bg="#%02x%02x%02x" % (rmapped, gmapped, bmapped))
    root.update()
    time.sleep(0.01)

我的问题:两者有什么区别?为什么 Arduino 代码不能正常运行,而 Python 代码可以?

事实证明,我认为 1024 是 Uno 的最大 analogWrite() 值,而实际上 255。循环运行完美;但只有当 val 变量小于或等于 255 时,灯光才会正确变暗。当 val 变量高于 255 时,颜色处于最大亮度;他们不能再亮了。因此,当 val 大于 255 时,颜色不会发生变化。这就是导致颜色闪烁的原因。

要解决此问题,只需将 Arduino 代码中出现的所有 1000 替换为 255