用AT89C51和DS18B20采集温度,在UG-2864HSWEG01上显示代码
时间: 2023-11-28 08:47:21 浏览: 129
以下是基于AT89C51和DS18B20采集温度,并在UG-2864HSWEG01上显示的示例代码:
```
#include <reg51.h>
#include <intrins.h>
#include <stdio.h>
#define DS18B20_DQ P3_7
#define UG_EN P2_3
#define UG_RW P2_2
#define UG_RS P2_1
#define UG_E P2_0
#define DS18B20_SKIP_ROM 0xCC
#define DS18B20_CONVERT_T 0x44
#define DS18B20_READ_SCRATCHPAD 0xBE
sbit SDA = P1^3;
sbit SCL = P1^2;
unsigned char code g_LcdInitCmd[] = {0x38, 0x0c, 0x06, 0x01, 0x02, 0x80};
unsigned char code g_LcdClearCmd[] = {0x01};
void delay_us(unsigned int us)
{
while (us--)
{
_nop_();
}
}
void delay_ms(unsigned int ms)
{
while (ms--)
{
delay_us(1000);
}
}
void DS18B20_Write_Byte(unsigned char dat)
{
unsigned char i;
for (i = 0; i < 8; i++)
{
DS18B20_DQ = 0;
_nop_();
_nop_();
DS18B20_DQ = dat & 0x01;
_nop_();
_nop_();
DS18B20_DQ = 1;
dat >>= 1;
}
}
unsigned char DS18B20_Read_Byte()
{
unsigned char i, dat = 0;
for (i = 0; i < 8; i++)
{
DS18B20_DQ = 0;
_nop_();
_nop_();
dat >>= 1;
if (DS18B20_DQ)
{
dat |= 0x80;
}
_nop_();
_nop_();
DS18B20_DQ = 1;
}
return dat;
}
void UG_Write_Cmd(unsigned char cmd)
{
UG_EN = 0;
UG_RW = 0;
UG_RS = 0;
P0 = cmd;
UG_EN = 1;
delay_us(1);
UG_EN = 0;
delay_ms(2);
}
void UG_Write_Data(unsigned char dat)
{
UG_EN = 0;
UG_RW = 0;
UG_RS = 1;
P0 = dat;
UG_EN = 1;
delay_us(1);
UG_EN = 0;
delay_ms(2);
}
void UG_Init()
{
unsigned char i;
UG_Write_Cmd(0x38);
UG_Write_Cmd(0x0c);
UG_Write_Cmd(0x06);
UG_Write_Cmd(0x01);
UG_Write_Cmd(0x02);
UG_Write_Cmd(0x80);
}
void UG_Clear()
{
UG_Write_Cmd(0x01);
}
void UG_Puts(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char i = 0;
if (y == 1)
{
UG_Write_Cmd(0x80 + x);
}
else
{
UG_Write_Cmd(0xc0 + x);
}
while (str[i] != '\0')
{
UG_Write_Data(str[i]);
i++;
}
}
void UG_Putc(unsigned char x, unsigned char y, unsigned char c)
{
if (y == 1)
{
UG_Write_Cmd(0x80 + x);
}
else
{
UG_Write_Cmd(0xc0 + x);
}
UG_Write_Data(c);
}
void UG_Display_Temperature(float temperature)
{
char str[17];
sprintf(str, "Temperature: %.1f C", temperature);
UG_Clear();
UG_Puts(0, 0, "AT89C51+DS18B20");
UG_Puts(0, 1, str);
}
void DS18B20_Start_Convert()
{
DS18B20_Write_Byte(DS18B20_SKIP_ROM);
DS18B20_Write_Byte(DS18B20_CONVERT_T);
}
unsigned int DS18B20_Read_Temperature()
{
unsigned char temp_l, temp_h;
unsigned int temp;
DS18B20_Write_Byte(DS18B20_SKIP_ROM);
DS18B20_Write_Byte(DS18B20_READ_SCRATCHPAD);
temp_l = DS18B20_Read_Byte();
temp_h = DS18B20_Read_Byte();
temp = temp_h;
temp <<= 8;
temp |= temp_l;
return temp;
}
void main()
{
float temperature;
unsigned int temp;
UG_Init();
UG_Clear();
UG_Puts(0, 0, "AT89C51+DS18B20");
while (1)
{
DS18B20_Start_Convert();
delay_ms(750);
temp = DS18B20_Read_Temperature();
temperature = (float)temp / 16.0;
UG_Display_Temperature(temperature);
delay_ms(2000);
}
}
```
需要注意的是,这个示例代码是基于AT89C51的,如果你使用的是其他型号的单片机,需要对代码进行相应的修改。同时,UG-2864HSWEG01显示屏需要通过SPI通信方式进行控制,如有需要也需要对代码进行修改。
阅读全文