-8
#include <avr/io.h>
#include <stdint.h>

// Ceramic Resonator
#ifndef F_CPU
#define F_CPU 3686400 // 4MHz
#endif

// UART
#define UART_BAUD_RATE 9600
#define UART_BAUD_CALC(UART_BAUD_RATE,F_OSC) ((F_CPU)/((UART_BAUD_RATE)*16L)-1)

int main(void)
{
    // USART
    UBRR0H =(uint8_t) (UART_BAUD_CALC(UART_BAUD_RATE,F_CPU) >>8);
    UBRR0L =(uint8_t) UART_BAUD_CALC(UART_BAUD_RATE,F_CPU);

    UCSR0B = (1<<RXEN0) | (1<<TXEN0); // enable receiver and transmitter,
    UCSR0C = (3<<UCSZ00); // 8 bit (default: asynchronous, no parity, 1 stop-bit)

    DDRC = (1<<5); // set data direction register bit 5 to one, this means PC5 is configured as output
    PORTC = (1<<5); // set output value of PC5 to High-Level (Source Current, 5V to ground)
    // VARIABLES
    //uint8_t get;
    // PROGRAM

    unsigned char code[3] = {'x','y','z'}; // Here you need to write your code
    unsigned char rcv[3]={'0','0','0'}; // received data

    int i = 0;

    while(1)
    {
        i = 0;
        for(i=0;i<=2;i++)
        {
            // wait for empty transmit buffer
            //while (!(UCSR0A & (1<<UDRE0)));
            // wait for data to be received
            while (!(UCSR0A & (1<<RXC0)));
            /* put data into buffer, sends the data*/
            {  
                code[i]= UDR0  ;
            }

            PORTC ^= (1<<5); //this is for LED

            // get received data from buffer
            rcv[i] = code[i];
        }
        // wait for empty transmit buffer
        while (!(UCSR0A & (1<<UDRE0)));
        // put data into buffer, sends the data
        if ((rcv[0] == rcv[1]) && (rcv[0] == rcv[2]) && (rcv[1] == rcv[2]))
        UDR0 = 00;             
        else UDR0 = 01;
    }
}

这是我的程序,我将数据从 PC 发送到微控制器(Docklight 的 Atmega 168PA)。我发送三个相同的字节。然后微控制器必须比较它们并向我发送一个布尔值,指示它们是否相等(like 00)或不相等(like 01)。

下一个任务是验证错误发生在哪里或哪个字节是错误的。

同样,当微控制器接收到一个数据时,它会将三个字节存储为一个数据(data[i]),它只是重复三次。

因此,如果我以某种方式发送数据('18''19''18'),它必须告诉我错误发生在哪里......

4

1 回答 1

0

看起来你已经在 usart0 上设置了 usart,设置了波特率并启用了 tx 和 rx,没有奇偶校验和 1 个停止位。在 while 循环中,您使用无中断机制从 usart 读取缓冲区获取数据并检查某些条件并给出 01 或 00 作为输出。您应该尝试 UDR0 = 0x00 否则 UDR0 = 0x01;

于 2013-07-09T09:56:43.600 回答