【发布时间】:2020-02-12 02:25:12
【问题描述】:
代码示例用于使用一行 LED 创建一个二进制计数器。我正在查看一个将其作为挑战发布的在线教程。我的目标是以可扩展的方式做到这一点。
以下代码正在运行,但我有一个问题。在 setup 函数中,我调用了 Serial.begin 函数,我在编写代码时用于记录日志。实际上,代码从 0 循环到 16,闪烁正确的相应 LED。
当我删除 Serial.begin 行时,循环中断,但在一个奇怪的点。它一直到 16 次(即所有 4 个 LED 都亮起),然后循环回来,然后卡住仅闪烁一个 LED(指示 1)。对我来说令人费解的事情显然是因为循环从 0 开始,当它失败时它实际上正在经历循环的第二次迭代。
我没有使用任何其他串行函数,因为它与 Serial.begin 一起使用,我觉得它在数学上是合理的。这让我认为这是 Arduino 特有的东西,我真的很想了解这里发生了什么以产生不同的结果。
总的来说,我也是 C++ 和 Arduino 的新手,因此我们也非常感谢您提供一般性建议或反馈!
/*
* The following code runs an Arduino powering 4 LEDs counting in binary
* Mission was to do this dynamically using for-loops, so that it is scalable for adding say, more LEDs
* To add an LED, all one needs to do is update the variable 'bits', increase the size of the 'ledArray' and 'myArray' and assign Arduino pins to the new LEDs
*/
// using Arduino pins 3, 5, 6 & 9. While I'm using PWM pins, this code uses digital write and there's no need to stick to these for the purpose of this code
int led1 = 3;
int led2 = 5;
int led3 = 6;
int led4 = 9;
int bits = 4; // the number of bits AKA the number of LEDs in the circuit
int del = 350; // the interval for each flash
int topNumber = pow(2,bits); // define the decimal number that can be counted to on a given set.
int ledArray[4] = {led1, led2, led3, led4}; // this array is made up of the Arduino pins. The array size should be the same as the number of bits
int myArray[4] = {0}; // this array is the array that creates the binary string. The array size should be the same as the number of bits
void setup() {
Serial.begin(9600); // Getting some odd behaviour with this :/ originally here for troubleshooting
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}
void loop() {
// the following for-loop iterates each number in the set from 0 to the ceiling (topNumber)
for (int n = 0; n <= topNumber; n++) {
int tempValue = n; // set a temporary variable for n - we're going to manipulate n to format our binary, but we want to come back to this value before this loop concludes to increment on it
// the following for-loop builds an array to present the binary string eg 1,0,0,1 for 1001
for (int i = 0; n > 0; i++) {
myArray[i] = n % 2;
n /= 2;
}
// the following for-loop matches the leds in the ledArray with the binary array and sets the voltage high as required
for (int i = 0; i <= bits; i++) {
if(myArray[i] == 1) {
digitalWrite(ledArray[i], HIGH);
} else {
}
}
delay(del);
// the following for-loop iterates through the ledArray and switches them all off after completion
for (int i = 0; i <= bits; i++) {
digitalWrite(ledArray[i],LOW);
}
n = tempValue; // return n to its original value so that the for-loop will iterate as intended
}
}
【问题讨论】:
-
循环条件
i <= bits假设为i <bits。超出范围的数组访问正在发生 -
谢谢你,你说得对。即使在纠正了这个问题之后,虽然我得到了同样的问题行为,
Serial.begin(9600);的存在似乎与有关 -
不看minimum reproducible code很难说出原因
标签: c++ arrays for-loop arduino