實驗3:UART通信
通信雙方幀格式一致胸梆,通信雙方的波特率一致
板子通過uart和pc 通信匿沛, pc 發(fā)‘a',led2 亮 榛鼎, pc 發(fā)‘b'逃呼,led2 滅
查看原理圖, 從P4 找
用CH340將USB信號轉換為UART信號
同時也可以將UART信號轉換為USB信號
USB_RXD與RXD鏈接
PC過來的信號最終鏈接到了stm32 U1_USART1_RX,U1_USART1_TX
STM32F051K8處理器通過pa9,pa10通信
3.2 UART串口函數(shù)
HAL_StatusTypeDef HAL_UART_Transmit (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size, uint32_t Timeout)
通過阻塞方式發(fā)送SIZE個字節(jié)者娱,發(fā)送的數(shù)據在pData里面抡笼,發(fā)送超時TimeOut
HAL_StatusTypeDef HAL_UART_Transmit_IT (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size)
通過huart,以中斷方式發(fā)送size個字節(jié),發(fā)送的數(shù)據在pData里面
HAL_StatusTypeDef HAL_UART_Receive (UART_HandleTypeDef * huart, uint8_t * pData,
uint16_t Size, uint32_t Timeout)
通過阻塞的方式接收size個字節(jié)黄鳍;
HAL_StatusTypeDef HAL_UART_Receive_IT (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size)
通過huart,以中斷的方式接收size個字節(jié)推姻。接收的數(shù)據在*pData里面
3.3. 代碼實現(xiàn)
#include "stdio.h"
#include "string.h"
int main(void)
{
/* USER CODE BEGIN 1 */
unsigned char rebuf[10]={0};
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
printf("after initalize all ......\r\n");//
printf("pi=%f\r\n",3.1415926);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_UART_Receive(&huart1,rebuf,3,0xffffffff);
printf("rebuf = %s\r\n",rebuf);
if(strncmp((char*)rebuf,"123",3)==0)
{
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2, GPIO_PIN_RESET);
}
else if(strncmp((char*)rebuf,"abc",3)==0)
{
HAL_GPIO_WritePin(GPIOB,GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2, GPIO_PIN_SET);
}