GY-906BAA红外传感器 把温度数据传给stm32f103c8t6 的代码
时间: 2023-08-02 09:08:25 浏览: 110
好的,以下是一个简单的示例代码,用于从GY-906BAA红外传感器读取温度数据,并将其存储到stm32f103c8t6的内存中:
```c
#include "stm32f10x.h"
#include "stm32f10x_i2c.h"
#define GY906BAA_ADDR 0x5A
void I2C_init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
/* Enable I2C1 clock */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
/* Enable GPIOB clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
/* Configure I2C1 pins: SCL and SDA */
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);
/* Configure 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);
/* Enable I2C1 */
I2C_Cmd(I2C1, ENABLE);
}
uint16_t GY906BAA_read_temp(void)
{
uint8_t buf[3];
uint16_t temp;
/* Send command to GY-906BAA to read temperature */
buf[0] = 0x01;
buf[1] = 0x80;
buf[2] = 0x00;
I2C_AcknowledgeConfig(I2C1, ENABLE);
I2C_GenerateSTART(I2C1, ENABLE);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1, GY906BAA_ADDR, I2C_Direction_Transmitter);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED));
I2C_SendData(I2C1, buf[0]);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_SendData(I2C1, buf[1]);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_SendData(I2C1, buf[2]);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED));
I2C_GenerateSTOP(I2C1, ENABLE);
/* Read temperature data from GY-906BAA */
I2C_AcknowledgeConfig(I2C1, ENABLE);
I2C_GenerateSTART(I2C1, ENABLE);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT));
I2C_Send7bitAddress(I2C1, GY906BAA_ADDR, I2C_Direction_Receiver);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED));
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
buf[0] = I2C_ReceiveData(I2C1);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
buf[1] = I2C_ReceiveData(I2C1);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED));
I2C_AcknowledgeConfig(I2C1, DISABLE);
I2C_GenerateSTOP(I2C1, ENABLE);
temp = buf[0] << 8 | buf[1];
return temp;
}
int main(void)
{
uint16_t temp;
/* Initialize I2C */
I2C_init();
/* Read temperature data from GY-906BAA */
temp = GY906BAA_read_temp();
/* Store temperature data in STM32F103C8T6's memory */
// TODO: Add your code here
while (1);
}
```
需要注意的是,以上示例代码仅供参考,具体实现还需要根据您的硬件和软件环境进行调整。同时,为了保证代码的可靠性和稳定性,建议您在实现过程中使用一些常见的库和工具,比如HAL库、CubeMX等。
阅读全文