stm32f103实现gy906红外测温仪
时间: 2023-07-14 16:14:08 浏览: 271
实现GY906红外测温仪需要以下步骤:
1.连接GY906模块
将GY906模块的SCL和SDA引脚分别连接到STM32F103的I2C1的SCL和SDA引脚上,同时将GY906模块的GND和VCC引脚分别连接到STM32F103的GND和3.3V引脚上。
2.初始化I2C总线
使用STM32F103的I2C1接口,需要初始化I2C总线。具体实现可以使用STM32CubeMX自动生成代码。
3.读取GY906数据
通过I2C总线向GY906模块发送读取温度命令,并接收GY906返回的温度数据。具体实现可以参考GY906模块的说明书,根据从GY906模块返回的数据计算出温度值。
4.显示温度值
将计算出的温度值通过串口或者LCD等方式显示出来。
下面是一个简单的示例代码:
```c
#include "stm32f10x.h"
#include "stdio.h"
#define GY906_ADDR 0x5A
void I2C_Configuration(void);
float getTemperature(void);
int main()
{
I2C_Configuration();
float temperature;
while(1)
{
temperature = getTemperature();
printf("temperature:%.2f\r\n", temperature);
}
}
void I2C_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_DeInit(I2C1);
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);
}
float getTemperature(void)
{
uint8_t data[3];
float temperature;
// Send read command
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1, GY906_ADDR << 1, I2C_Direction_Transmitter);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C1, 0x07);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTOP(I2C1, ENABLE);
// Read temperature data
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1, GY906_ADDR << 1, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
data[0] = I2C_ReceiveData(I2C1);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
data[1] = I2C_ReceiveData(I2C1);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
data[2] = I2C_ReceiveData(I2C1);
I2C_AcknowledgeConfig(I2C1, DISABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
// Calculate temperature
temperature = (data[0] + (data[1] << 8)) * 0.02 - 273.15;
return temperature;
}
```
注意:以上代码仅供参考,具体实现需要根据GY906模块的说明书和STM32F103的数据手册进行修改。
阅读全文