首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Arduino系列打印一次:而循环不工作?

Arduino系列打印一次:而循环不工作?
EN

Stack Overflow用户
提问于 2022-05-03 17:29:25
回答 1查看 161关注 0票数 0

我为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循环?!我一定是错过了一些明显的东西。

代码语言:javascript
运行
复制
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);
  }

}
EN

Stack Overflow用户

发布于 2022-05-03 19:22:16

你的代码是:

在永无止境的循环中,

  1. loop()一次又一次地被调用。
  2. ,如果sensorVal高,什么都不会发生,
  3. ,如果sensorVal下降到LOW,你必须知道需要多长时间。例如,1 second
  4. count_3if语句中递增,然后在while语句中递增,有些数据是printed.
  5. next时间count_3仅在if语句中递增。count_3的类型是int,所以每2^16(65536)增量溢出到0,然后又是1。
  6. 在1s中执行了多少次增量?估计一个循环持续时间为10次,因此它是100000次增量.这意味着每个second
  7. while语句大约要打印两次,这与此无关。更好的方法是使用if语句

错误方法

中断和主代码中使用的变量必须声明为volatile。这是对编译器的提示,说明变量可以随时更改,编译器不使用优化来访问变量。

代码语言:javascript
运行
复制
volatile long count_1 = 0;     //interrupt counter 1
volatile long count_2 = 0;     //interrupt counter 2

从主代码中访问ISR中更改的变量必须以原子方式进行。否则,错误的值可以读取到主代码。例如:

代码语言:javascript
运行
复制
    long count_1_copy;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
        count_1_copy = count_1;
    }
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72103263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档