在决定时发现错误

时间:2013-07-09 08:11:04

标签: c microcontroller atmega

#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)。我发送三个相同的字节。然后微控制器必须比较它们并向我发送一个布尔值,指示它们是否相等(如00)或不同(如01)。

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

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

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

1 个答案:

答案 0 :(得分:0)

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