所以,我在这里有我的程序,我正在尝试制作一个程序,我们手动将导线拉出并放回去,每次将其拉出时,它是1次迭代,然后再放回1次迭代中。只要将其连接到端口,外部LED就会变暗;将其拔出时,外部LED就会变亮。我应该能够执行10次迭代,并在到达那里后停止。
问题是,当我包含while(true)时;语句中,我的外部LED不起作用,但是如果没有该语句,该程序将按照我想要的方式运行,除了它在10次迭代后不会停止工作之外,对此不胜感激!
#include<EEPROM.h>
const int LED = 12;
const int SWITCH = 4;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(LED, OUTPUT); //LED is always outputting information
pinMode(LED_BUILTIN, OUTPUT); //Built in LED is always outputting information
pinMode(SWITCH, INPUT_PULLUP); //Switch inputs value when in/out of ground
}
void loop() {
// put your main code here, to run repeatedly:
int addr = 0; //Declaring variables
int count = 0;
int seconds;
if (digitalRead(SWITCH) == LOW) { //If wire starts in ground, record values
Serial.println("----Recording----");
while (count <= 10) { //While count value is less than or equal to 10
if (digitalRead(SWITCH) == LOW) { //When wire is connected to 4
count = count + 1; //Add one to count in each iteration
digitalWrite(LED, LOW); //LED light is off in this position
delay(50); //Checks switch state every 0.05 seconds
}
else if (digitalRead(SWITCH) == HIGH) { //When wire isnt connected to 4
count = count + 1; //Add one to count in each iteration
digitalWrite(LED, HIGH); //LED light is on in this position
delay(50); //Checks switch state every 0.05 seconds
}
while (true);
}
}
}
答案 0 :(得分:0)
为什么不起作用?让我们稍微重写一下代码:
while (count <= 10) {
count = count + 1;
digitalWrite(LED, digitalRead(SWITCH));
delay(50);
while (true); // aaand kill it
}
如果第一个数字读取返回HIGH,然后第二个数字返回LOW(它不会等待50ms停止),则我忽略了竞争条件
我希望像指望针脚变化这样的东西:
while (count <= 10) {
byte = digitalRead(SWITCH);
if (byte != digitalRead(LED))
{
count = count + 1;
digitalWrite(LED, byte);
}
delay(50);
}
while (true); // aaand kill it