Demo entry 6350198

v

   

Submitted by anonymous on Mar 07, 2017 at 18:01
Language: C. Code size: 2.6 kB.

#include<reg52.h>  
#include<intrins.h>
#include<stdio.h>  
#include <math.h>


#define uchar unsigned char   
#define uint unsigned int 

sbit SCL=P2^0;
sbit SDA=P2^1;
                                       
void delayms (uint x)       //1ms delay
{    
	uint i,j;   
	for(i=x;i>0;i--)  
		for(j=110;j>0;j--); 
} 
                                         
void delay()
{                 
	_nop_();        
	_nop_();
}

void init() 
{ 
	SCL=1; 
	delay();                   
	SDA=1;
	delay(); 
} 

void start() 
{ 
	SDA=1; 
	delay(); 
	SCL=1; 
	delay();
	SDA=0; 
	delay(); 
}                 

void response()
{
	uchar i=0;
	SCL=1;
	delay();
	while((SDA==1)&&(i<255))
		i++;
	SCL=0;
	delay();
}

void stop()
{ 
	SDA=0; 
	delay();
	SCL=1; 
	delay();
	SDA=1; 
	delay();          
}

void writebyte(uchar value) 
{    
		unsigned char i;     
		for (i=0x80;i>0;i>>=1)  
		{   
			SCL=0;  
			delay();   
			if(i&value)
			{    
				SDA=1;  
			}    
			else
			{   
				SDA=0; 
			} 
			delay();   
			SCL=1; 
			delay();     
		} 
		SCL=0;  
		delay(); 
		SDA=1;   
		delay();                        
} 

char readbyte(bit ack) 
{  
	uchar i,val=0; 
	SDA=1;  
	delay(); 
	for (i=0x80;i>0;i>>=1)   
	{  
		SCL=1;            
		delay();      
		if (SDA)
			val=(val | i);         
		SCL=0;   
		delay();       
	}     
	SDA =! ack;              
	SCL=1;       
	delay();              
	SCL=0;  
	delay();    
	SDA=1;    
	return val; 
} 

void temperature()
{
	uchar MSB,LSB;
	unsigned int a;
	float b,c;
	start();
	writebyte(0x80);
	response();
	writebyte(0xE3);  
	response();
	start();
	writebyte(0x81);
	response();	
	delayms(100);
	MSB=readbyte(1);
	LSB=readbyte(0);
	stop();
	a=MSB*256+LSB;
	a=a/4*4;
	b=(float)a;
	c=-46.85+175.72*b/pow(2,16);
	printf("the temperature is %.1f\n",c);
}

void humidity()
{
	uchar MSB,LSB;
	unsigned int a;
	float b,c;
	start();
	writebyte(0x80);
	response();
	writebyte(0xE5);  
	response();
	start();
	writebyte(0x81);
	response();	
	delayms(100);
	MSB=readbyte(1);
	LSB=readbyte(0);
	stop();
	a=MSB*256+LSB;
	a=a/4*4;
	b=(float)a;
	c=-6+125*b/pow(2,16);
	printf("the humidity is %.1f\n",c);
}

void main() 
{  
	TMOD=0x20; 
	TH1=0xFD; 
	TL1=0xFD;  
	TR1=1;  
	REN=1;  
	SM0=0;  
	SM1=1;             
	ES=1;                                 
	EA=1;  
	P2=0x00; 
	init();
	TI=1;
//	printf("the temperature is ");
	while(1)
	{
		temperature();
		humidity();
		delayms(1000);
	}                                     
	
}  

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).