/*TI=1时,申请中断,CPU响应中断后,发送数据 RI=1时,申请中断,要求CPU取走数据*/ #include "reg51.h" #include "stdio.h" #include "intrins.h" #define CTH1 0xfd #define CTL1 0xfd sbit cs=P3^1; sbit reset=P3^2; sbit drdy=P3^3; sbit sclk=P3^4; sbit din=P3^6; sbit dout=P3^5; unsigned char idata send_letter; unsigned char LSB,MSB; void serial_init(void); void serial_send(void); void ad7705_init(void); void writead7705(unsigned char); void resetad7705(void) ; unsigned char readad7705(unsigned char); unsigned char exchange(unsigned char a); void serial_init() { TMOD=0x21; TH1=CTH1; TL1=CTL1; SCON=0x50; PCON=0; TR1=1; TR0=1; ET0=1; ES=1; EA=1; } void ad7705_init() { cs=0; writead7705(0x20);//写通信寄存器,找时钟寄存器 writead7705(0x55);//写时钟寄存器 writead7705(0x10);//写通信寄存器,找设置寄存器 writead7705(0x40);//写设置寄存器 } void serial_send() { unsigned char data tmp=0; tmp=send_letter; TI=0; SBUF=tmp; while(!TI); TI=0; } void resetad7705(void) { int tim; unsigned char j; tim=1000; reset=0; while(tim--); reset=1; cs=0; sclk=1; for(j=0;j<40;j++) //*多于连续32个 din=1 使串口复位 { sclk=0; din =1; sclk=1; }
} unsigned char readad7705(unsigned char readata) { int AD_result; unsigned char LSB,MSB; unsigned char comm; cs=0; comm=exchange(readata); while(drdy==1); SCON=0; SBUF=comm; while(TI==0); TI=0; SCON=0x10; while(RI==0); RI=0; MSB=SBUF; SCON=0x10; while(RI==0); RI=0; LSB=SBUF; MSB=exchange(MSB); LSB=exchange(LSB); AD_result=(int)MSB; //以下为高低字节合并 AD_result=AD_result<<8; AD_result=AD_result|(int)LSB; return AD_result; //返回读取的数据 } void writead7705( unsigned char byteword) { unsigned i; // sclk=1; for(i=0;i<8;i++) { din=(bit)(byteword&0x80); sclk=1; sclk=0; sclk=1; byteword<<=1; } // sclk=1;//程序执行完后sclk仍为高电平 din=1; //为保证不乱写程序
} unsigned char exchange(unsigned char a) /*将8位数据a的顺序颠倒后赋给b。 因为串口发送顺序和ad7705的接收顺序刚好相反*/ { unsigned char i,b; b=a&0x01; for(i=1; i<8; i++) { b=b<<1; a=a>>1; b=b+(a&0x01); } return(b); } /*void writead7705( unsigned char byteword) //通过串口给ad7705发送命令字a { unsigned char comm; SCON=0; TI=0; comm=exchange(byteword); SBUF=comm; while(!TI); TI=0; }*/
void main(void) { int result; serial_init(); resetad7705(); ad7705_init(); result=readad7705(0x38); send_letter=result; serial_send(); } |