stm32f103c8t6读取ds18b20的温度并将温度信息传输给I2C总线库函数代码
时间: 2023-08-02 16:08:26 浏览: 96
以下是基于STM32 HAL库实现的读取DS18B20温度并将温度信息通过I2C总线传输的代码:
```c
#include "main.h"
#include "stm32f1xx_hal.h"
#include "ds18b20.h"
#include "i2c.h"
/* DS18B20引脚定义 */
#define DS18B20_GPIO_PORT GPIOA
#define DS18B20_GPIO_PIN GPIO_PIN_1
/* I2C设备地址 */
#define I2C_DEVICE_ADDRESS 0x50
/* 定义I2C发送和接收缓冲区 */
uint8_t txBuffer[2];
uint8_t rxBuffer[2];
void SystemClock_Config(void);
int main(void)
{
/* MCU初始化 */
HAL_Init();
SystemClock_Config();
/* I2C初始化 */
MX_I2C1_Init();
/* DS18B20初始化 */
ds18b20_init(DS18B20_GPIO_PORT, DS18B20_GPIO_PIN);
while (1)
{
float temperature = ds18b20_get_temperature(DS18B20_GPIO_PORT, DS18B20_GPIO_PIN);
/* 将温度转换为两个字节的数据 */
uint16_t tempData = (uint16_t)(temperature * 10);
txBuffer[0] = tempData >> 8;
txBuffer[1] = tempData & 0xFF;
/* 发送温度数据到I2C */
HAL_I2C_Master_Transmit(&hi2c1, I2C_DEVICE_ADDRESS, txBuffer, 2, HAL_MAX_DELAY);
/* 等待I2C传输完成 */
HAL_Delay(1000);
}
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
```
需要注意的是,该代码使用了自定义的DS18B20库文件(ds18b20.h和ds18b20.c),需要在项目中添加这两个文件。
同时,需要在CubeMX中配置I2C的GPIO引脚和时钟,并生成代码。
阅读全文