|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
#include "c8051f040.h"
#include "UART.h"
unsigned char uart_recv_state;
unsigned char uart_recv_cnt;
unsigned char uart_txd_cnt;
UART_CMD uare_cmd;
unsigned char xdata coma_rxd_buff [ 10 ] ;
unsigned char xdata coma_txd_buff [ 10 ] ;
void SYSCLK_Init (void)
{
int i; // 延时计数器
SFRPAGE = CONFIG_PAGE;
OSCXCN = 0x67; // 使用外部22.1184MHz晶振
for(i=0; i<3000; i++); // 等待1ms
while ((OSCXCN & 0x80) == 0); // 等待外部振荡器稳定
CLKSEL = 0x01; //系统时钟不分频
}
void PORT_Init (void)
{
SFRPAGE = CONFIG_PAGE;
XBR0 = 0x05; //设置XBR0,CP0,CEX0,UART0,SPI,SMBUS连接到端口引脚
XBR1 = 0x00; //
XBR2 = 0x44; //打开交叉开关和弱上拉,连接UART1到端口引脚
P0MDOUT = 0x00; //设置P0口输出
P2MDOUT = 0x00; //设置P2口输出
P4MDOUT = 0x00;
P5MDOUT = 0x00;
P6MDOUT = 0x00;
P7MDOUT = 0x00;
P1MDIN = 0x00; //P1端口设置为模拟输入
P3MDIN = 0x00; //P3端口设置为模拟输入
P7 = 0xFF; //设置P7口为数字输入
}
void Uart0_Init(unsigned char BaudRate) //Uart0初始化
{
SFRPAGE = TIMER01_PAGE;
TR1 = 0; // 关闭定时器Timer1
ET1 = 0; // 关闭定时器Timer1中断
PT1 = 0; // 关闭定时器Timer1中断优先权
TCON = 0x40; //
TMOD = 0x20; // TMOD: 定时器1, 模式2, 8位重载
SFRPAGE = UART0_PAGE;
SCON0 = 0x50; // SCON0: 模式1, 8位UART, 使能RX
SSTA0 = 0x00; //SMOD=0
CKCON = 0x10;
TH1 = ~(SYSCLK/(BaudRate*1200)/32)+1;
ES0=0; // 关闭串口Uart0中断
PS=0; // 关闭串口Uart0中断优先权
TI0 = 0;
RI0 = 0; // Indicate RX0 ready
SFRPAGE = TIMER01_PAGE;
TR1 = 1; //定时器1使能
//缓冲区初始化
uart_recv_state = 0;
uart_recv_cnt = 0;
}
void Uart0_Int_Proc(void) interrupt 4
{
unsigned char recv_data;
SFRPAGE = UART0_PAGE;
if ( RI0 )
{
if(uart_recv_state == 0){
recv_data = SBUF0;
uart_recv_cnt++;
switch(uart_recv_cnt){
case 1:
if(recv_data!='X') uart_recv_cnt = 0;
break;
case 2:
uare_cmd.package_length = recv_data;
break;
case 3:
uare_cmd.cmd_state = recv_data;
break;
case 4:
uare_cmd.cmd_func = recv_data;
break;
case 5:
uare_cmd.port_num = recv_data;
break;
case 6:
uare_cmd.data_h = recv_data;
break;
case 7:
uare_cmd.data_l = recv_data;
break;
case 8:
uare_cmd.crc = recv_data;
break;
default:
break;
}
if(uart_recv_cnt>=8){
uart_recv_cnt=0;
uart_recv_state = 1;
}
}
RI0 = 0 ;
}
if ( TI0 )
{
if ( uart_txd_cnt < 8)
{
SBUF0 = coma_txd_buff [ uart_txd_cnt ] ;
uart_txd_cnt ++ ;
}
else
{
uart_txd_cnt = 0x00 ;
}
TI0 = 0 ;
}
}
void main (void)
{
EA = 0;
WDTCN = 0xde; //向WDTCN 寄存器写入0xDE 后再写入0xAD 将禁止WDT
WDTCN = 0xad;
SYSCLK_Init();
PORT_Init();
Uart0_Init(BaudRate_9600); // UART0初始化
ES0=1; // 开启串口Uart0中断
PS=1; // 串口Uart0中断优先权设置为高
//中断使能
EA = 1;
while (1)
{
if(uart_recv_state==0x01)
{
coma_txd_buff [ 0 ] = 0x58 ;
coma_txd_buff [ 1 ] = uare_cmd.package_length;
coma_txd_buff [ 2 ] = uare_cmd.cmd_state;
coma_txd_buff [ 3 ] = uare_cmd.cmd_func;
coma_txd_buff [ 4 ] = uare_cmd.port_num;
coma_txd_buff [ 5 ] = uare_cmd.data_h;
coma_txd_buff [ 6 ] = uare_cmd.data_l;
coma_txd_buff [ 7 ] = uare_cmd.crc;
uart_txd_cnt = 1;
SFRPAGE = UART0_PAGE;
SBUF0 = coma_txd_buff [ 0 ];
uart_recv_state = 0x00;
P2 = ~P2;
}
}
} |
|