0

所以有主从Attiny2313。主机发送 9 位数据(第 9 位 TXB8 设置为 1),但从机没有检测到第 9 位(RXB8 仍为 0)。我认为如果在主设备中设置了 TXB8 位,则从设备上的 RXB8 位应该自动设置,或者不?(在代码中,我检查 UCSRB 中的 RXB8 是否设置为 1。事实并非如此,这就是问题所在)

void USART_Init(void)
{
    /* Set baud rate */
    UBRRH = (unsigned char)(BAUDRATE>>8);
    UBRRL = (unsigned char)BAUDRATE;

    /* Enable receiver and transmitter */
    UCSRB = (1<<RXEN)|(1<<TXEN);

    /* Set frame format: 9data, 1stop bit */
    UCSRC = (7<<UCSZ0);
}

void USART_Transmit(unsigned int data)
{
    /* Wait for empty transmit buffer */
    while ( !( UCSRA & (1<<UDRE)) );

    /* Copy 9th bit to TXB8 */
    UCSRB &= ~(1<<TXB8);
    if ( data & 0x0100 )
        UCSRB |= (1<<TXB8);

    /* Put data into buffer, sends the data */

    UDR = data;

//Slave Receive Code

gned int USART_Receive( void )
{
    unsigned char status, resh, resl;

    /* Wait for data to be received */
    while ( !(UCSRA & (1<<RXC)) );



    /* Get status and 9th bit, then data from buffer */
    status = UCSRA; 
    resh = UCSRB;
    resl = UDR;
        return resh; ///test
    /* If error, return -1 */
    if ( status & ((1<<FE)|(1<<DOR)|(1<<UPE)) )
    return -1;

    /* Filter the 9th bit, then return */
    resh = (resh >> 1) & 0x01;  
    return ((resh << 8) | resl);

}
4

1 回答 1

0

我发现了问题所在,USART 是这样初始化的:

/* Enable receiver and transmitter */
    UCSRB = (1<<RXEN)|(1<<TXEN);

    /* Set frame format: 9data, 1stop bit */
    UCSRC = (7<<UCSZ0);

但是 UCSZ2 位在 USCRB 寄存器中,而不在 UCSRC 中,所以正确的代码是:

UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<UCSZ2);
UCSRC  = (1<<UCSZ0)|(1<<UCSZ1);
于 2015-10-30T21:31:40.290 回答