微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > ATMEGA16与DS18B20数码管显示

ATMEGA16与DS18B20数码管显示

时间:12-02 来源:互联网 点击:
一个误差值大的DS18B20把我害得不浅,一直以为是程序错,下狠心换了个,成功了!误了我三天去查程序

/*本程序为八位共阴极数码管且有两个573控制的动态扫描*/
#include
#include
#define uchar unsigned char
#define uint unsigned int
//注code的功能是把后面的数据存在程序存贮器中,不用code就放到了随机存贮器中.
#pragmadata:code
const table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d, 0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};//不带小数点
const table2[]={0xbf,0x86,0xdb,0xcf,0xe6,
0xed,0xfd,0x87,0xff,0xdf};//带小数点编码

/*如果用uchar table[]就放到了数据存贮器中。决不要这样用,这样占用空间多。*/
/*两个573,段码PA3,位码PA4*/
//把18B20的DQ接到PC2上
#define DQ_IN DDRC&=~BIT(2)
//上一句是把DQ设为输入
#define DQ_OUT DDRC|=BIT(2)
//上一句是把DQ设为输出
#define DQ_SET PORTC|=BIT(2)
//上一句是把DQ设为高电平
#define DQ_CLR PORTC&=~BIT(2)
//上一句是把DQ设为低电平
#define DQ_RD PINC&BIT(2)
//上一句是从PC2中读出数据
uchar disdata[4];
void delay(uint ms)
{
uint i,j;
for(i=ms;i>0;i--)

for(j=220;j>0;j--);

}
void delayus(uint us)
{
while(us--);
}
void show(uchar j,uchar k)
{
DDRA|=BIT(3);
DDRA|=BIT(4);
DDRB=0XFF;
PORTA|=BIT(3);
PORTB=table[j];
PORTA&=~BIT(3);

PORTB=0XFF;
PORTB&=~BIT(k);
PORTA|=BIT(4);
PORTA&=~BIT(4);
delay(5);
}

void show_point(uchar j,uchar k)
{
DDRA|=BIT(3);
DDRA|=BIT(4);
DDRB=0XFF;
PORTA|=BIT(3);
PORTB=table2[j];
PORTA&=~BIT(3);

PORTB=0XFF;
PORTB&=~BIT(k);
PORTA|=BIT(4);
PORTA&=~BIT(4);
delay(5);
}
rest_18B20()
{
uchar i ;
DQ_OUT;//把DQ设为输出
DQ_SET;//拉高DQ
delayus(5);
DQ_CLR;//拉低DQ
delayus(800);
DQ_SET;//拉高DQ
//delayus(550);
DQ_IN;//把DQ设为输入
i=DQ_RD;
delayus(800);
return i;
}
void write_18B20(uchar dat)
{
uchar i;
for(i=0;i<8;i++)
{
DQ_OUT;//把DQ设为输出
DQ_CLR;//拉低DQ
delayus(30);
if(dat&0x01)//判断当前位是不是高,如果是高就执行下面语句
{
DQ_SET;//拉高DQ,让总线采样到1
}
else
{
DQ_CLR;//拉低DQ
}
delayus(80);
DQ_SET;//释放总线
dat=dat>>1;
}
}
uchar read_18B20()
{
uchar i,value;
for(i=0;i<8;i++)
{

DQ_OUT;//把DQ设为输出
DQ_CLR;//拉低DQ
value=value>>1;
delayus(10);
DQ_SET;//释放总线 等MCU采样
DQ_IN;//把DQ设为输入才能采样
if(DQ_RD)
{
value|=0x80;
}

delayus(100);
// DQ_SET;//释放总线
}
return value;
}

void display(uint tvalue)
{
disdata[0]=tvalue/1000;//百位数
disdata[1]=tvalue%1000/100;//十位数
disdata[2]=tvalue%100/10;//个位数
disdata[3]=tvalue%10;//小数位
show(disdata[0],0);
delay(2);
show(disdata[1],1);
delay(2);
show_point(disdata[2],2);
//show(0x80,2);
show(disdata[3],3);
//下面这种显示方式也可以
/* uint i,temp[4];
for(i=0;i<4;i++)
{
temp[3-i]=dat%10;
dat=dat/10;
}

for(i=0;i<4;i++)
{
show(temp[i],i);
delay(2);*/
/* // 以下三句为关闭显示,动态显示时要用的
DDRA|=BIT(3);
DDRA|=BIT(4);
DDRB=0XFF;
}*/
}
void main()
{int L,H;
uint tvalue;
while(1)
{
rest_18B20();
write_18B20(0xcc);//跳过读序列号
write_18B20(0x44);//启动温度转换
delayus(50);
//读之前再复位一次
rest_18B20();
write_18B20(0xcc);//跳过读序列号
write_18B20(0xbe);//启动开始采样,读暂存器
delayus(50);
L=read_18B20();//先读低八位字节
H=read_18B20();//后读高八位
tvalue=H;
tvalue<=8;
tvalue=tvalue|L;
tvalue=tvalue*0.625;//扩大10倍
display(tvalue);
}
}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top