2016-12-16 85 views
0

我正在創建超聲波測距儀。我目前正在測試傳感器以確保其正常工作。我已分別將回顯引腳和觸發引腳連接到PC4和PC5。當我運行這個代碼時,理想情況下它會發送6到我的顯示器。但是,它顯示0.這導致我相信代碼與傳感器沒有正確連接。請幫忙。AVR中的超聲波傳感器

#define F_CPU 16000000UL 

#include <avr/io.h> 
#include <util/delay.h> 
#include <avr/interrupt.h> 

void DisplayIt(int i); 

int main(void) 
{ 

    while(1) 
    { 
     DDRC = 0xFF; 
     int i = 0; 
     PORTC = 0b00000000; 
     _delay_us(2); 
     PORTC = 0b00100000; 
     _delay_us(10); 
     PORTC = 0x00; 

     DDRC = 0x00; 
     if (PINC == 0b00010000) 
     { 
      i = 6; 
     } 
     DisplayIt(i); 
    } 

} 

回答

0

PINCPORTC是相同的寄存器。

PORTC = 0x00;在您閱讀之前將此寄存器的內容設置爲0。

+0

那麼,如何解決這個問題,因爲我需要明確的是,爲了阻止觸發? –

+2

您需要編輯您的問題以指示傳感器的類型。是HC-SR04嗎?在這種情況下,你正在閱讀回聲太早。請參考時序圖。觸發脈衝;等待脈衝發送;時間多長時間針高。在脈衝發送之前您正在讀取引腳。這就是爲什麼它仍然很低。這個傳感器有很多教程和代碼示例。 Sparkfun有一些Arduino的簡單代碼,可以適應,以及數據表。 – UncleO

0

我不知道您使用了什麼超聲波傳感器。但我認爲這是因爲你沒有等到傳感器收到它的回波信號。基於我曾經使用超聲波傳感器,SRF04,它具有這樣的時序圖:

enter image description here

我修改您的代碼,以便它必須打印「6」時,傳感器檢測的物體的能力它的前面(我們從回波信號的到來知道它)。

下面是代碼:

while(1) { 
    DDRC = 0xFF; // Configure all Port C pins as an output 
    int i = 0; 

    PORTC = 0b00100000; // Write 1 (high) to PORTC.5 (trigger pin) 
    _delay_us(10); // Keep PORTC.5 to give high signal output for 10us 
    PORTC = 0x00; // Write 0 (low) to PORTC.5 

    // The code above completes Trigger Input To Module (see Timing Diagram image) 

    DDRC = 0x00; // Configure all Port C pins as an input 
    while (PINC.4 == 0); // Wait until PINC.4 (echo pin) has 1 (high) value 
    if(PINC.4 == 1) i = 6; // Once PINC.4 is high, while loop will break and this line will be executed 

    DisplayIt(i); 

    _delay_ms(10); // Allow 10ms from End of Echo to Next Trigger Pulse 
}