0
我正在制作Arduino程序,但无法使其工作。如何使用Arduino打开一定距离的LED
只要有人离开传感器5英寸,所有程序都会打开LED。问题是,无论什么时候,只要我启动程序,LED都会熄灭。这里是我的程序
const int pingPin =7 ;
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
long duration, inches, cm;
pinMode(pingPin,OUTPUT);
digitalWrite(pingPin,LOW);
delayMicroseconds(2);
digitalWrite(pingPin,HIGH);
delayMicroseconds(5);
digitalWrite(pingPin,LOW);
pinMode(pingPin,INPUT);
duration =pulseIn(pingPin,HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
while (true) {
if (inches <= 5) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
}
long microsecondsToInches(long microseconds)
{
return microseconds /74/2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds /29/2;
}
我该如何解决这个问题,使LED在正确的距离打开和关闭?
非常感谢!我不敢相信我没有看到 – Michaelslec 2012-07-31 06:06:56
现在唯一的问题是它随机闪烁,当它打开时,LED亮起并随机开始闪烁。 – Michaelslec 2012-07-31 06:13:53
闪烁是一个单独的问题。我不知道你使用的是什么样的传感器 - 所以可能存在核心问题(如何设置,读数有多大波动等)。怎么了延迟微秒+延迟(100)?我发现噪声传感器(或环境)有助于获取一些读数(每个'loop()')并将其平均以确定最终值。另外,打印语句需要一些时间来处理,以便进行真正的测试,并将其注释掉(除非它们对于您的项目是必需的)。 – 2012-07-31 06:25:19