How to create a Ready-to-use STM32CubeIDE project for DS18B20?

 Here's a step-by-step guide to create a ready-to-use STM32CubeIDE project for reading temperature from the DS18B20 sensor using STM32 HAL. The example assumes you're using STM32F103C8T6 ("Blue Pill") but can be adapted to other STM32 chips.




Project Overview

  • Microcontroller: STM32F103C8T6

  • Sensor: DS18B20

  • Interface: 1-Wire protocol (bit-banged using GPIO)

  • Development Tool: STM32CubeIDE

  • Library: MaJerle's OneWire and DS18B20 drivers (HAL-compatible)


Wiring Recap

DS18B20 PinConnect To STM32
GNDGND
VDD3.3V
DQPA1 (or your chosen GPIO)
4.7 kΩBetween DQ and VDD

Project Setup Steps

 1. Create a New Project

  • Open STM32CubeIDE

  • File → New → STM32 Project

  • Select STM32F103C8T6 (or your MCU)

  • Name your project: DS18B20_Project


 2. Configure GPIO

  • Open .ioc file

  • Set PA1 as GPIO_Output

  • Enable USART1 (optional, for serial print/debug)

  • Enable SYS → Debug: Serial Wire (for SWD debugging)


 3. Add DS18B20 + OneWire HAL Libraries

You can use MaJerle’s libraries:

Files to Add:

  • on1wire.c, on1wire.h

  • ds18b20.c, ds18b20.h

  • Add them to Core/Src/ and Core/Inc/ folders in CubeIDE.

 Modify onewire.c/h:

  • Set ONEWIRE_MAX_DEV = 1 if using 1 sensor.

  • Set the correct GPIO and PORT used (PA1).


 4. Main Code (main.c)

Inside main.c, modify like this:

c

#include "onewire.h" #include "ds18b20.h" #include "stdio.h" float temp; char buffer[32]; int main(void) { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); MX_USART1_UART_Init(); // Optional OneWire_t ow; OneWire_Init(&ow, GPIOA, GPIO_PIN_1); // PA1 uint8_t rom[8]; if (OneWire_Search(&ow, rom)) { while (1) { DS18B20_Start(&ow, rom, DS18B20_Resolution_12bits); HAL_Delay(750); // Max conversion time temp = DS18B20_ReadTemperature(&ow, rom); sprintf(buffer, "Temp: %.2f C\r\n", temp); HAL_UART_Transmit(&huart1, (uint8_t*)buffer, strlen(buffer), HAL_MAX_DELAY); HAL_Delay(1000); } } else { // No sensor found while (1) { HAL_UART_Transmit(&huart1, (uint8_t*)"No DS18B20\r\n", 12, HAL_MAX_DELAY); HAL_Delay(1000); } } }

Build and Flash

  • Press Build 

  • Flash using ST-Link or USB-UART (e.g. via bootloader)

  • Open serial monitor at 9600 baud to view temperature readings


Helpful Notes

  • You can use CubeMX middleware for UART or printf if needed.

  • For multiple sensors, use OneWire_Search and loop through detected ROMs.

  • For STM32F4, replace HAL GPIO setup and clocks accordingly.

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What is a Look-Up Table (LUT) in an FPGA, and how does it work?

Detailed Explanation of STM32 HAL Library Clock System