蓝桥杯单片机CT107D_18_模数转换器PCF8591的基本应用

#include
#include"IIC.h"

sbit S4 = P3^3;               //定义独立按键
unsigned char dat_Rd1 = 0;	  //存放Rd1数据
unsigned char dat_Rb2 = 0;	  //存放Rb2数据
unsigned char state = 0;	  //标志位
unsigned char code SEG_code[18] = 
	{
     0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,
	 0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,
	 0xbf,0x7f};	          //定义共阳数码管段码内容:0~F,—,.

void Select_HC138(unsigned char n)
{
     
	switch(n)
	{
     
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
			break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
			break;
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;
			break;
	}
}

void Delay_tube(unsigned char t)   //数码管延时函数
{
     
	while(t--);
}

void Show_tube(unsigned char position,unsigned char value)
{
     
	Select_HC138(7);
	P0 = 0xff;
	Select_HC138(6);
	P0 = 0x01 << position;
	Select_HC138(7);
	P0 = value;
}

void Show_all()
{
     
	Select_HC138(7);
	P0 = 0xff;
	Select_HC138(6);
	P0 = 0xff;
}

void Display_tube(unsigned char channel,unsigned char dat)
{
     
	Show_tube(0,SEG_code[16]);
	Delay_tube(100);
	Show_tube(1,SEG_code[channel]);	      //显示通道
	Delay_tube(100);
	Show_tube(2,SEG_code[16]);
	Delay_tube(100);

	Show_tube(5,SEG_code[dat/100]);       //显示电压的百位
	Delay_tube(100);
	Show_tube(6,SEG_code[(dat/10)%10]);	  //显示电压的十位
	Delay_tube(100);
	Show_tube(7,SEG_code[dat%10]);        //显示电压的个位
	Delay_tube(100);

	Show_all();
}

void Delay_keys()          //按键延时函数
{
     
	unsigned char i,j;
	i = 108;
	j = 145;
	
	do
	{
     
		while(--j);
	}while(--i);
}

void Press_keys()
{
     
	if(S4 == 0)
	{
     
		Delay_keys();
		if(S4 == 0)
		{
     
			if(state == 0)
			{
     
				state = 1;        //显示Rb2
			}
			
			else if(state == 1)
			{
     
				state = 0;		  //显示Rd1
			}
		}
		while(S4 == 0);
	}
}

void Read_Rd1()         //采样光敏电阻Rd1的电压
{
     
	IIC_Start();              //IIC总线起始信号
	IIC_SendByte(0x90);       //写设备地址
	IIC_WaitAck();            //等待从机应答
	IIC_SendByte(0x01);       //写控制字
	IIC_WaitAck();            //等待从机应答
	IIC_Stop();               //IIC总线停止信号

	IIC_Start();              //IIC总线起始信号
	IIC_SendByte(0x91);       //读设备地址
	IIC_WaitAck();            //等待从机应答
	dat_Rd1 = IIC_RecByte();  //读取PCF8591通道1的数据
	IIC_Ack(0);               //产生非应答信号
	IIC_Stop();               //IIC总线停止信号
}

void Read_Rb2()			//采样电位器Rb2的电压
{
     
	IIC_Start();
	IIC_SendByte(0x90);
	IIC_WaitAck();
	IIC_SendByte(0x03);
	IIC_WaitAck();
	IIC_Stop();

	IIC_Start();
	IIC_SendByte(0x91);
	IIC_WaitAck();
	dat_Rb2 = IIC_RecByte();
	IIC_Ack(0);
	IIC_Stop();
}

void main()
{
     
	Select_HC138(5);
	P0 = 0x00;       //关闭蜂鸣器和继电器
	while(1)
	{
     
		Press_keys();
		switch(state)
		{
     
			case 0:
				Read_Rd1();
				Display_tube(1,dat_Rd1);
				break;
			case 1:
				Read_Rb2();
				Display_tube(3,dat_Rb2);
				break;
		}
	}
}
		

你可能感兴趣的:(蓝桥杯单片机,单片机,c语言)