将测的温度通过IIC总线保存到AT24C02芯片中,同样也可以读出来并在数码管上显示,程序中的串口部分用于切换程序段、向AT24C02写数据并提示是否写入成功:“返回1:成功,返回0:失败”、从AT24C02数据,并处理显示在数码管上。
单片机源程序如下:
- /*********************************************************************
- *程序说明:用DS18B20测温,用串口发送响应的字符串可实现将温度数据保存
- * 在AT24C02中,同样也可以读出来并显示在数码管上。
- *主要程序段:IIC、DS18B20驱动、Usart
- *********************************************************************/
- #include "REG52.H"
- #include "DS18B20.h"
- #include "I2C.h"
- #include "Usart.h"
- #define GPIO_DIG P0
- typedef unsigned int u16;
- typedef unsigned char u8;
- u8 code smgduan[16] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,
- 0x7c,0x39,0x5e,0x79,0x71};
- u8 display[6];
- u8 data_r;
- int Read_tp; //保存从AT24C02读出来的温度
- int tp; //保存将要写入AT24C02的温度
- int response; //检查是否了写入数据
- sbit LSA = P1^0;
- sbit LSB = P1^1;
- sbit LSC = P1^2;
- void Delay(u16 i)
- {
- while(i--);
- }
- /* 定义八个数码管显示器的位选函数 ,扫描数码管 */
- void Digdisplay()
- {
- u8 i;
- for(i = 0; i < 6; i++)
- {
- switch(i)
- {
-
- case (0):
- LSA = 0; LSB = 0; LSC = 0; break; // 000
- case (1):
- LSA = 1; LSB = 0; LSC = 0; break; // 001
- case (2):
- LSA = 0; LSB = 1; LSC = 0; break; // 010
- case (3):
- LSA = 1; LSB = 1; LSC = 0; break; // 011
- case (4):
- LSA = 0; LSB = 0; LSC = 1; break; // 100
- case (5):
- LSA = 1; LSB = 0; LSC = 1; break; // 101
- }
- GPIO_DIG = display[i];
- Delay(80); //改变参数的值能实现滚动显示。最大为65535,否则会溢出。
- GPIO_DIG = 0x00; //清空数码管,以防止出现重影。
- }
- }
- //将读出来的温度数据进行处理
- void DataPros(int temp)
- {
- float temperature;
- if(temp < 0)
- {
- display[0] = 0x40; //显示负号
- temp -= 1;
- temperature = ~temp;
- temp = temperature * 0.0625 * 100;
- }
- else
- {
- display[0] = 0x00;
- temperature = temp;
- temp = temperature * 0.0625 * 100;
- }
- display[1] = smgduan[temp/10000];
- display[2] = smgduan[temp%10000/1000];
- display[3] = smgduan[temp%1000/100]|0x80;
- display[4] = smgduan[temp%100/10];
- display[5] = smgduan[temp%10];
- }
- void main()
- {
- Usart_Init(); //串口初始化
- while(1)
- {
- switch(data_r)
- {
- case '1': //测温
- DataPros(Ds18b20ReadTemp());
- Digdisplay();
- break;
- case '2': //将测温数据保存在AT24c02第1个地址中
- DataPros(0x00); //保存数据时,让数码管显示零
- Digdisplay();
- tp = Ds18b20ReadTemp();
- response = At24C02WriteByte(1,tp);//检查数据是否写入,返回1:成功 返回0:失败
- break;
- case '3': //读出AT24c02第1个地址中的温度数据并显示
- Read_tp = At24C02ReadByte(1);
- DataPros(Read_tp);
- Digdisplay();
- break;
- case '4': //将测温数据保存在AT24c02第2个地址中
- DataPros(0x00);
- Digdisplay();
- tp = Ds18b20ReadTemp();
- response = At24C02WriteByte(2,tp);
- break;
- case '5': //读出AT24c02第2个地址中的温度数据并显示
- Read_tp = At24C02ReadByte(2);
- DataPros(Read_tp);
- Digdisplay();
- break;
- }
- }
- }
- void Usart() interrupt 4
- {
- u8 ReceiveData;
- ReceiveData = SBUF;
- data_r = ReceiveData;
- while(!RI);
- RI = 0;
- // SBUF = tp;
- // while(!TI);
- // TI = 0;
-
- SBUF = response;
- while(!TI);
- TI = 0;
- }
复制代码
所有资料51hei提供下载:
DS18B20温度传感器.rar
(42.31 KB, 下载次数: 49)
|