【蓝桥杯单片机】DS18B20程序设计

onewire.c

#include "reg52.h"
#include "onewire.h"


void Delay_OneWire(unsigned int t)  
{
	unsigned char i;
	while(t--){
		for(i=0;i<12;i++);
	}
}





void Write_DS18B20(unsigned char dat)
{
	unsigned char i;
	for(i=0;i<8;i++)
	{
		DQ = 0;
		DQ = dat&0x01;
		
		Delay_OneWire(5);
		
		DQ = 1;
		dat >>= 1;
	}
	Delay_OneWire(5);

}




unsigned char Read_DS18B20(void)
{
	unsigned char i;
	unsigned char dat;
  
	for(i=0;i<8;i++)
	{
		DQ = 0;
		dat >>= 1;
		DQ = 1; 
		if(DQ)  
		{
			dat |= 0x80;
		}	    
		Delay_OneWire(5);
	}
	return dat;
}

//DS18B20³õʼ»¯£¬¸´Î»
bit init_ds18b20(void)
{
  	bit initflag = 0;
  	
  	DQ = 1;
  	Delay_OneWire(12);
  	DQ = 0;
  	Delay_OneWire(80); 
  	DQ = 1;
  	Delay_OneWire(10);  
  	initflag = DQ;     
  	Delay_OneWire(5);
  
  	return initflag;
}



unsigned char Read_temp(void)
{
    unsigned char low,high;
  	char temp=0;
  
  	init_ds18b20();
  	Write_DS18B20(0xCC);
  	Write_DS18B20(0x44); 
  	Delay_OneWire(1000);
	


	
  	init_ds18b20(); 
  	Write_DS18B20(0xCC);
  	Write_DS18B20(0xBE);

  	low = Read_DS18B20();
  	high = Read_DS18B20(); 
 
	
	temp = high<<4;   
  	temp |= (low>>4);

	return temp;

}

onewire.h

#ifndef _ONEWIRE_H
#define _ONEWIRE_H

sbit DQ = P1^4;

unsigned char Read_temp(void);

#endif

init.c

#include "reg52.h"
#include "init.h"
void init_led_buss()
{
P0=0xff;
	P2=(P2 &0x1f) |0x80;
	P2 &=0x1f;
	
	P0=0x00;
	P2=(P2 &0x1f) |0xa0;
	P2 &=0x1f;
}

void init_Timer1()
{
AUXR |= 0x80;
	TMOD &= 0xF0;
	TL0 = 0xCD;	
	TH0 = 0xD4;	
	TF0 = 0;	
	TR0 = 1;
	ET0 = 1;
	EA = 1;
}

init.h

#ifndef _INIT_H
#define _INIT_H

sfr AUXR = 0x8E;

void init_led_buss();
void init_Timer1();

#endif

main.c

#include "reg52.h"
#include "init.h"
#include "onewire.h"

code unsigned char SMG[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
unsigned char SMG_Dis[8] = {10,10,10,10,10,10,10,10};
bit temp = 0;
void SMG_Bit(void);



void SMG_DisPlay()
{unsigned char Temp;
 if(temp)
		{
			temp = 0;
			Temp = Read_temp();  //¶ÁÎÂ¶È         
     }
  
		(Temp>=10)?(SMG_Dis[6] = Temp/10):(SMG_Dis[6]=10);       
		SMG_Dis[7] =Temp%10; 
    }


void main(void)
{ 
	
	init_led_buss();
  init_Timer1();
    
    while(1)
    {
       SMG_DisPlay();
}}



void Timer1(void)  interrupt 1 
{
    static unsigned char intr;
	if(++intr == 50)  
	{
        intr = 0;
		temp = 1;  
    }
	SMG_Bit();
}



void SMG_Bit(void)
{   
	static unsigned char SMG_bit = 0;
	P2 = ((P2&0x1f)|0xE0);   
	P0 = 0xff;               
	P2 &= 0x1f; 

	P0 = 1<<SMG_bit;	       
	P2 = ((P2&0x1f)|0xC0);   
	P2 &= 0x1f;
	
	P0 = SMG[SMG_Dis[SMG_bit]];
  P2 = ((P2&0x1f)|0xE0);   
	P2 &= 0x1f;               
	
    if(++SMG_bit == 8){
       SMG_bit = 0;
    }    
}


版权声明:本文为m0_63213850原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。