蓝桥杯单片机学习过程记录(八)时钟芯片

蓝桥杯单片机学习过程记录(八)时钟芯片


//时钟芯片
#include
#include
sbit sck=P1^7;
sbit io=P2^3;
sbit ce=P1^3;
unsigned char seg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf,0xff};
unsigned char yi,er,san,si,wu,liu,qi,ba;
//初始化时钟
unsigned char init_time[]={50,59,23,0,0,0,0};
unsigned char shijian[7];
void delayms(int ms);
void display_12(yi,er);
void display_34(san,si);
void display_56(wu,liu);
void display_78(qi,ba);
void allinit();
void ds1302_init();
void ds1302_get();
unsigned char ds1302_read(unsigned char address);
void ds1302_write(unsigned char address,unsigned char dat);
void write_byte(unsigned char temp);
//主函数
void main(void){
 allinit();
 ds1302_init();
 while(1){
  ds1302_get();
  yi=shijian[2]/10;er=shijian[2]%10;san=10;
  si=shijian[1]/10;wu=shijian[1]%10;liu=10;
  qi=shijian[0]/10;ba=shijian[0]%10;
  display_12(yi,er);
  display_34(san,si);
  display_56(wu,liu);
  display_78(qi,ba);
 }
}
//时钟获取
void ds1302_get(void){
 unsigned char i,add;
 add=0x81;
 ds1302_write(0x8e,0x00);
 for(i=0;i<7;i++){
  shijian[i]=ds1302_read(add);
  add=add+2;
 }
 ds1302_write(add,0x80);
}
//时钟初始化
void ds1302_init(void){
 unsigned char i,add;
 add=0x80;
 ds1302_write(0x8e,0x00);
 for(i=0;i<7;i++){
  ds1302_write(add,init_time[i]);
  add=add+2;
 }
 ds1302_write(0x8e,0x80);
}
//高电平写入上升沿
void ds1302_write(unsigned char address,unsigned char dat){
 unsigned char i;
 ce=0;_nop_();
 sck=0;_nop_();
 ce=1;
 //拉高前加一个延时5v为1us
 for(i=0;i<8;i++){
  sck=0;
  //最低位传输;
  io=address&0x01;
  _nop_();
  sck=1;
  address>>=1;
 }
 dat=(((dat/10)<<4)|(dat%10));
 //数据信息写入
 for(i=0;i<8;i++){
  sck=0;
  io=dat&0x01;
  sck=1;
  dat>>=1;
 }
}
//下降沿读取
unsigned char ds1302_read(unsigned char address){
 unsigned int i;
 unsigned int temp;
 unsigned int dat_1;
 unsigned int dat_2;
 ce=0;sck=0;ce=1;
 write_byte(address);
 for(i=0;i<8;i++){
  sck=0;
  temp>>=1;
  if(io)
   temp|=0x80;
  sck=1;
 }
 io=0;
 dat_1=temp/16;
 dat_2=temp%16;
 temp=dat_1*10+dat_2;
 return temp;
}
//字节写入
void write_byte(unsigned char temp){
 unsigned char i;
 for(i=0;i<8;i++){
  sck=0;
  io=temp&0x01;
  sck=1;
  temp>>=1;
 }
}
//初始化
void allinit(){
 P2=0XA0;P0=0X00;
 P2=0XC0;P0=0XFF;P2=0XE0;P0=0XFF;
 P2=0X80;P0=0XFF;
 yi=11;er=11;san=11;si=11;wu=11;liu=11;qi=11;ba=11;
}
//数码管12
void display_12(yi,er){
 P2=0XC0;P0=0X01;P2=0XE0;P0=seg[yi];
 delayms(1);
 P2=0XC0;P0=0X02;P2=0XE0;P0=seg[er];
 delayms(1);
}
void display_34(san,si){
 P2=0XC0;P0=0X04;P2=0XE0;P0=seg[san];
 delayms(1);
 P2=0XC0;P0=0X08;P2=0XE0;P0=seg[si];
 delayms(1);
}
void display_56(wu,liu){
 P2=0XC0;P0=0X10;P2=0XE0;P0=seg[wu];
 delayms(1);
 P2=0XC0;P0=0X20;P2=0XE0;P0=seg[liu];
 delayms(1);
}
void display_78(qi,ba){
 P2=0XC0;P0=0X40;P2=0XE0;P0=seg[qi];
 delayms(1);
 P2=0XC0;P0=0X80;P2=0XE0;P0=seg[ba];
 delayms(1);
}
//延时
void delayms(int ms){
 int q,w;
 for(q=0;q<ms;q++)
  for(w=0;w<845;w++);
}

你可能感兴趣的:(单片机)