蓝桥杯单片机学习过程记录(九)IIC通信读取

蓝桥杯单片机学习过程记录(九)IIC通信读取


没写写入的函数,听说不考

蓝桥杯单片机学习过程记录(九)IIC通信读取_第1张图片

//IIC通信读电压值
#include
#include
#define uchar unsigned char;
#define uint unsigned int;
//定义引脚
sbit SDA=P2^1;
sbit SCL=P2^0;
uchar dianya;
uchar yi,er,san,si,wu,liu,qi,ba;
//定义数码管及相应小数
uchar seg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,
       0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10,0xbf,0xff};
void delayms(int ms);
void allinit();
void display_12(yi,er);
void display_34(san,si);
void display_56(wu,liu);
void display_78(qi,ba);
void Delay6us();
//iic相关函数
unsigned char iic_read();
unsigned char iic_rect();
void iic_wait();
void iic_start();
void iic_stop();
void iic_send(unsigned char dat);
//主函数
void main(void){
 allinit();
 yi=20;er=20;san=20;si=20;wu=20;liu=20;qi=20;ba=20;
 while(1){
  dianya=iic_read();
  yi=dianya/100+10;er=dianya%100/10;san=dianya%10;
  display_12(yi,er);
  display_34(san,si);
  display_56(wu,liu);
  display_78(qi,ba);
 }
}
//IIC读
unsigned char iic_read(){
 unsigned int temp;
 //启动
 iic_start();
 iic_send(0x90);
 iic_wait();
 iic_send(0x03);
 iic_wait();
 iic_stop();
 //读入
 iic_start();
 iic_send(0x91);
 iic_wait();
 temp=iic_rect();
 iic_stop();
 //转换
 temp=temp*1.96;
 return temp;
}
//启动
void iic_start(){
 SDA=1;SCL=1;
 Delay6us();
 SDA=0;
 Delay6us();
 SCL=0;
}
//停止
void iic_stop(){
 SDA=0;SCL=0;
 Delay6us();
 SDA=1;
 Delay6us();
}
//写控制字
void iic_send(unsigned char dat){
 unsigned char i;
 for(i=0;i<8;i++){
  if(dat&0x80)
   SDA=1;
  else 
   SDA=0;
  Delay6us();
  SCL=1;
  dat<<=1;
  Delay6us();
  SCL=0;
 }
}
//输出
unsigned char iic_rect(){
 unsigned char i;
 unsigned char temp;
 for(i=0;i<8;i++){
  SCL=1;
  Delay6us();
  temp<<=1;
  if(SDA)
   temp|=0x01;
  SCL=0;
  Delay6us();
 }
 return temp;
}
//等待响应
void iic_wait(){
 SDA=1;
 Delay6us();
 SCL=1;Delay6us();
 if(SDA){
  SCL=0;
  Delay6us();
  iic_stop();
 }
 else
  SCL=0;
}
//延时6us
void Delay6us()  //@11.0592MHz
{
 unsigned char i;
 i = 14;
 while (--i);
}
//延时
void delayms(int ms){
 int q,w;
 for(q=0;q<ms;q++)
  for(w=0;w<845;w++);
}
//初始化
void allinit(){
 //蜂鸣器
 P2=0XA0;P0=0X00;
 //数码管
 P2=0XC0;P0=0XFF;P2=0XE0;P0=0XFF;
 //led灯
 P2=0X80;P0=0XFF;
}
//数码管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);
}
//数码管34
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);
}
//数码管56
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);
}
//数码管78
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);
}

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