5

我正在研究Arduino Mega 2560項目。在Windows 7 PC上,我使用的是Arduino1.0 IDE。我需要建立一個波特率爲115200的串行藍牙通信。當RX有數據時,我需要接收一箇中斷。我看到的每一段代碼都使用「輪詢」,這是在Arduino的循環內部放置一個Serial.available條件。如何在Arduino的循環中替換這種方法來實現中斷及其服務程序?似乎attachInterrupt()不提供這個用途。我依靠一箇中斷來喚醒Arduino從睡眠模式。Arduino串行中斷

我已經開發了應該打開連接銷13

#include <avr/interrupt.h> 
    #include <avr/io.h> 
    void setup() 
    { 
     pinMode(13, OUTPUT);  //Set pin 13 as output 

     UBRR0H = 0;//(BAUD_PRESCALE >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register 
     UBRR0L = 8; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register 
     UCSR0C |= (1 << UCSZ00) | (1 << UCSZ10); // Use 8-bit character sizes 
     UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Turn on the transmission, reception, and Receive interrupt  
    } 

    void loop() 
    { 
     //Do nothing 
    } 

    ISR(USART0_RXC_vect) 
    {  
     digitalWrite(13, HIGH); // Turn the LED on   
    } 

的問題是,子程序從未服LED這個簡單的代碼。

+0

你的問題與藍牙有什麼關係?好像你只是問如何使用帶有中斷的普通UART? – TJD 2012-04-18 22:46:18

回答

6

最後我發現了我的問題。我改變了中斷向量「USART0_RXC_vect」USART0_RX_vect。另外我加了interrupts();來啓用全局中斷,並且它工作得很好。

的代碼是:

#include <avr/interrupt.h> 
#include <avr/io.h> 
void setup() 
{ 
    pinMode(13, OUTPUT); 

    UBRR0H = 0; // Load upper 8-bits of the baud rate value into the high byte of the UBRR register 
    UBRR0L = 8; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register 
    UCSR0C |= (1 << UCSZ00) | (1 << UCSZ10); // Use 8-bit character sizes 
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Turn on the transmission, reception, and Receive interrupt  
    interrupts(); 
} 

void loop() 
{ 

} 

ISR(USART0_RX_vect) 
{ 
    digitalWrite(13, HIGH); // set the LED on 
    delay(1000);    // wait for a second 
} 

謝謝你的答覆!!!!

1

你有沒有試過這段代碼,它不起作用?我認爲問題在於你沒有打開中斷。您可以嘗試在setup函數中調用sei();interrupts();