From: AceVest Date: Wed, 3 Jul 2019 10:26:27 +0000 (+0800) Subject: usart dma variable receive length X-Git-Url: http://zhaoyanbai.com/repos/%22http:/www.isc.org/icons/zpipe.c?a=commitdiff_plain;h=811f565322517a8c92cd92bb2c39d6a5efd8fa6d;p=acecode.git usart dma variable receive length --- diff --git a/learn/doc/mac_bash_profile b/learn/doc/mac_bash_profile index 6d3c43c..835a2ef 100644 --- a/learn/doc/mac_bash_profile +++ b/learn/doc/mac_bash_profile @@ -26,7 +26,7 @@ CLOSECOLOR="\[\033[00m\]" #PS1='\[\033[02;37m\]\t\[\033[00m\]\[\033[01;37m\]@\[\033[01;33m\]\W\[\033[00m\]\$ ' #PS1='\[\033[02;37m\]\t\[\033[00m\]\[\033[01;37m\]@\[\033[01;33m\]\W\[\033[00m\]\$ ' -PS1="$GRAY\t$CLOSECOLOR$WHITE@$PURPLE\h $CYAN\W$RED\$ $CLOSECOLOR" +PS1="$RED\t$CLOSECOLOR$YELLOW@$PURPLE\h $CYAN\W$RED\$ $CLOSECOLOR" alias ll='ls -lGh' alias ls='ls -Gh' alias rm='rm -rf' diff --git a/learn/stm32/USART.md b/learn/stm32/USART.md index 094d22b..2fe1377 100644 --- a/learn/stm32/USART.md +++ b/learn/stm32/USART.md @@ -222,4 +222,93 @@ void USART2_IRQHandler(void) { TransferUsartData(); } +``` + +## USART DMA 任意字节接收 +需要把DMA接收模式改为`Circular`模式 + +``` +#define BUFSZ 2 +typedef struct { + uint32_t len; + DMA_HandleTypeDef *dmarx; + uint8_t buf[BUFSZ]; +}UsartDmaData_t; + +#define CBUFSIZE 512 +typedef struct CircleBuffer { + uint32_t rp; + uint32_t wp; + uint8_t buf[CBUFSIZE] +} CircleBuffer_t; + +UsartDmaData_t usart1_dma_data; +CircleBuffer_t circle_buf; + +static uint32_t tick = 0; +void InitUsartDmaTransfer(){ + + __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE); + + memset(&usart1_dma_data, 0, sizeof(usart1_dma_data)); + memset(&circle_buf, 0, sizeof(circle_buf)); + + usart1_dma_data.dmarx = &hdma_usart1_rx; + + HAL_UART_Receive_DMA(&huart1, usart1_dma_data.buf, BUFSZ); + + //HAL_Delay(1000); + HAL_UART_Transmit(&huart1, "AT+CIFSR\r\n", 10, 0xFFFF); +} + + +void TransferUsartData() { + if(circle_buf.rp == circle_buf.wp) { + HAL_Delay(10); // 很重要 + return; + } + + uint8_t t = circle_buf.buf[circle_buf.rp]; + HAL_UART_Transmit(&huart1, &t, 1, 0xFFFF); + circle_buf.rp = (circle_buf.rp + 1) % CBUFSIZE; +} + +void WriteCircleData(uint8_t *data, uint32_t size) { + for(uint32_t i=0; iInstance != USART1) { + return ; + } + uint32_t flag = __HAL_UART_GET_FLAG(huart,UART_FLAG_IDLE); + if(flag == RESET) { + return; + } + + __HAL_UART_CLEAR_IDLEFLAG(huart); + + HAL_UART_DMAStop(huart); + + WriteCircleData(usart1_dma_data.buf, BUFSZ - usart1_dma_data.dmarx->Instance->CNDTR); + + HAL_UART_Receive_DMA(&huart1, usart1_dma_data.buf, BUFSZ); +} ``` \ No newline at end of file