我为Arduino Mega编写了代码来计算上升边缘出现在引脚2和3上的次数(中断)。当我将引脚4拉低时,我想从引脚2和3打印计数数一次,而不是多次。我编写了一个while循环,以确保在count_3 ==1时打印值,但即使count_3大于1时,值仍然打印。我不明白这怎么可能。我在while循环中打印了count_3的值,以表明它大于1,而当count_3大于1时它仍然打印。当count_3大于1时,它如何进入while循环?!我一定是错过了一些明显的东西。
long count_1 = 0; //interrupt counter 1
long count_2 = 0; //interrupt counter 2
int count_3 = 0; //counter to trigger serial print
void increment_1() { //1st ISR
count_1++;
}
void increment_2() { //2nd ISR
count_2++;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); // open the serial port at 9600 bps:
attachInterrupt(digitalPinToInterrupt(2), increment_1, RISING); //Enable Interrupt
attachInterrupt(digitalPinToInterrupt(3), increment_2, RISING); //Enable Interrupt
pinMode(4, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
int sensorVal = digitalRead(4); //read pin 4
if (sensorVal == LOW) {
count_3++; //increase count so program enters while loop once
}
while (count_3 == 1) {
count_3++; //increase count3 so it never prints again
Serial.println(count_3);
Serial.print('\n');
Serial.println(count_1);
Serial.print('\n');
Serial.println(count_2);
}
}发布于 2022-05-03 19:22:16
你的代码是:
在永无止境的循环中,
loop()一次又一次地被调用。sensorVal高,什么都不会发生,sensorVal下降到LOW,你必须知道需要多长时间。例如,1 secondcount_3在if语句中递增,然后在while语句中递增,有些数据是printed.count_3仅在if语句中递增。count_3的类型是int,所以每2^16(65536)增量溢出到0,然后又是1。while语句大约要打印两次,这与此无关。更好的方法是使用if语句错误方法
中断和主代码中使用的变量必须声明为volatile。这是对编译器的提示,说明变量可以随时更改,编译器不使用优化来访问变量。
volatile long count_1 = 0; //interrupt counter 1
volatile long count_2 = 0; //interrupt counter 2从主代码中访问ISR中更改的变量必须以原子方式进行。否则,错误的值可以读取到主代码。例如:
long count_1_copy;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
{
count_1_copy = count_1;
}https://stackoverflow.com/questions/72103263
复制相似问题