【发布时间】:2016-05-10 11:26:38
【问题描述】:
我有一个带有 arduino UNO 和颜色传感器的程序,女巫向我展示了 RGB 值。 我也有一个按钮,女巫可能会开始读取一个对象(彩色纸),但是当我按下它时,程序会读取 5 次,而不是我想要的一次。 在每种情况下(对于每种颜色),我想为我想在串行监视器中显示的变量添加一个值,但是在读取(或 5 个读数:)))之后,串行监视器只显示我想要的值添加到我的变量中(例如 c=c+2;串行运动:每次按下按钮 2)。
这是我的代码:
// Define pins
const int ledpin = 13;
const int GSR1 = 12;
const int GSR0 = 11;
const int GSG1 = 10;
const int GSG0 = 9;
const int GSB1 = 8;
const int GSB0 = 7;
int redpin = A0;
int greenpin = A1;
int bluepin = A2;
const int buttonPin = 6;
// Sensor read values
int red = 0;
int green = 0;
int blue = 0;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ledpin, OUTPUT);
pinMode(GSR1, OUTPUT);
pinMode(GSR0, OUTPUT);
pinMode(GSG1, OUTPUT);
pinMode(GSG0, OUTPUT);
pinMode(GSB1, OUTPUT);
pinMode(GSB0, OUTPUT);
// Turn on the LED
digitalWrite(ledpin, HIGH);
// Set the gain of each sensor
digitalWrite(GSR1, LOW);
digitalWrite(GSR0, LOW);
digitalWrite(GSG1, LOW);
digitalWrite(GSG0, LOW);
digitalWrite(GSB1, LOW);
digitalWrite(GSB0, LOW);
}
void loop()
{
int buttonState;
buttonState = digitalRead(buttonPin);
// Read sensors
red = analogRead(redpin) * 10;
green = analogRead(greenpin) * 14;
blue = analogRead(bluepin) * 17;
int c=0;
int br=0;
if (buttonState == HIGH)
{
if (1200>red && red>1000 && 1950>green && green>1500 && 850>blue && blue>650)
{
Serial.print("yellow");
Serial.print("\n");
c=2;
}
if(c==2)
{
br=br+2;
Serial.print(br);
Serial.print("\n");
}
}
}
【问题讨论】:
-
确保按钮去抖动。
-
在你的代码中,你有
int br=0;insideloop()函数。因此,br在每次迭代中都重置为 0。在函数外部声明br看看是否有帮助。
标签: button colors arduino sensors arduino-uno