相当于arduino millis(); pic微控制器中的函数(返回通过时间)?

时间:2015-10-09 15:58:10

标签: arduino microcontroller pic

我有这个代码的相同情况它解决了我的问题(这段代码闪烁leds而不使用延迟函数阻止执行直到设定的时间已经过去)

我的问题是,在pic微控制器中,这个函数是否具有优势?

const int ledPin =  13;      
int ledState = LOW;            
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;           // interval at which to blink (milliseconds)

void setup()
{
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval)
    {
        previousMillis = currentMillis;  // save the last time you blinked the LED
        // if the LED is off turn it on and vice-versa:

        if (ledState == LOW)
        {
            ledState = HIGH;
        } 
        else 
        {
            ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
    }
}

我的问题是xc8编译器中有一个函数或lib来执行millis()函数的相同工作吗?

谢谢你。

2 个答案:

答案 0 :(得分:0)

没有明确的计时器功能。 但我正在考虑Time library,只是因为你的眨眼间隔设置为1000毫秒= 1秒。

实际上你可以单独构建一个函数,如果第二个消失,则返回“true”,并在调用函数后写入第二个参数。 如果秒数相同,则返回false,因此不要更改led的状态。 如果秒数不同,则返回true并更改led的状态。

例如,代码的结构将是这样的:

void loop()
{
    precSec = second();
    flag = secondIsGone(precSec);

    if (flag) {
      if (ledState == LOW) {
        ledState = HIGH;
        } 
        else {
            ledState = LOW;
        }
        digitalWrite(ledPin, ledState);
    }
} //loop

    boolean secondIsGone (int precSec) {
      if (precSec != second() ) {
         return true;
         }
         else {
           return false;
           }
    }

答案 1 :(得分:0)

实现此目的的最佳方法是始终使用Timer中断,因此您的程序在第二个运行时不会阻塞。在C-Compiler中,您必须执行以下操作:

#define tmr0 53036  //50ms with a 8MHz clock

#INT_TIMER0
void TIMER0()
{       
    static int counter = 20;
    set_timer0(tmr0);   //reload timer register
    if(counter-- == 0)
    {
        //1 sec.
        counter = 20;
        output_bit(PIN_B4,!input(PIN_B4));  
    }
}

void main()
{      
  //configurations here
  set_tris_b(0x00);  //0b00000000 
  setup_timer_0(RTCC_INTERNAL | RTCC_DIV_8);
  set_timer0(tmr0); //50ms : TMR0=65536 - overflow_time/(4*Tosc*prescaler)=53036 [in this case overflow_time=50ms, Tosc=1/8MHz=125ns, prescaler=8]
  //since TMR0=53036 -> overflow_time=(65536-TMR0)*(4*Tosc*prescaler)=(65536-53036)*(4*125ns*8)=50ms
  enable_interrupts(INT_TIMER0);
  enable_interrupts(GLOBAL);
  //********************************************

  while(true){...} //whatever you want
}