当我把" c"在setColor(c);
error: too few arguments to function 'void setColor(int, int, int)'
。
我明白我应该提出3个论点。我不明白的是,序列正确地显示了3个参数(255,000,000),所以为什么它一直告诉我这个错误。我做错了什么?
int rPin = 11;
int gPin = 9;
int bPin = 10;
void setup() {
Serial.begin(9600);
pinMode(rPin, OUTPUT);
pinMode(gPin, OUTPUT);
pinMode(bPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
delay(100);
while (Serial.available() > 0) {
char c = Serial.read(); // serial will display an rgb code, for exemple: 255, 000, 000 (red color)
setColor(c);
}
}
}
void setColor(int red, int green, int blue) {
analogWrite(rPin, red);
analogWrite(gPin, green);
analogWrite(bPin, blue);
}
答案 0 :(得分:0)
正如您的错误告诉您的那样,setColor(int red, int green, int blue)
需要3个您应该同时传递的参数。
问题在于,您从阅读Serial
端口而不是int
s但您所写字符的ASCII值(即0 = 48
)获得了参数。
因此,您需要使用Serial.parseInt()
来获取所需的实际值。
以下是您的代码应该是什么样的。
int rPin = 11;
int gPin = 9;
int bPin = 10;
void setup() {
Serial.begin(9600);
pinMode(rPin, OUTPUT);
pinMode(gPin, OUTPUT);
pinMode(bPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
delay(100);
while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();
// look for the newline. That's the end of your sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);
setColor(red, green, blue);
}
}
}
void setColor(int red, int green, int blue) {
analogWrite(rPin, red);
analogWrite(gPin, green);
analogWrite(bPin, blue);
}