2016-11-09 346 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微秒

這應該讓你開始。