串口通信实验

1.在CUBEMX配置

需要用的GPIO口为PA9和PA10

串口通信实验_第1张图片

串口通信实验_第2张图片

串口通信实验_第3张图片

串口通信实验_第4张图片

串口通信实验_第5张图片

2.HAL_UART_Transmit(&huart1,"hello world\n",strlen("hello world\n"),100);函数用于发送

3.HAL_UART_Receive(&huart1,ch,19,100);

该函数用于接收,接收完成后需要memset(ch,0,strlen(ch));使用memest需要加#include

4.重定向,通过这串代码,可以实现使用printf代替HAL_UART_Transmit(&huart1,ch,strlen(ch),100);但是需要魔术棒打开Use MicroLIB

串口通信实验_第6张图片


#include "main.h"
#include "usart.h"
#include "gpio.h"

#include 
#include

void SystemClock_Config(void);

int fputc(int ch,FILE *f)
{
	unsigned char temp[1] = {ch};
	HAL_UART_Transmit(&huart1,temp,1,0xfff);
	return ch;
}

int main(void)
{
  
  SystemClock_Config();

  
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  
HAL_UART_Transmit(&huart1,"hello world\n",strlen("hello \n"),100);

  while (1)
  {
    
		HAL_UART_Receive(&huart1,ch,19,100);
		//HAL_UART_Transmit(&huart1,ch,strlen(ch),100);
		printf(ch);
		memset(ch,0,strlen(ch));
  }
  
}


void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

 
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

 
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}



void Error_Handler(void)
{
  
  __disable_irq();
  while (1)
  {
  }
  
}

#ifdef  USE_FULL_ASSERT

void assert_failed(uint8_t *file, uint32_t line)
{
  
}
#endif 

全部代码

int fputc(int ch,FILE *f)
{
	unsigned char temp[1] = {ch};
	HAL_UART_Transmit(&huart1,temp,1,0xfff);
	return ch;
}

你可能感兴趣的:(linux,运维,服务器)