用stm32f103c8t6芯片编写HC—SR04超声波模块用于测距的代码并显示在OLED显示屏上
时间: 2023-09-04 13:08:46 浏览: 114
好的,下面是一个使用STM32F103C8T6控制HC-SR04测距模块,并将测距结果显示在OLED屏幕上的示例代码:
```
#include "stm32f1xx_hal.h"
#include "ssd1306.h"
#include <stdio.h>
#define TRIG_PIN GPIO_PIN_0
#define ECHO_PIN GPIO_PIN_1
#define GPIO_PORT GPIOA
void SystemClock_Config(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = TRIG_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = ECHO_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIO_PORT, &GPIO_InitStruct);
ssd1306_Init();
while (1)
{
HAL_GPIO_WritePin(GPIO_PORT, TRIG_PIN, GPIO_PIN_SET);
HAL_Delay(10);
HAL_GPIO_WritePin(GPIO_PORT, TRIG_PIN, GPIO_PIN_RESET);
uint32_t start_tick = HAL_GetTick();
while (HAL_GPIO_ReadPin(GPIO_PORT, ECHO_PIN) == GPIO_PIN_RESET);
uint32_t end_tick = HAL_GetTick();
uint32_t duration = end_tick - start_tick;
float distance = duration * 0.0343 / 2;
char distance_str[10];
snprintf(distance_str, sizeof(distance_str), "Distance: %.2f cm", distance);
ssd1306_Fill(Black);
ssd1306_SetCursor(0,0);
ssd1306_WriteString(distance_str, Font_7x10, White);
ssd1306_UpdateScreen();
HAL_Delay(1000);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0);
}
```
该代码使用SSD1306 OLED显示屏库,在OLED屏幕上显示测距结果。您需要将相关库添加到您的工程中,并根据您的需要进行修改和完善。
阅读全文