c-AVR 9位Usart不工作(MPCM)



所以有主和从阁楼2313。主设备发送9位数据(第9位TXB8设置为1),但从设备没有检测到第9位(RXB8仍然为0)。我认为如果TXB8位设置在主设备中,那么从设备上的RXB8位应该自动设置,还是不自动设置?(在代码i中,检查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);
}

我发现了问题所在,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);

最新更新