实验3:UART通信
通信双方帧格式一致,通信双方的波特率一致
板子通过uart和pc 通信, pc 发‘a',led2 亮 , pc 发‘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串口函数
HAL_StatusTypeDef HAL_UART_Transmit (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size, uint32_t Timeout)
通过阻塞方式发送SIZE个字节,发送的数据在pData里面,发送超时TimeOut
HAL_StatusTypeDef HAL_UART_Transmit_IT (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size)
通过huart,以中断方式发送size个字节,发送的数据在pData里面
HAL_StatusTypeDef HAL_UART_Receive (UART_HandleTypeDef * huart, uint8_t * pData,
uint16_t Size, uint32_t Timeout)
通过阻塞的方式接收size个字节;
HAL_StatusTypeDef HAL_UART_Receive_IT (UART_HandleTypeDef * huart, uint8_t *
pData, uint16_t Size)
通过huart,以中断的方式接收size个字节。接收的数据在*pData里面
3.3. 代码实现
#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);
}