|
#include <mega168.h>
#define UART_BEGIN_STX 0xBB
#define UART_END_STX 0xEE
#define RXB80 1
#define TXB80 0
#define UPE0 2
#define DOR0 3
#define FE0 4
#define UDRE0 5
#define RXC0 7
#define FRAMING_ERROR (1<<FE0)
#define PARITY_ERROR (1<<UPE0)
#define DATA_OVERRUN (1<<DOR0)
#define DATA_REGISTER_EMPTY (1<<UDRE0)
#define RX_COMPLETE (1<<RXC0)
#define TX_BUFFER_SIZE 5
unsigned char tx_buffer[TX_BUFFER_SIZE]; // USART Transmitter buffer
unsigned char tx_wr_index,tx_rd_index,tx_counter;
// USART Transmitter interrupt service routine
interrupt [USART_TXC] void usart_tx_isr(void)
{
if (tx_counter)
{
--tx_counter;
UDR0=tx_buffer[tx_rd_index];
if (++tx_rd_index == TX_BUFFER_SIZE) tx_rd_index=0;
}
}
void putchar(unsigned char c)
{
while (tx_counter == TX_BUFFER_SIZE);
#asm("cli")
if (tx_counter || ((UCSR0A & DATA_REGISTER_EMPTY)==0))
{
tx_buffer[tx_wr_index]=c;
if (++tx_wr_index == TX_BUFFER_SIZE) tx_wr_index=0;
++tx_counter;
}
else
UDR0=c;
#asm("sei")
}
#define RX_BUFFER_SIZE 5
unsigned char rx_buffer[RX_BUFFER_SIZE]; // USART Receiver buffer
unsigned char rx_counter;
bit Uart_RecvFlag;
// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
unsigned char status,data;
status = UCSR0A;
data = UDR0;
if (!Uart_RecvFlag) // 判断是否允许接收一个新的数据包
{
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==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; // Uart_RecvFlag=1,表示正确接收到一个数据包
}
}
}
}
void main(void)
{
unsigned char channel = 0x07;
unsigned char tx_1,tx_3;
PORTB = ~(0x01<<channel);
UDR0=0xFF;
// USART initialization
UCSR0A=0x00; // Communication Parameters: 8 Data, 1 Stop, No Parity
UCSR0B=0xD8; // USART Receiver: On, USART Transmitter: On
UCSR0C=0x86; // USART Mode: Asynchronous, USART Baud Rate: 9600
UBRR0H=0x00;
UBRR0L=0x19;
#asm("sei") // Global enable interrupts
while (1)
{
if (Uart_RecvFlag)
{ // 有刚接收到数据包需要处理
tx_1 = 0x00;
switch (rx_buffer[1]) // 数据包处理过程
{
case 0xA0:
break;
case 0xA1:
if (rx_buffer[2]>=0x00 && rx_buffer[2]<=0x07)
{
channel = rx_buffer[2];
PORTB= ~(0x01<<channel);
}
else
tx_1 = 0x02;
break;
default:
tx_1 = 0x01;
break;
}
tx_3 = tx_1^channel;
putchar(UART_BEGIN_STX); // 发送回送数据包
putchar(tx_1);
putchar(channel);
putchar(tx_3);
putchar(UART_END_STX);
Uart_RecvFlag = 0; // 允许接收下一个数据包
}
}
} |
阿莫论坛20周年了!感谢大家的支持与爱护!!
曾经有一段真挚的爱情摆在我的面前,我没有珍惜,现在想起来,还好我没有珍惜……
|