AVR 9 位 Usart 不工作 (MPCM)
AVR 9 bit Usart not working (MPCM)
于是有了主从Attiny2313。 Master 发送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);
}
我找到问题所在了,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);
于是有了主从Attiny2313。 Master 发送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);
}
我找到问题所在了,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);