1

PC から atmega16 にシリアルで 4 バイトのデータを送信しています。私はUARTを使用しています。1 つの手法は、データシートで指定された関数を使用することですが、ポーリングを使用するため、コードの残りの部分をブロックします。だから私はwhileループを使用しています。しかし、whileループが始まるときのコードの構造を理解できません..これで私を助けてください. thnx

#include <avr/io.h>
#define FOSC 1843200// Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1

void UART_Init( unsigned int ubrr)
{
/* Set baud rate */
UBRRH = (unsigned char)(ubrr>>8);
UBRRL = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSRB = (1<<RXEN);
/* Set frame format: 8data, 2stop bit */
UCSRC = (1<<URSEL)|(1<<USBS)|(3<<UCSZ0);
}

int main( void )
{   
int i = 0;
unsigned char my_data [4];

UART_Init ( MYUBRR );

while (1)
{   
    if (UCSRA & (1<<RXC)) 
    {
        my_data[i] = UDR;
    }
    i++;

    if (i == 3)
    {
        /*my next code here and once thats done, its again in uart receive mode*/
    i = 0;
    }
}
}
4

2 に答える 2

2

私はwhileループを取り、それらの横にコメントを付けたので、うまくいけばあなたはそれを理解します:)

while (1)
{   
    if (UCSRA & (1<<RXC)) //If Usart control and status register A and Receive complete flag are true (Comparing the register with the value of RXC, which is a bit in the register)
    {
        my_data[i] = UDR; //Read Usart Data Register, which is 1 byte
        i++; //Like Joachim Pileborg said, this should be in the if statement
    }

    if (i == 3) //If received your 4 bytes.
    {
        /*my next code here and once thats done, its again in uart receive mode*/
        //Do something with the data
        i = 0;
    }
}

今ははっきりしているといいのですが!ところで:あなたは今も常にデータをポーリングしているので、これはあなたが思っていたものと何ら変わりはありません。

于 2012-05-24T07:45:59.920 に答える
1

ブロッキングポーリングを使用したくない場合は、着信データの割り込み駆動処理を行う必要があります。基本的に、コードを含む RX-Complete-ISR を作成します。

    my_data[i] = UDR; //Read Usart Data Register, which is 1 byte
    i++; //Like Joachim Pileborg said, this should be in the if statement

sei();(当然、これがデータを受信できるようになる前に、一般的な割り込み ( ) と USART 受信完了割り込みをオンにする必要があります。)

次に、メインループで他のタスクを実行し、経由で確認できます

if (i == 3) //If received your 4 bytes.
{
    /*my next code here and once thats done, its again in uart receive mode*/
    //Do something with the data
    i = 0;
}

ISR がすべてのバイトを受信した場合。

i を として宣言するなど、同期の問題に注意を払う必要があるかもしれませんがvolatile、それが最もパフォーマンスの高い方法です。

于 2012-05-24T09:29:25.823 に答える