闪烁的光代码中的Arduino上的未知错误
我正在尝试创建这个项目,以便不断闪烁,然后使用以下新等待时间打印毫秒:100 (例如)
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
static int delayPeriod = 100;
int countDir = 1;
digitalWrite(ledPin, HIGH);
delay(delayPeriod);
digitalWrite(ledPin, LOW);
delay(delayPeriod);
countDir = checkDirChange(delayPeriod, countDir);
Serial.println("New wait time: ");
Serial.print(delayPeriod);
delayPeriod += 100 * countDir;
}
int checkDirChange(int delayPeriod, int countDir) {
if ((delayPeriod == 100) || (delayPeriod == 0)) {
countDir *= -1;
if (countDir < 0) {
Serial.println("Going down.");
} else {
Serial.println("Succesful");
}
return countDir;
}
}
I'm trying to create this project so a light blinks constantly and then it prints the milliseconds with the following New wait time: 100(for example)
const int ledPin = 13;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
static int delayPeriod = 100;
int countDir = 1;
digitalWrite(ledPin, HIGH);
delay(delayPeriod);
digitalWrite(ledPin, LOW);
delay(delayPeriod);
countDir = checkDirChange(delayPeriod, countDir);
Serial.println("New wait time: ");
Serial.print(delayPeriod);
delayPeriod += 100 * countDir;
}
int checkDirChange(int delayPeriod, int countDir) {
if ((delayPeriod == 100) || (delayPeriod == 0)) {
countDir *= -1;
if (countDir < 0) {
Serial.println("Going down.");
} else {
Serial.println("Succesful");
}
return countDir;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您不是在问一个问题。您面临的确切问题是什么?
其次,您的逻辑没有意义。您正在创建负值,并将其分配为显然不正确的延迟。您想实现什么?
这:
在第二次迭代后将变为负面。之后,代码将行为不稳定。
这是Codelite中代码的快速 dirty 测试(我只是通过系统暂停模拟延迟,并且还使用简短模仿 loop() loop):
请澄清您的代码目的。
我强烈鼓励您使用
millis()
功能作为定时事件的适当方法。请参阅 this 指南P.S.是的,我保证我会很快激活我的Windows ;)
First of all, you are NOT asking a question. What is the exact problem you are facing?
Second, your logic doesn't make sense. You are creating negative values and assigning them as delays which is evidently incorrect. What are you trying to achieve with it?
This:
will become negative after the second iteration. After this, the code will behave erratically.
This is a quick and dirty test of your code in Codelite (where I just emulated the delays by system pauses and also emulated the loop() using a short while loop):
Please clarify the purpose of your code.
I highly encourage you to use the
millis()
function as a proper approach for timing events. Please refer to this guideP.S. Yeah, I promise I will activate my Windows very soon ;)