⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.c

📁 使用ATmega32驱动DS18B20
💻 C
字号:
#include <iom32v.h>
#include <macros.h> 
#include "delay.h"
#include "ds18b20.h"
#include "lcd.h"

unsigned char temp_buf[5];
unsigned int temp=0;
unsigned long int temp_long=0;
float temperature=0; //涉及到小数点的计算,要用float
unsigned char buf[7];

void main(void)
{
   unsigned int  temp=0;

   LCD16xx_init();
   LCD16xx_clr();                     //显示清屏
   
   delay_nms(1); 
   
   temp=resetDS18B20();             //检测DS1302的存在
   
   LCD16xx_write_string(3,0,"Welcome to");
   LCD16xx_write_string(1,1,"www.avrarm.com!");
   delay_nms(500);
   LCD16xx_clr();                     //显示清屏
   delay_nms(2);
   
   while(1)
   {
	   temp=readTempDS18B20();
	   //temp=0xfFE0; //输入数值来检验输出是否有问题

	   if(temp==0xf800) //即是-128°C,不能处理 下面的temp&=0x07ff;、temp=2048-temp;会出错
	   {
		   temp=0xf801; //变成 -127.9375°C
	   }

	   if(temp>=256*8) //高5位都为1,则为负温度
	   {
		   //buf[0]='-';
		   temp_buf[0]='-';
		   temp&=0x07ff;
		   temp=2048-temp; //补码转换成原码,符号变正
	   }
	   else
	   {
		   //buf[0]='+';
		   temp_buf[0]='+';
	   }

	   //temperature = temp;
	   temp_long=temp;

		//temperature = temperature * 0.0625*10; //计算到小数点后1位 最大为128*10度 共需要4+1+1位 即6位,再加字符串结束位共7位
		temp_long = temp_long*625; //2047*0.0625=127.9375  共8位(计上小数点),再加上符号位则为9位(加字符串 共10位);2047*625 用long刚好保存
		
		temperature = DS18B20_FLOAT_Temp(); //读出浮点温度值,有正负之分,有小数点
		temperature = temperature * 10; //为待会显示小数点一位做准备,待会转为正整数
		if(temperature<0)
		{
			buf[0]='-';
			temperature=-temperature;
		}
		else
			buf[0]='+';
		
		temp=temperature; //换回int类型,方便下面的操作


		if(temp<1280&&temp_long<1280000)
		{
			temp_buf[1]=(temp_long%10000000)/1000000+0x30;
			temp_buf[2]=(temp_long%1000000)/100000+0x30;
			temp_buf[3]=(temp_long%100000)/10000+0x30;
			temp_buf[4]='.';
			temp_buf[5]=(temp_long%10000)/1000+0x30;			
			temp_buf[6]=(temp_long%1000)/100+0x30;
			temp_buf[7]=(temp_long%100)/10+0x30;
			temp_buf[8]=temp_long%10+0x30;
			temp_buf[9]=0;

			if(temp_buf[1]==0x30)	//如果百位为0,则百位不显示	
				temp_buf[1]=' ';
			if(temp_buf[1]==' '&&temp_buf[2]==0x30)	//如果百位为0,十位也为0,则十位不显示
			{
				temp_buf[2]=' ';
			}

			buf[1]=(temp%10000)/1000+0x30;
			buf[2]=(temp%1000)/100+0x30;
			buf[3]=(temp%100)/10+0x30;
			buf[4]='.';
			buf[5]=temp%10+0x30;
			buf[6]=0;

			if(buf[1]==0x30)	//如果百位为0,则百位不显示	
				buf[1]=' ';
			if(buf[1]==' '&&buf[2]==0x30)	//如果百位为0,十位也为0,则十位不显示
			{
				buf[2]=' ';
			}
		}

		LCD16xx_write_string(3,0,temp_buf);
		LCD16xx_write_string(5,1,buf);
		delay_nms(200);
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -