利用gy906的代码.
时间: 2023-07-03 21:21:14 浏览: 44
好的,下面是使用GY906红外温度传感器的代码示例,该代码使用89C52单片机和GY906进行连接,读取GY906输出的温度数据并在LCD屏幕上显示出来。
```
#include <reg52.h>
#include <intrins.h>
//定义端口
#define wela P2
#define dula P2
#define DATA P0
#define SDA P1_7
#define SCL P1_6
//定义函数
void delay(unsigned int i);
void init();
void write_com(unsigned char com);
void write_data(unsigned char dat);
void display(unsigned char addr,unsigned char dat);
unsigned char read_i2c(unsigned char addr,unsigned char reg);
void write_i2c(unsigned char addr,unsigned char reg,unsigned char dat);
//主函数
void main()
{
unsigned char temp[2]; //存储温度数据
unsigned int temperature; //存储温度值
init(); //初始化
while(1)
{
temperature = read_i2c(0xD0,0x07)*256 + read_i2c(0xD0,0x06); //读取温度值
temperature = temperature*0.02 - 273.15; //将温度值转换为摄氏度
display(0x80,temperature/100); //显示百位数字
display(0x81,temperature%100/10); //显示十位数字
display(0x82,temperature%10); //显示个位数字
delay(500); //延时0.5s
}
}
//延时函数
void delay(unsigned int i)
{
while(i--);
}
//初始化函数
void init()
{
write_com(0x38); //开显示
write_com(0x0c); //开光标、不显示
write_com(0x06); //写数据时光标自动加1
write_com(0x01); //清屏
}
//写命令函数
void write_com(unsigned char com)
{
DATA = com; //将命令写入数据口
dula = 0; //清除锁存器
_nop_(); //空操作
_nop_();
dula = 1; //锁存器锁存
}
//写数据函数
void write_data(unsigned char dat)
{
DATA = dat; //将数据写入数据口
dula = 0; //清除锁存器
_nop_(); //空操作
_nop_();
dula = 1; //锁存器锁存
}
//显示函数
void display(unsigned char addr,unsigned char dat)
{
wela = 0; //清除锁存器
_nop_(); //空操作
_nop_();
wela = 1; //锁存器锁存
write_com(addr); //写入地址
write_data(dat+'0'); //写入数字
}
//I2C读取函数
unsigned char read_i2c(unsigned char addr,unsigned char reg)
{
unsigned char dat;
SDA = 1; //SDA线置高
SCL = 1; //SCL线置高
_nop_(); //空操作
_nop_();
SDA = 0; //SDA线置低(起始信号)
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
write_i2c(addr,reg,0); //写入寄存器地址
SDA = 1; //SDA线置高(停止信号)
_nop_();
_nop_();
SCL = 1; //SCL线置高
_nop_();
_nop_();
SDA = 1; //SDA线置高
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
SDA = 0; //SDA线置低(起始信号)
_nop_();
_nop_();
addr = addr | 0x01; //读取地址
write_i2c(addr,0,0); //写入读取地址
SDA = 1; //SDA线置高
_nop_();
_nop_();
SCL = 1; //SCL线置高
_nop_();
_nop_();
dat = DATA; //读取数据
SDA = 1; //SDA线置高(停止信号)
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
return dat;
}
//I2C写入函数
void write_i2c(unsigned char addr,unsigned char reg,unsigned char dat)
{
SDA = 1; //SDA线置高
SCL = 1; //SCL线置高
_nop_(); //空操作
_nop_();
SDA = 0; //SDA线置低(起始信号)
_nop_();
_nop_();
DATA = addr; //写入设备地址
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
SDA = 1; //SDA线置高(ACK信号)
_nop_();
_nop_();
DATA = reg; //写入寄存器地址
_nop_();
_nop_();
SCL = 1; //SCL线置高
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
SDA = 1; //SDA线置高(ACK信号)
_nop_();
_nop_();
DATA = dat; //写入数据
_nop_();
_nop_();
SCL = 1; //SCL线置高
_nop_();
_nop_();
SCL = 0; //SCL线置低
_nop_();
_nop_();
SDA = 1; //SDA线置高(停止信号)
_nop_();
_nop_();
}
```
需要注意的是,该代码中使用的读取温度值的计算方法适用于GY906型号的红外温度传感器,如果您使用的是其他型号的红外温度传感器,可能需要根据传感器的数据手册进行相应的调整。