如何使用微控制器在C中实现中断标志?

时间:2019-05-22 02:34:04

标签: c microcontroller

我已经使用一个名为Thunderbird12的16位微控制器建立了一个项目,类似于9s12 / Freescale 68HC12系列。它做一些事情,但主要是打开外部水泵。一切正常,除了我需要实现一个中断。我希望能够通过按钮通过中断来停止电动机。

我已经设置了按钮,当按下该按钮时,会将端口P的引脚0设置为高电平。使用C,我已初始化硬件并编写了代码,但未调用该标志。请参见下面的代码。

function insertHTML(html, dest, append=false){
    // if no append is requested, clear the target element
    if(!append) dest.innerHTML = '';
    // create a temporary container and insert provided HTML code
    let container = document.createElement('div');
    container.innerHTML = html;
    // cache a reference to all the scripts in the container
    let scripts = container.querySelectorAll('script');
    // get all child elements and clone them in the target element
    let nodes = container.childNodes;
    for( let i=0; i< nodes.length; i++) dest.appendChild( nodes[i].cloneNode(true) );
    // force the found scripts to execute...
    for( let i=0; i< scripts.length; i++){
        let script = document.createElement('script');
        script.type = scripts[i].type || 'text/javascript';
        if( scripts[i].hasAttribute('src') ) script.src = scripts[i].src;
        script.innerHTML = scripts[i].innerHTML;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    // done!
    return true;
}

如果我将这段代码// Interrupt function int interruptFlag; void interrupt 56 WaterPumpRoutine() { if ((PIFP & 0x01) == 0x01) { // check if pin 0 of port p is high (when button is pressed) interruptFlag = 1; // set the flag to 1 } // Main void main() { DDRP = 0x00; // set port P as input PIEP = PIEP | 0x01; // enable interrupts on port P, pin 0 PERP = PERP | 0x01; // enable pull-up/down on port P, pin 0 if ( interruptFlag == 1) PORTB = (PORTB & 0x00) // Here I'm turning off all the pins in Port B, which includes the pump. } 放在PORTB = (PORTB & 0x00)函数中,它可以正常工作,但是我需要能够在任何地方调用该标志。我不确定我缺少什么。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

假设中断调用正常。.

  1. 将变量int interruptFlag;更改为volatile int interruptFlag;。这是为了避免编译器优化掉main中的if条件。
  2. main中,您需要在某些情况下重置interruptFlag。这取决于程序。也许您可以这样做。

    if ( interruptFlag == 1)
    {
          PORTB = (PORTB & 0x00) // Here I'm turning off all the pins in Port B, which includes the pump.
          interruptFlag = 0;
    }
    
  3. 如果使用的是按钮,则应引入一种去抖机制,以避免检测到多个输入。

  4. 您需要在while(1)循环内的main中添加if条件,因为中断随时可能出现。

    while(1)
    { 
        if(interruptFlag == 1)
        {
            ...
        }
    }
    

答案 1 :(得分:0)

如果您仍然无法触发中断,在提出其他建议之后,您应该检查是否已启用全局中断或已启用特定部分的中断(GPIO),因为在大多数uc中,设置GPIO不会生成中断中断