分享一下单片机温度显示的实现,传感器用的DS18B20,很简单,直接看代码就行
两个文件:first.c代码
#include<stdio.h>
#include<reg52.h>
#include<temp.h>
#include<stdlib.h>
typedef unsigned char u8;
typedef unsigned int u16;
sbit LSA=P2^2;
sbit LSB=P2^3;
sbit LSC=P2^4;
u8 num=0,Data[8];
u8 t[5];
u8 code datachuan[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; //共阴极数码管
void delay(u16 m){
while(m--);
} //设置delay延迟
int datareceive(int temp){
float tp;
if(temp>0){
Data[0]=0x00;
tp=temp;
temp=tp*0.0625*100+0.5;
}
else {
Data[0]=0x40;
temp--;
temp=~temp;
tp=temp;
temp=tp*0.0625*100;
temp=temp+0.5; //四舍五入的作用
}
return temp;
}
//数码管打印
void dataprintf(int temp){
int temp1;
u8 m;
temp1=datareceive(temp);
Data[1]=datachuan[temp1/10000];
t[0]=temp1%10000/1000+0x30;
Data[2]=datachuan[temp1%10000/1000];
t[1]=temp1%10000%1000/100+0x30;
t[2]='.';
t[3]=temp1%10000%1000%100/10+0x30;
t[4]=temp1%10000%1000%100%10+0x30;
m=datachuan[temp1%10000%1000/100];
Data[3]=m|0x80;
Data[4]=datachuan[temp1%10000%1000%100/10];
Data[5]=datachuan[temp1%10000%1000%100%10]; //计算每个数码管的数值
}
void DigDisplay(){
u8 i;
for(i=0;i<6;i++){
switch(i){
case (0) :
LSA=0;LSB=0;LSC=0;break;
case (1) :
LSA=1;LSB=0;LSC=0;break;
case (2) :
LSA=0;LSB=1;LSC=0;break;
case (3) :
LSA=1;LSB=1;LSC=0;break;
case (4) :
LSA=0;LSB=0;LSC=1;break;
case (5) :
LSA=1;LSB=0;LSC=1;break;
}
P0=Data[i];
delay(100);
P0=0x00;
}
}
void UsartInit(){
TMOD=0x20; //选择工作方式二
TH1=0xFD; //9600波特率
TL1=0xFD;
//PCON=0x80;
TR1=1;
SCON=0x50;
ES=1;
EA=1;
}
void SerialSendchar(u8 dat)
{
SBUF = dat;
while (TI == 0);
TI = 0;
}
void SerialSendString(u8 *p)
{
while(*p != '\0')
{
SerialSendchar(*p);
p++;
}
}
void main(){
int temp;
while(1){
temp=Ds18b20ReadTemp();
dataprintf(temp);
DigDisplay();
UsartInit();
SerialSendString("temperature is ");
SerialSendString(t);
SerialSendString("\n");
}
}
temp.c代码
#include<temp.h>
void Delay1ms(uint y){
uint x;
for(;y>0;y--){
for(x=110;x>0;x--);
}
}
//Ds18b20初始化
uchar Ds18b20(){
uchar i=70;
DS=0;
while(i--); //延时642us
DS=1;
i=0; //将i置为0
while(DS){
Delay1ms(1);
i++;
if(i>5){
return 0;
}
}
//延时超过5ms,return0
return 1;
}
//写数据
void Ds18b20write(uchar dat){
uchar i,j;
for(j=0;j<8;j++){
DS=0;
i++;
DS=dat&0x01;
i=6;
while(i--); //延时68ms
DS=1;
dat>>=1;
}
}
//读数据
uchar Ds18b20read(){
uchar i,j;
uchar bi,byte;
for(j=0;j<8;j++){
DS=0;
i++; //延时1ms
DS=1;
i++;
i++;
bi= DS;
byte=(byte>>1)|(bi<<7);
i=4;
while(i--);
}
return byte;
}
//最后的温度数据
int Ds18b20ReadTemp(){
int temp=0;
uchar temph,templ;
Ds18b20();
Delay1ms(1);
Ds18b20write(0xcc);
Ds18b20write(0x44);
Ds18b20();
Delay1ms(1);
Ds18b20write(0xcc); //跳过64位rom
Ds18b20write(0xbe); //写入ram
templ=Ds18b20read();
temph=Ds18b20read();
temp=temph;
temp<<=8;
temp|=templ;
return temp;
}
|