avr 串口通信
这是用C写的程序,芯片是mega8,当上机位发送数据时,下机位无法接受到数据,经测试应该是没有产生(USART_RXC_vect)中断,而且下机位单纯的发送数据在上机位显示也不正确,至于发送的内容以及下机位在收到信息之后相关的逻辑处理在这里不详述,主要问题是现在下机位无法接收到数据以及发送数据在上机位不正确。求解。同时想知道这类问题如何进行调试,避免以后遇到类似的问题不会自己解决,谢谢了!下面是代码部分
#include <avr/io.h>串口通信
#include <avr/interrupt.h>
#define UART_BEGIN_STX 0xBB
#define UART_END_STX 0xEE
#define TX_BUFFER_SIZE 5
#define RX_BUFFER_SIZE 5
unsigned char tx_buffer[TX_BUFFER_SIZE];
unsigned char rx_buffer[RX_BUFFER_SIZE];
unsigned char rx_counter,tx_counter,tx_rd_index,tx_wr_index;
volatile unsigned char Uart_RecvFlag=0;
ISR(USART_TXC_vect)
{
if(tx_counter)
{
--tx_counter;
UDR=tx_buffer[tx_rd_index];
if(++tx_rd_index == TX_BUFFER_SIZE)
tx_rd_index=0;
}
}
void put_char(unsigned char c)
{
while(tx_counter == TX_BUFFER_SIZE);
cli();
if(tx_counter||((UCSRA&(1<<UDRE))== 0))
{
tx_buffer[tx_wr_index]=c;
if(++tx_wr_index == TX_BUFFER_SIZE)
tx_wr_index=0;
++tx_counter;
}
else
UDR=c;
sei();
}
ISR(USART_RXC_vect)
{
unsigned char status,data;
status=UCSRA;
data=UDR;
if(!Uart_RecvFlag)
{
if((status & ((1<<FE)|(1<<PE)|(1<<DOR)) )==0)
{
rx_buffer[rx_counter] =data;
rx_counter++;
switch(rx_counter)
{
case 1:
if(data!= UART_BEGIN_STX)
rx_counter=0;
break;
case 4:
if(data!=(rx_buffer[1]^rx_buffer[2]))
rx_counter=0;
break;
case 5:
rx_counter=0;
if(data == UART_END_STX)
Uart_RecvFlag=1;
break;
}
}
}
}
int main(void)
{
unsigned char channel=0x00;
unsigned char tx_1=0x00,tx_3;
DDRB |= 1<<5;
PORTB &= ~(1<<5);
DDRD &= ~(1<<2);
PORTD |= (1<<2);
UCSRA=0x00;
UCSRB=(1<<RXCIE)|(1<<TXCIE)|(1<<RXEN)|(1<<TXEN);
UCSRC=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
UBRRH=0x00;
UBRRL=0x19;
sei();
while(1)
{
if(Uart_RecvFlag)
{
switch(rx_buffer[1])
{
case 0xA0:
tx_1=0xB0;
if(PIND &(1<<2))
channel=0x40;
else
channel=0x00;
break;
case 0xA1:
tx_1=0xB1;
channel=0x01;
if(rx_buffer[2]==0)
PORTB &= ~(1<<5);
else
PORTB |= (1<<5);
break;
default:
tx_1=0x00;
channel=0x00;
break;
}
tx_3=tx_1^channel;
put_char(UART_BEGIN_STX);
put_char(tx_1);
put_char(channel);
put_char(tx_3);
put_char(UART_END_STX);
Uart_RecvFlag=0;
}
}
}