当前位置: 代码迷 >> 单片机 >> C8051F020使用UART1与485通信解决思路
  详细解决方案

C8051F020使用UART1与485通信解决思路

热度:26   发布时间:2016-04-28 16:11:06.0
C8051F020使用UART1与485通信
//我想使用C8051F020的UART1与485通信,p04,p05分配给UART1,p57与485的2、3脚相连(硬件已经固定),
//程序如下:
//问题:为什么EA=0;时接上位机收到了DONE 而EA = 1;却一个符号接收不到
//我第一次遇到这样的问题,是不是程序中对端口的配置或者写法有误,应该怎样该
//请高手指点一下,十分感谢啊...


#include <C8051F020.H>

#define SYSCLK 22118400 // SYSCLK frequency in Hz
#define BAUDRATE 9600 // Baud rate of UART in bps 、

#define uchar unsigned char
#define uint unsigned int

#define REDE485_1 P5 |= 0x80; //P5.7置1 //1000 0000
#define REDE485_0 P5 &= 0x7f; //P5.7置0 //0111 1111

uchar arm = 0x0f;
uchar message1[]="Done";

//延时函数
void Delay( uint tt )
{
while( tt-- );
}

//串口的初始化
void UART1_Init(void) 


// SCON0 = 0x02; // SCON0 UART0关闭
  SCON1 = 0x50; // SCON1: mode 1, 8-bit UART, enable RX
  TMOD = 0x20; // TMOD: timer 1, mode 2, 8-bit reload
  TH1 = -(SYSCLK/BAUDRATE/16); // set Timer1 reload value for baudrate
  TR1 = 1; // start Timer1
  CKCON |= 0x10; // Timer1 uses SYSCLK as time base
  PCON |= 0x10; // SMOD11 = 1
  //TI1 = 1; // Indicate TX1 ready
}

//开启UART1
void UART1_ISROp(void) 
{
  EIE2 |= 0X40; //ES1=1
}

//关闭UART1
void UART1_ISROff(void) 
{
  EIE2 &= 0XBF; //ES1 = 0;
}

//发送字符
void Send_Char(uchar ch) 

REDE485_1;
  Delay(65535);
  Delay(65534); 

SBUF1 = ch; //送入缓冲区 
while((SCON1 & 0X02) == 0); //等待发送完毕 
SCON1 &= ~0X02; //软件清零 


//发送字符串
void send_string_com(uchar *str,uint strlen)
{
unsigned int k=0;
do
{
  Send_Char(*(str + k));
k++;
} while(k < strlen);
}

//端口的配置
void SysPort_Initnew (void)  
{
XBR0 = 0x05; //设置XBR0,UART0,IIC使能
XBR1 = 0x14; //设置XBR1,INT0,INT2使能
XBR2 = 0x44; //关闭交叉开关和弱上拉,UART1使能 P1.0 T4计数 P1.1 T4捕捉
 
P0MDOUT = 0x11; //0001 0001 //设置P0口输出,TXD0,TXD1:推挽输出,其它漏极开路输出
P1MDIN = 0xff; //设置P1口输入信号类型:数字输入

P74OUT = 0xff;
// EMI0CF = 0x25; //外部存储器接口配置,ALE = 2SYSCLK
// EMI0TC = 0x4f; //SYSCLK, //EWR = 4SYSCLK, EAH = 3SYSCLK,
// EMI0CN = 0; //页选择清零
}

void SYSCLK_Init (void)
{
int i; // delay counter
OSCXCN = 0x67; // start external oscillator with
// 22.1184MHz crystal
for (i=0; i < 256; i++) ; // Wait for osc. to start up  
while (!(OSCXCN & 0x80)) ; // Wait for crystal osc. to settle
OSCICN = 0x88; // select external oscillator as SYSCLK
// source and enable missing clock
// detector
}
 
void main(void)
{
WDTCN = 0xde;
  WDTCN = 0xad; //关闭看门狗

SYSCLK_Init(); //系统初始化
SysPort_Initnew(); //端口的配置

UART1_Init();
UART1_ISROp();
   
  EA = 1;//此地为什么EA=0时上位机会收到done的字符,而EA=1时去接受不到?????????


while(1)
{
P5 = arm;
send_string_com(message1,sizeof(message1));
}
}

void UART1_ISR(void) interrupt 20 using 3

REDE485_0;
Delay(65535);
  Delay(65534);