]> Zhao Yanbai Git Server - acecode.git/commitdiff
usart1 usart2 之间重定向
authorAceVest <zhaoyanbai@126.com>
Fri, 7 Jun 2019 13:31:13 +0000 (21:31 +0800)
committerAceVest <zhaoyanbai@126.com>
Fri, 7 Jun 2019 13:31:13 +0000 (21:31 +0800)
learn/stm32/USART.md

index 080af4fe47bdaa2f5499219bdbe27a6fb81b0cd0..12076be80fd8014d92cc806eecea9a9225cd2fab 100644 (file)
@@ -25,4 +25,78 @@ PUTCHAR_PROTOTYPE
 
 `Mode: Asynchronous`
 
-`Hadware Flow Control (RS233): Disable`
\ No newline at end of file
+`Hadware Flow Control (RS233): Disable`
+
+
+
+# USART1、USART2转发
+
+需要开启这两个串口的中断
+
+```
+#define USART_RX_BUFSZ 10
+typedef struct {
+       uint8_t rxdata;
+       uint8_t rxbuf[USART_RX_BUFSZ];
+       uint16_t rxwp;
+       uint16_t rxrp;
+} UsartData_t;
+
+UsartData_t usart1_data;
+UsartData_t usart2_data;
+
+
+void InitUsartTransfer(){
+       usart1_data.rxrp = usart1_data.rxwp = 0;
+       usart2_data.rxrp = usart2_data.rxwp = 0;
+       if(HAL_OK != HAL_UART_Receive_IT(&huart1, &usart1_data.rxdata, 1)) {
+               Error_Handler();
+       }
+
+       if(HAL_OK != HAL_UART_Receive_IT(&huart2, &usart2_data.rxdata, 1)) {
+               Error_Handler();
+       }
+}
+
+void TransferToUsart(UsartData_t *data, UART_HandleTypeDef *to_huart){
+       uint16_t rxwp = data->rxwp;
+       if(data->rxrp == rxwp) {
+               // empty
+               return ;
+       }
+       HAL_UART_Transmit(to_huart, data->rxbuf+data->rxrp, 1, 0xFFFF);
+       data->rxrp = (data->rxrp + 1) % USART_RX_BUFSZ;
+}
+
+void TransferUsartData() {
+       TransferToUsart(&usart1_data, &huart2);
+       TransferToUsart(&usart2_data, &huart1);
+}
+
+void ReceiveUsartData(UsartData_t *data, UART_HandleTypeDef *huart) {
+       if((data->rxwp + 1) % USART_RX_BUFSZ == data->rxrp) {
+               // full
+               goto end;
+       }
+
+       data->rxbuf[data->rxwp] = data->rxdata;
+
+       data->rxwp =(data->rxwp + 1) % USART_RX_BUFSZ;
+
+end:
+       if(HAL_OK != HAL_UART_Receive_IT(huart, &data->rxdata, 1)) {
+               //Error_Handler();
+       }
+}
+
+
+void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
+       if(huart->Instance == USART1) {
+               return ReceiveUsartData(&usart1_data, huart);
+       }
+
+       if(huart->Instance == USART2) {
+               return ReceiveUsartData(&usart2_data, huart);
+       }
+}
+```
\ No newline at end of file