gpt4 book ai didi

c - AVR 中断的变量在 main 中更新

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:19 24 4
gpt4 key购买 nike

使用 8 位 AVR micro,我遇到了一个可能不太容易解决的简单情况。

考虑以下片段:

static volatile uint8_t counter;

//fires often and I need all the values of the counter.
void isr(void) {
counter++;
}

int main (void) {

while(1) {
send_uart(counter);
counter = 0;
delay_ms(1000); //1 sec pause
}

return 0;
}

1.) 可能会发生 send_uart 后跟一个增加计数器的 isr,然后下一条语句将其清零。因此我会错过计数器的一个数据。

2.) 如果我在主 fn 中使用 ATOMIC_BLOCK(ATOMIC_RESTORESTATE),我可以避免 (1) 中声明的问题,但是我可能会错过 ISR,因为在这种情况下是 INT被短时间禁用。

有没有更好的方法将信息从主 fn 传递到 ISR?

最佳答案

如果对计数器进行采样而不是重置,则不会有任何时序问题。发送时发生的增量将在下一次迭代中说明。计数器变量的无符号数据类型将保证明确定义的溢出行为。

uint8_t cs = 0;                  // counter sample at time of sending
uint8_t n = 0; // counter as last reported

while (1) {
cs = counter; // sample the counter
send_uart((uint8_t)(cs - n)); // report difference between sample and last time
n = cs; // update last reported value
delay_ms(1000);
}

关于c - AVR 中断的变量在 main 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53681256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com