libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
ch32_uart.cpp
1// ch32_uart.cpp
2
3#include "ch32_uart.hpp"
4
5#include "ch32_dma.hpp"
6#include "ch32_gpio.hpp"
7
8using namespace LibXR;
9
10// === 静态对象指针表 ===
11CH32UART *CH32UART::map[ch32_uart_id_t::CH32_UART_NUMBER] = {nullptr};
12
13// === 构造函数:串口+DMA+GPIO初始化 ===
14CH32UART::CH32UART(ch32_uart_id_t id, RawData dma_rx, RawData dma_tx,
15 GPIO_TypeDef *tx_gpio_port, uint16_t tx_gpio_pin,
16 GPIO_TypeDef *rx_gpio_port, uint16_t rx_gpio_pin, uint32_t pin_remap,
17 uint32_t tx_queue_size, UART::Configuration config)
18 : UART(&_read_port, &_write_port),
19 id_(id),
20 _read_port(dma_rx.size_),
21 _write_port(tx_queue_size, dma_tx.size_ / 2),
22 dma_buff_rx_(dma_rx),
23 dma_buff_tx_(dma_tx),
24 instance_(CH32_UART_GetInstanceID(id)),
25 dma_rx_channel_(CH32_UART_RX_DMA_CHANNEL_MAP[id]),
26 dma_tx_channel_(CH32_UART_TX_DMA_CHANNEL_MAP[id])
27{
28 map[id] = this;
29
30 bool tx_enable = dma_tx.size_ > 1;
31 bool rx_enable = dma_rx.size_ > 0;
32
33 ASSERT(tx_enable || rx_enable);
34
35 /* GPIO配置(TX: 推挽输出,RX: 悬空输入) */
36 GPIO_InitTypeDef gpio_init = {};
37 gpio_init.GPIO_Speed = GPIO_Speed_50MHz;
38
39 if (tx_enable)
40 {
41 (*write_port_) = WriteFun;
42 gpio_init.GPIO_Pin = tx_gpio_pin;
43 gpio_init.GPIO_Mode = GPIO_Mode_AF_PP;
44 GPIO_Init(tx_gpio_port, &gpio_init);
45 RCC_APB2PeriphClockCmd(CH32GetGPIOPeriph(tx_gpio_port), ENABLE);
46 }
47
48 if (rx_enable)
49 {
50 (*read_port_) = ReadFun;
51 gpio_init.GPIO_Pin = rx_gpio_pin;
52 gpio_init.GPIO_Mode = GPIO_Mode_IN_FLOATING;
53 GPIO_Init(rx_gpio_port, &gpio_init);
54 RCC_APB2PeriphClockCmd(CH32GetGPIOPeriph(rx_gpio_port), ENABLE);
55 }
56
57 /* 可选:引脚重映射 */
58 if (pin_remap != 0)
59 {
60 RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
61 GPIO_PinRemapConfig(pin_remap, ENABLE);
62 }
63
64 /* 串口外设时钟使能 */
65 if (CH32_UART_APB_MAP[id] == 1)
66 {
67 RCC_APB1PeriphClockCmd(CH32_UART_RCC_PERIPH_MAP[id], ENABLE);
68 }
69 else if (CH32_UART_APB_MAP[id] == 2)
70 {
71 RCC_APB2PeriphClockCmd(CH32_UART_RCC_PERIPH_MAP[id], ENABLE);
72 }
73 else
74 {
75 ASSERT(false);
76 }
77 RCC_AHBPeriphClockCmd(CH32_UART_RCC_PERIPH_MAP_DMA[id], ENABLE);
78
79 // 3. USART 配置
80 USART_InitTypeDef usart_cfg = {};
81 usart_cfg.USART_BaudRate = config.baudrate;
82 usart_cfg.USART_StopBits =
83 (config.stop_bits == 2) ? USART_StopBits_2 : USART_StopBits_1;
84 switch (config.parity)
85 {
86 case UART::Parity::NO_PARITY:
87 usart_cfg.USART_Parity = USART_Parity_No;
88 usart_cfg.USART_WordLength = USART_WordLength_8b;
89 break;
90 case UART::Parity::EVEN:
91 usart_cfg.USART_Parity = USART_Parity_Even;
92 usart_cfg.USART_WordLength = USART_WordLength_9b;
93 break;
94 case UART::Parity::ODD:
95 usart_cfg.USART_Parity = USART_Parity_Odd;
96 usart_cfg.USART_WordLength = USART_WordLength_9b;
97 break;
98 default:
99 ASSERT(false);
100 }
101
102 usart_cfg.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
103 usart_cfg.USART_Mode =
104 (tx_enable ? USART_Mode_Tx : 0) | (rx_enable ? USART_Mode_Rx : 0);
105 uart_mode_ = usart_cfg.USART_Mode;
106 USART_Init(instance_, &usart_cfg);
107
108 /* DMA 配置 */
109 DMA_InitTypeDef dma_init = {};
110 dma_init.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
111 dma_init.DMA_MemoryInc = DMA_MemoryInc_Enable;
112 dma_init.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
113 dma_init.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
114 dma_init.DMA_Priority = DMA_Priority_High;
115 dma_init.DMA_M2M = DMA_M2M_Disable;
116
117 if (rx_enable)
118 {
119 DMA_DeInit(dma_rx_channel_);
120 dma_init.DMA_PeripheralBaseAddr = (uint32_t)&instance_->DATAR;
121 dma_init.DMA_MemoryBaseAddr = (uint32_t)dma_buff_rx_.addr_;
122 dma_init.DMA_DIR = DMA_DIR_PeripheralSRC;
123 dma_init.DMA_Mode = DMA_Mode_Circular;
124 dma_init.DMA_BufferSize = dma_buff_rx_.size_;
125 DMA_Init(dma_rx_channel_, &dma_init);
126 DMA_Cmd(dma_rx_channel_, ENABLE);
127 USART_DMACmd(instance_, USART_DMAReq_Rx, ENABLE);
128 }
129
130 if (tx_enable)
131 {
132 DMA_DeInit(dma_tx_channel_);
133 dma_init.DMA_PeripheralBaseAddr = (u32)(&instance_->DATAR);
134 dma_init.DMA_MemoryBaseAddr = 0;
135 dma_init.DMA_DIR = DMA_DIR_PeripheralDST;
136 dma_init.DMA_Mode = DMA_Mode_Normal;
137 dma_init.DMA_BufferSize = 0;
138 DMA_Init(dma_tx_channel_, &dma_init);
139 DMA_ITConfig(dma_tx_channel_, DMA_IT_TC, ENABLE);
140 USART_DMACmd(instance_, USART_DMAReq_Tx, ENABLE);
141 }
142
143 // 6. USART和相关中断
144 USART_Cmd(instance_, ENABLE);
145
146 if (rx_enable)
147 {
148 USART_ITConfig(instance_, USART_IT_IDLE, ENABLE);
149 }
150
151 if (tx_enable)
152 {
153 NVIC_EnableIRQ(CH32_DMA_IRQ_MAP[CH32_DMA_GetID(dma_tx_channel_)]);
154 }
155
156 NVIC_EnableIRQ(CH32_UART_IRQ_MAP[id]);
157}
158
159// === 串口运行时配置变更 ===
161{
162 USART_InitTypeDef usart_cfg = {};
163 usart_cfg.USART_BaudRate = config.baudrate;
164 usart_cfg.USART_StopBits =
165 (config.stop_bits == 2) ? USART_StopBits_2 : USART_StopBits_1;
166
167 switch (config.parity)
168 {
170 usart_cfg.USART_Parity = USART_Parity_No;
171 usart_cfg.USART_WordLength = USART_WordLength_8b;
172 break;
174 usart_cfg.USART_Parity = USART_Parity_Even;
175 usart_cfg.USART_WordLength = USART_WordLength_9b;
176 break;
178 usart_cfg.USART_Parity = USART_Parity_Odd;
179 usart_cfg.USART_WordLength = USART_WordLength_9b;
180 break;
181 default:
182 return ErrorCode::NOT_SUPPORT;
183 }
184
185 usart_cfg.USART_Mode = uart_mode_;
186 usart_cfg.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
187 USART_DeInit(instance_);
188 USART_Init(instance_, &usart_cfg);
189
190 if (uart_mode_ & USART_Mode_Rx)
191 {
192 USART_DMACmd(instance_, USART_DMAReq_Rx, ENABLE);
193 USART_ITConfig(instance_, USART_IT_IDLE, ENABLE);
194 }
195
196 if (uart_mode_ & USART_Mode_Tx)
197 {
198 USART_DMACmd(instance_, USART_DMAReq_Tx, ENABLE);
199 }
200
201 USART_Cmd(instance_, ENABLE);
202
203 return ErrorCode::OK;
204}
205
206// === 写操作回调(DMA搬运) ===
207ErrorCode CH32UART::WriteFun(WritePort &port)
208{
209 CH32UART *uart = CONTAINER_OF(&port, CH32UART, _write_port);
210 if (!uart->dma_buff_tx_.HasPending())
211 {
212 WriteInfoBlock info;
213 if (port.queue_info_->Peek(info) != ErrorCode::OK)
214 {
215 return ErrorCode::EMPTY;
216 }
217
218 uint8_t *buffer = nullptr;
219 bool use_pending = false;
220
221 // DMA空闲判断
222 bool dma_ready = uart->dma_tx_channel_->CNTR == 0;
223 if (dma_ready)
224 {
225 buffer = reinterpret_cast<uint8_t *>(uart->dma_buff_tx_.ActiveBuffer());
226 }
227 else
228 {
229 buffer = reinterpret_cast<uint8_t *>(uart->dma_buff_tx_.PendingBuffer());
230 use_pending = true;
231 }
232
233 if (port.queue_data_->PopBatch(buffer, info.data.size_) != ErrorCode::OK)
234 {
235 ASSERT(false);
236 return ErrorCode::EMPTY;
237 }
238
239 if (use_pending)
240 {
241 uart->dma_buff_tx_.EnablePending();
242 // 检查当前DMA是否可切换
243 bool dma_ready = uart->dma_tx_channel_->CNTR == 0;
244 if (dma_ready && uart->dma_buff_tx_.HasPending())
245 {
246 uart->dma_buff_tx_.Switch();
247 }
248 else
249 {
250 return ErrorCode::FAILED;
251 }
252 }
253
254 port.queue_info_->Pop(uart->write_info_active_);
255
256 DMA_Cmd(uart->dma_tx_channel_, DISABLE);
257 uart->dma_tx_channel_->MADDR =
258 reinterpret_cast<uint32_t>(uart->dma_buff_tx_.ActiveBuffer());
259 uart->dma_tx_channel_->CNTR = info.data.size_;
260 DMA_Cmd(uart->dma_tx_channel_, ENABLE);
261
262 return ErrorCode::FAILED; // 实际是发起传输成功,但等待DMA完成
263 }
264 return ErrorCode::FAILED;
265}
266
267// === 读操作回调(由中断驱动) ===
268ErrorCode CH32UART::ReadFun(ReadPort &port)
269{
270 UNUSED(port);
271 // 接收由 IDLE 中断驱动,读取在 ISR 中完成
272 return ErrorCode::EMPTY;
273}
274
275// === USART IDLE中断服务 ===
276extern "C" void CH32_UART_ISR_Handler_IDLE(ch32_uart_id_t id)
277{
278 auto uart = CH32UART::map[id];
279 if (!uart)
280 {
281 return;
282 }
283
284 // 检查和清除IDLE标志
285 if (!USART_GetITStatus(uart->instance_, USART_IT_IDLE))
286 {
287 return;
288 }
289
290 USART_ReceiveData(uart->instance_);
291
292 auto rx_buf = static_cast<uint8_t *>(uart->dma_buff_rx_.addr_);
293 size_t dma_size = uart->dma_buff_rx_.size_;
294 size_t curr_pos = dma_size - uart->dma_rx_channel_->CNTR;
295 size_t last_pos = uart->last_rx_pos_;
296
297 if (curr_pos != last_pos)
298 {
299 if (curr_pos > last_pos)
300 {
301 // 普通区间
302 uart->_read_port.queue_data_->PushBatch(&rx_buf[last_pos], curr_pos - last_pos);
303 }
304 else
305 {
306 // 回卷区
307 uart->_read_port.queue_data_->PushBatch(&rx_buf[last_pos], dma_size - last_pos);
308 uart->_read_port.queue_data_->PushBatch(&rx_buf[0], curr_pos);
309 }
310 uart->last_rx_pos_ = curr_pos;
311 uart->_read_port.ProcessPendingReads(true);
312 }
313}
314
315// === DMA TX完成中断服务 ===
316extern "C" void CH32_UART_ISR_Handler_TX_CPLT(ch32_uart_id_t id)
317{
318 auto uart = CH32UART::map[id];
319 if (!uart)
320 {
321 return;
322 }
323
324 DMA_ClearITPendingBit(CH32_UART_TX_DMA_IT_MAP[id]);
325
326 WriteInfoBlock &current_info = uart->write_info_active_;
327 uart->_write_port.write_size_ = current_info.data.size_; // 标记已发送
328 current_info.op.UpdateStatus(true, ErrorCode::OK); // 标记操作完成
329
330 if (!uart->dma_buff_tx_.HasPending())
331 {
332 return;
333 }
334
335 // 有pending包,继续取下一包
336 if (uart->_write_port.queue_info_->Pop(current_info) != ErrorCode::OK)
337 {
338 ASSERT(false);
339 return;
340 }
341 uart->dma_buff_tx_.Switch();
342
343 auto *buf = reinterpret_cast<uint8_t *>(uart->dma_buff_tx_.ActiveBuffer());
344 DMA_Cmd(uart->dma_tx_channel_, DISABLE);
345 uart->dma_tx_channel_->MADDR = (uint32_t)buf;
346 uart->dma_tx_channel_->CNTR = current_info.data.size_;
347 DMA_Cmd(uart->dma_tx_channel_, ENABLE);
348
349 current_info.op.MarkAsRunning();
350
351 // 预装pending区
352 WriteInfoBlock next_info;
353 if (uart->write_port_->queue_info_->Peek(next_info) != ErrorCode::OK)
354 {
355 return;
356 }
357
358 if (uart->write_port_->queue_data_->PopBatch(
359 reinterpret_cast<uint8_t *>(uart->dma_buff_tx_.PendingBuffer()),
360 next_info.data.size_) != ErrorCode::OK)
361 {
362 ASSERT(false);
363 return;
364 }
365 uart->dma_buff_tx_.EnablePending();
366}
367
368// === DMA 通道中断回调 ===
369void CH32UART::DmaIRQHandler(DMA_Channel_TypeDef *channel, ch32_uart_id_t id)
370{
371 if (DMA_GetITStatus(CH32_UART_TX_DMA_IT_MAP[id]) == RESET) return;
372
373 if (channel->CNTR == 0) CH32_UART_ISR_Handler_TX_CPLT(id);
374}
375
376// === 各类串口中断入口适配 ===
377#if defined(USART1)
378extern "C" void USART1_IRQHandler(void) __attribute__((interrupt));
379extern "C" void USART1_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART1); }
380#endif
381#if defined(USART2)
382extern "C" void USART2_IRQHandler(void) __attribute__((interrupt));
383extern "C" void USART2_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART2); }
384#endif
385#if defined(USART3)
386extern "C" void USART3_IRQHandler(void) __attribute__((interrupt));
387extern "C" void USART3_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART3); }
388#endif
389#if defined(USART4)
390extern "C" void USART4_IRQHandler(void) __attribute__((interrupt));
391extern "C" void USART4_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART4); }
392#endif
393#if defined(USART5)
394extern "C" void USART5_IRQHandler(void) __attribute__((interrupt));
395extern "C" void USART5_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART5); }
396#endif
397#if defined(USART6)
398extern "C" void USART6_IRQHandler(void) __attribute__((interrupt));
399extern "C" void USART6_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART6); }
400#endif
401#if defined(USART7)
402extern "C" void USART7_IRQHandler(void) __attribute__((interrupt));
403extern "C" void USART7_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART7); }
404#endif
405#if defined(USART8)
406extern "C" void USART8_IRQHandler(void) __attribute__((interrupt));
407extern "C" void USART8_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_USART8); }
408#endif
409#if defined(UART1)
410extern "C" void UART1_IRQHandler(void) __attribute__((interrupt));
411extern "C" void UART1_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART1); }
412#endif
413#if defined(UART2)
414extern "C" void UART2_IRQHandler(void) __attribute__((interrupt));
415extern "C" void UART2_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART2); }
416#endif
417#if defined(UART3)
418extern "C" void UART3_IRQHandler(void) __attribute__((interrupt));
419extern "C" void UART3_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART3); }
420#endif
421#if defined(UART4)
422extern "C" void UART4_IRQHandler(void) __attribute__((interrupt));
423extern "C" void UART4_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART4); }
424#endif
425#if defined(UART5)
426extern "C" void UART5_IRQHandler(void) __attribute__((interrupt));
427extern "C" void UART5_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART5); }
428#endif
429#if defined(UART6)
430extern "C" void UART6_IRQHandler(void) __attribute__((interrupt));
431extern "C" void UART6_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART6); }
432#endif
433#if defined(UART7)
434extern "C" void UART7_IRQHandler(void) __attribute__((interrupt));
435extern "C" void UART7_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART7); }
436#endif
437#if defined(UART8)
438extern "C" void UART8_IRQHandler(void) __attribute__((interrupt));
439extern "C" void UART8_IRQHandler(void) { CH32_UART_ISR_Handler_IDLE(CH32_UART8); }
440#endif
ErrorCode SetConfig(UART::Configuration config)
设置 UART 配置 / Sets the UART configuration
size_t size_
数据大小(字节)。 The size of the data (in bytes).
bool HasPending() const
判断是否有待切换的缓冲区 Checks whether a pending buffer is ready
uint8_t * ActiveBuffer()
获取当前正在使用的缓冲区指针 Returns the currently active buffer
void Switch()
切换到备用缓冲区(若其有效) Switches to the pending buffer if it's valid
uint8_t * PendingBuffer()
获取备用缓冲区的指针 Returns the pending (inactive) buffer
void EnablePending()
手动启用 pending 状态 Manually sets the pending state to true
ErrorCode PushBatch(const Data *data, size_t size)
批量推入数据 / Pushes multiple elements into the queue
ErrorCode PopBatch(Data *data, size_t size)
批量弹出数据 / Pops multiple elements from the queue
void MarkAsRunning()
标记操作为运行状态。 Marks the operation as running.
Definition libxr_rw.hpp:204
void UpdateStatus(bool in_isr, Status &&...status)
Updates operation status based on type.
Definition libxr_rw.hpp:173
原始数据封装类。 A class for encapsulating raw data.
size_t size_
数据大小(字节)。 The size of the data (in bytes).
void * addr_
数据存储地址。 The storage address of the data.
ReadPort class for handling read operations.
Definition libxr_rw.hpp:270
virtual void ProcessPendingReads(bool in_isr)
Processes pending reads.
Definition libxr_rw.hpp:501
通用异步收发传输(UART)基类 / Abstract base class for Universal Asynchronous Receiver-Transmitter (UART)
Definition uart.hpp:19
@ NO_PARITY
无校验 / No parity
@ ODD
奇校验 / Odd parity
@ EVEN
偶校验 / Even parity
WritePort * write_port_
写入端口 / Write port
Definition uart.hpp:52
WritePort class for handling write operations.
Definition libxr_rw.hpp:564
LibXR 命名空间
Definition ch32_gpio.hpp:9
ErrorCode(* ReadFun)(ReadPort &port)
Function pointer type for read operations.
Definition libxr_rw.hpp:247
ErrorCode(* WriteFun)(WritePort &port)
Function pointer type for write operations.
Definition libxr_rw.hpp:243
UART 配置结构体 / UART configuration structure.
Definition uart.hpp:44
uint8_t stop_bits
停止位长度 / Number of stop bits
Definition uart.hpp:48
Parity parity
校验模式 / Parity mode
Definition uart.hpp:46
uint32_t baudrate
波特率 / Baud rate
Definition uart.hpp:45