2016-11-09 337 views
0

我在微处理器类中,我们正在编写自己的延迟函数,它们实际上是精确的。我们的教授给了我们,我认为是4毫秒延迟功能。我真的不知道如何将它转换为0.25秒或1秒的延迟,这对于我的作业来说都是需要的。使用arduino IDE的自定义延迟功能

给定的功能如下(假设_BV()被定义为_BV(x)的1 < <(X)):

DDRB |= _BV(1); 
TCCR1A |= _BV(COM1A0); 
TCNT1 = 0; 
OCR1A = 100; 
TIFR1 = _BV(OCF1A); 
TCCR1B |= _BV(CS10); 
while((TIFR1 & _BV(OCF1A)) == 0); 

TIFR1 = _BV(OCF1A); 
OCR1A = 100 + 64000; 
while((TIFR1 & _BV(OCF1A)) == 0); 
TCCR1B = 0; 
TCCR1A = 0; 

我写完成除作业所需的代码两个延迟功能。

这是我到目前为止有:

#include <avr/io.h> 

uint8_t numIN; 

void setup() { 
    Serial.begin(9600); 

    DDRB |= _BV(5); 
} 

void loop() { 
    int i; 

    numIN = 10; 

    Serial.println("Enter a number between 0 and 9."); 

    do { 
    while (Serial.available() > 0) 
    { 
     numIN = Serial.read() - '0'; 
     if (numIN < 0 || numIN > 9) 
     { 
     Serial.println("Input Error!"); 
     } 
    } 
    } while (numIN < 0 || numIN > 9); 

    Serial.print("You entered "); 
    Serial.println(numIN); 

    if (isEven(numIN)) 
    { 
    for (i = 0; i < 5; i++) 
    { 
     PORTB |= _BV(5); 
     delay(1000); //temporary 
     //delay_Sec(); 
     PORTB &= ~_BV(5); 
     delay(1000); //temporary 
     //delay_Sec(); 
    } 
    } 

    else 
    { 
    for (i = 0; i < 5; i++) 
    { 
     PORTB |= _BV(5); 
     delay(250); //temporary 
     //delay_quarterSec(); 
     PORTB &= ~_BV(5); 
     delay(250); //temporary 
     //delay_quarterSec(); 
     } 
    } 
} 

void delay_quarterSec(void) 
{ 
    //need to finish 
} 

void delay_Sec(void) 
{ 
    //need to finish 
} 

boolean isEven(int num) 
{ 
    if (num & _BV(0)) 
    return false; 

    else 
    return true; 
} 

我只是困惑我怎么把我的教授的代码,并将其转移到什么,我需要做的。任何帮助是极大的赞赏!

+0

所以你会在你的草图中使用AVR寄存器吗? – cagdas

回答

4

我可以简单介绍一下提供的代码的功能。

(这是从内存,所以不要把我的话,而且你不提你的控制器类型。你将不得不查找寄存器了详细介绍。)

DDRB |= _BV(1);   // set the compare match output pin to output 
TCCR1A |= _BV(COM1A0); // enable output compare PIN toggle 
TCNT1 = 0;    // set counter start value to 0 
OCR1A = 100;   // set compare match value to 100 (the actual delay) 
TIFR1 = _BV(OCF1A);  // clear the output compare flag 
TCCR1B |= _BV(CS10); // enable the timer by setting the pre-scaler 
while((TIFR1 & _BV(OCF1A)) == 0); // wait until the timer counted to 100 (compare flag is set again) 

因此,实际延迟取决于:

  • 预分频器的设置
  • 控制器
  • OCR1A
  • 价值的时钟速度

例:
如果分频器设置为1,您在10MHz运行,你得到了
T =(1 /(10000000 /秒))* 100 = 10微秒

这应该让你开始。