代码之家  ›  专栏  ›  技术社区  ›  Daniel

avr中断变量在main中更新

  •  0
  • Daniel  · 技术社区  · 7 年前

    使用8位avr微型机,我到达了一个简单的情况,这可能不是很容易解决。

    请考虑以下片段:

    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)如果我使用 ATOMIC_BLOCK(ATOMIC_RESTORESTATE) 在主FN中,我可以避免在(1)中声明的问题,但它可能会发生,我错过了ISR,因为在这种情况下,在短时间内禁用。

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   vega8 uncleO    7 年前

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

    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);
    }