2017-02-28 90 views
-3

我目前正在開發一個項目,我們必須使用AVR ATMEGA328微控制器,特別是USART外設來控制8個LED。我們必須向微控制器發送命令,以便以不同的速率打開,關閉和閃爍LED。我已經用C編寫了一個程序,我認爲它可以完成這項工作,但我希望有人看一下它,並幫助我解決可能存在的任何錯誤。對你的幫助表示感謝!AVR USART編程

* P.S。命令數組中的每個命令都與LED陣列中相應的LED狀態相關聯。 LED連接到微控制器的PORTB。

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

/* Arrays that contain all input commands and LED states */ 
const char *commands[] = {"ON0","ON1","ON2","ON3","ON4","ON5","ON6","ON7","ON8","OFF0","OFF1","OFF2","OFF3","OFF4","OFF5","OFF6","OFF7","OFF8","BLINK0","BLINK1","BLINK2","BLINK3","BLINK4","BLINK5","BLINK6","BLINK7","BLINK8","STOP"\0} 
int LEDs[28] = {0X01,0X02,0X04,0X08,0X10,0X20,0X40,0X80,0XFF,0XFE,0XFD,0XFB,0XF7,0XEF,0XDF,0XBF,0X7F,0,0X01,0X02,0X04,0X08,0X10,0X20,0X40,0X80,0XFF,0} 

int i; 
int j; 

int Blinky(int j); // Function to execute blinking commands where j is the argument 
{ 
    PORTB = LEDs[j]; 
    _delay_ms[250 + (j-18) * 50]; /* Calculates blinking delay times */ 
    PORTB = 0; 
    _delay_ms[250 + (j-18) * 50]; 
} 

int main(void) 
{ 
    DDRB=0XFF; // PORTB is set to output 
    DDRD=0X02; // Turns on the transmit pin for the USART in PORTD 

    /* Setup USART for 9600,N,8,1 */ 
    USCR0B = 0X18; 
    USCR0C = 0X06; 
    UBRR0 = 51; 

    sei(); // Enable Global Interrupts 

    char input; 

    if(UCSR0A & 0X80) /* Reads data from the USART and assigns the contents to the character input */ 
     input = UDR0; 

    j=28; 

    char cmd; 
    cmd = *commands[i]; 

    for(i=0; i<28; i++) 
    { 
     if(input==cmd) /* If the contents of UDR0 are equal to one of the commands */ 
      j = i; 
    } 

    while(1) 
    { 
     if(j<18) 
      PORTB=LEDs[j]; // Executes the "ON" and "OFF" commands 

     else if(j<27) 
      Blinky(j); // Executes the blinking command by calling the Blinky function 

     else if(j=27) 
      PORTB=0; // Executes the "STOP" command 

     else 
      PORTB=0; // Accounts for typing errors 
    } 
    return(0); 
} 
+1

您應該在發佈之前測試您的代碼。如果它不起作用,請提供所有詳細信息,以便我們幫助您進行調試。如果它正在工作,您可以在https://codereview.stackexchange.com上發佈它,以獲得有關如何改進它的建議。 –

回答

1

這個程序有很多錯誤,但代碼審查不是Stack Overflow的目的。請參閱FAQ以瞭解如何提出適當的問題。

這就是說,一些顯而易見的問題是:

  • 的_delay_ms()函數需要一個編譯時常被調用。如果需要在運行時計算參數,它將無法正常工作。

  • 如果你沒有讀取USART中的任何字符,那麼你仍然會經歷其餘的循環。

  • char cmd聲明瞭一個字符變量,但是然後給它指定了一個指針。

  • i在它被設置爲有意義的值之前被使用。

  • input== cmd可能永遠不會是真的,因爲一邊是字符而另一邊是指針。

這個問題很快就會結束。祝你好運,如果你有更適合Stack Overflow的問題,請回來。

+0

感謝您的迴應!我理解你的意見。你會建議我做什麼? –