我要设计一个基于单片机的非接触式人体红外测温系统,系统包括STC89C52单片机,MLX90614红外测温模块,LCD1602显示模块等装置,请写一段代码,实现测量人体温度并将温度值显示在LCD1602上的功能
时间: 2024-03-01 09:55:45 浏览: 89
好的,以下是一个简单的代码示例,可以实现你所描述的功能:
```c
#include <reg52.h>
#include <intrins.h>
#define FOSC 11059200L
#define BAUD 9600
typedef unsigned char uchar;
typedef unsigned int uint;
sbit SCL=P2^1;
sbit SDA=P2^0;
sbit E=P1^7;
sbit RW=P1^6;
sbit RS=P1^5;
// I2C总线相关操作
void delay5us() _naked
{
_asm
nop
nop
nop
nop
_endasm;
}
void i2c_start()
{
SDA = 1;
delay5us();
SCL = 1;
delay5us();
SDA = 0;
delay5us();
SCL = 0;
delay5us();
}
void i2c_stop()
{
SDA = 0;
delay5us();
SCL = 1;
delay5us();
SDA = 1;
delay5us();
}
void i2c_ack()
{
SDA = 0;
delay5us();
SCL = 1;
delay5us();
SCL = 0;
delay5us();
SDA = 1;
delay5us();
}
void i2c_nack()
{
SDA = 1;
delay5us();
SCL = 1;
delay5us();
SCL = 0;
delay5us();
SDA = 1;
delay5us();
}
uchar i2c_write_byte(uchar dat)
{
uchar i, ack_bit;
for(i=0; i<8; i++)
{
SDA = (dat & 0x80) >> 7;
dat <<= 1;
delay5us();
SCL = 1;
delay5us();
SCL = 0;
delay5us();
}
SDA = 1;
delay5us();
SCL = 1;
delay5us();
ack_bit = SDA;
SCL = 0;
delay5us();
return ack_bit;
}
uchar i2c_read_byte()
{
uchar i, dat = 0;
SDA = 1;
delay5us();
for(i=0; i<8; i++)
{
dat <<= 1;
SCL = 1;
delay5us();
dat |= SDA;
SCL = 0;
delay5us();
}
return dat;
}
// MLX90614红外测温模块相关操作
void mlx90614_init()
{
i2c_start();
i2c_write_byte(0xB4);
i2c_write_byte(0x01);
i2c_write_byte(0x60);
i2c_stop();
}
float mlx90614_get_temp()
{
uchar i, temp_h, temp_l;
float temp;
i2c_start();
i2c_write_byte(0xB4);
i2c_write_byte(0x07);
i2c_stop();
i2c_start();
i2c_write_byte(0xB5);
temp_h = i2c_read_byte();
temp_l = i2c_read_byte();
i2c_nack();
i2c_stop();
temp = (temp_h << 8) | temp_l;
temp *= 0.02;
temp -= 273.15;
return temp;
}
// LCD1602显示模块相关操作
void lcd_write_cmd(uchar cmd)
{
RS = 0;
RW = 0;
P0 = cmd;
E = 1;
_nop_();
_nop_();
E = 0;
}
void lcd_write_data(uchar dat)
{
RS = 1;
RW = 0;
P0 = dat;
E = 1;
_nop_();
_nop_();
E = 0;
}
void lcd_init()
{
lcd_write_cmd(0x38);
lcd_write_cmd(0x0C);
lcd_write_cmd(0x06);
lcd_write_cmd(0x01);
}
void lcd_display_temp(float temp)
{
uchar i, temp_int, temp_dec;
temp_int = (uchar)temp;
temp_dec = (uchar)((temp - temp_int) * 100);
lcd_write_cmd(0x80);
lcd_write_data('T');
lcd_write_data('e');
lcd_write_data('m');
lcd_write_data('p');
lcd_write_data(':');
lcd_write_data(' ');
lcd_write_data(temp_int / 10 + '0');
lcd_write_data(temp_int % 10 + '0');
lcd_write_data('.');
lcd_write_data(temp_dec / 10 + '0');
lcd_write_data(temp_dec % 10 + '0');
lcd_write_data('C');
}
// 主函数
void main()
{
float temp;
TMOD = 0x20;
TH1 = TL1 = -(FOSC/12/32/BAUD);
TR1 = 1;
SCON = 0x50;
ES = 1;
EA = 1;
lcd_init();
mlx90614_init();
while(1)
{
temp = mlx90614_get_temp();
lcd_display_temp(temp);
delay_ms(500);
}
}
// 串口中断服务函数
void uart_isr() interrupt 4
{
RI = 0;
TI = 0;
}
```
这段代码使用了STC89C52单片机,通过I2C总线与MLX90614红外测温模块进行通信,读取人体温度值,然后通过LCD1602显示模块将温度值显示出来。
注意,这段代码中串口通信部分还没有实现,如果需要使用串口通信功能,需要自己添加相关代码。
阅读全文