#include<iom16v.h>
#include<macros.h>
#include <math.h>
#define uchar unsigned char
#define uint unsigned int
#define QW_IN DDRB&=~BIT(4)
#define QW_OUT DDRB|=BIT(4)
#define QW_SET PORTB|=BIT(4)
#define QW_CLR PORTB&=BIT(4)
//#DEFINE QW_R PINB&BIT(4)
void delay(uint ms)
{
uint i,j;
for(i=0;i<ms;i++)
{
for(j=0;j<1141;j++);
}
}
//定义 1us 延时函数
void delay_us(uint n)
{
{asm("nop");}
}
uchar digit[]={"0123456789"}; //定义字符数组显示数字
uchar error[]={"Error!"}; //没有检测到DS18B20
uchar temp[]={"Temp:"}; //显示的是温度
//对液晶模块的操作程序
void write_com(uchar com)
{
PORTC&=~BIT(0); //RS=0,指令寄存器
PORTC&=~BIT(1); //R/W=0写数据到LCD
PORTA=com;
PORTB|=BIT(2);
delay(3);
PORTB&=~BIT(2);
}
void write_dat(uchar dat)
{
PORTC|=BIT(0); //RS=1,数据寄存器
PORTC&=~BIT(1); //R/W=0写数据到LCD
PORTA=dat;
PORTB|=BIT(2);
delay(3);
PORTB&=~BIT(2);
}
void LCD()
{
DDRA=0XFF;
DDRC|=BIT(0)|BIT(1);
DDRB|=BIT(2);
PORTB&=~BIT(2);
write_com(0X38);
delay(9);
write_com(0X01);
delay(9);
write_com(0X0C);
delay(9);
write_com(0X06);
delay(9);
}
//显示温度值
void display_error()
{
uchar i;
i=0;
LCD();
write_com(0X80+0X40);
delay_us(5000);
while(error[i]!=0)
{
write_dat(error[i]);
i++;
delay_us(100);
}
}
void display_temp()
{
uchar i;
write_com(0X80+0X00);
delay(9);
while(temp[i]!='\0')
{
write_dat(temp[i]);
i++;
delay(9);
}
}
void xsd()
{
write_com(0X80+0X0A);
delay(9);
write_dat('.');
delay(9);
}
void dw()
{
write_com(0X80+0X0D);
delay(9);
write_dat('C');
delay(9);
}
void wd(uint temp)
{
uint a;
uint b;
uint c;
uint d;
a=temp/1000;
temp=temp%1000;
b=temp/100;
temp=temp%100;
c=temp/10;
d=temp%10;
write_com(0X80+0X07);
delay(9);
write_dat(digit[a]);
write_com(0X80+0X08);
delay(9);
write_dat(digit[b]);
write_com(0X80+0X09);
delay(9);
write_dat(digit[c]);
delay(9);
write_com(0X80+0X0B);
delay(9);
write_dat(digit[d]);
delay(9);
}
/* void wdx(uint temp)
{
uint a;
uint b;
uint c;
uint d;
a=temp/1000;
temp=temp%1000;
b=temp/100;
temp=temp%100;
c=temp/10;
temp=temp%10;
d=temp;
write_com(0X80+0X0B);
delay(9);
write_dat(digit[d]);
}*/
//DS18B20初始化
uchar ds18b20_reset()
{
uchar i;
QW_OUT;
QW_CLR;
delay_us(600);
QW_SET;
delay_us(100);
QW_IN;
i=PINB&BIT(4);
delay_us(500);
return i;
}
//DB18B20写操作程序
void ds18b20_write_byte(char ha)
{
uchar i;
for(i=0;i<0;i++)
{
QW_OUT;
QW_CLR;
delay_us(5);
if(ha&0x01)
{
QW_SET;
}
delay_us(100);
QW_SET;
ha=ha>>1;
}
}
//DS18B20读操作程序
uchar ds18b20_read_byte()
{
uchar i;
uchar ha;
ha=0;
for(i=0;i<8;i++)
{
ha=ha>>1;
QW_OUT;
QW_CLR;
delay_us(5);
QW_SET;
QW_IN;
if(PINB&BIT(4))
{
ha|=0x80;
}
delay_us(60);
}
return ha;
}
//主函数程序
void main()
{
uchar i;
uchar j;
uint temp;
LCD();
if(ds18b20_reset()==1)
{
display_error();
}
display_temp();
xsd();
dw();
while(1)
{
ds18b20_reset(); //DS18B20初始化
ds18b20_write_byte(0XCC); //对ROM操作,跳过ROM
ds18b20_write_byte(0X44); //启动温度转换
delay(9);
ds18b20_reset();
ds18b20_write_byte(0XCC);
ds18b20_write_byte(0xBE); //读暂存器
i=ds18b20_read_byte(); //LSB
j=ds18b20_read_byte(); //MSB
temp=j*256+i;
temp=temp*0.625;
wd(temp);
//wdx(temp);
delay(10);
}
}
|