新增 Hc05 类,支持 HC-05 蓝牙模块的串口通信,增加串口设置波特率函数
All checks were successful
Build and Upload Artifact / build and upload-artifact (push) Successful in 19m59s

This commit is contained in:
chauyin
2025-05-12 21:57:21 +08:00
parent c3e0edd72d
commit 17d298c782
9 changed files with 119 additions and 18 deletions

View File

@@ -1,6 +1,7 @@
#pragma once
#include "main.h"
#include "stm32h5xx_hal_uart.h"
#include <cstdarg>
#include <cstdint>
#include <cstring>
@@ -13,23 +14,31 @@ private:
uint32_t timeout;
std::unique_ptr<char[]> buffer;
uint8_t ReadByteForce() {
return handle->Instance->RDR;
}
public:
SerialPort(UART_HandleTypeDef* uart, uint32_t length, uint32_t timeout)
: handle(uart), timeout(timeout), buffer(std::make_unique<char[]>(length)) {}
SerialPort(UART_HandleTypeDef* uart, uint32_t baudRate, uint32_t length, uint32_t timeout)
: handle(uart), timeout(timeout), buffer(std::make_unique<char[]>(length)) {
SetBaudRate(baudRate);
}
~SerialPort() = default;
uint8_t ReadByte() {
return handle->Instance->RDR;
void SetBaudRate(uint32_t baudRate) {
HAL_UART_DeInit(handle);
handle->Init.BaudRate = baudRate;
HAL_UART_Init(handle);
}
std::string ReadLine() {
std::string result;
result.reserve(128);
char c;
ReadByte();
ReadByteForce();
while (true) {
auto r = HAL_UART_Receive(handle, reinterpret_cast<uint8_t*>(&c), sizeof(c), timeout);
auto r = HAL_UART_Receive(handle, reinterpret_cast<uint8_t*>(&c), sizeof(c), timeout);
if (r != HAL_OK) {
throw std::runtime_error("UART receive error");
}