STM32 Cubemx

串口

串口重定义

#include "stdio.h"

#ifdef __GNUC__
/* With GCC, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART2 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);//修改串口句柄
  return ch;
}

串口接收中断

uint8_t rs232_Buf = 0;
uint8_t rs232_Buf_count = 0;
char rs232_Buf_try[rs232_Buf_Max];


HAL_UART_Receive_IT(&huart4, &rs232_Buf, 1);//初始化的时候要打开,要不然进不了中断

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart4)
    {      
            if (rs232_Buf_count < rs232_Buf_Max)
            {
                rs232_Buf_try[rs232_Buf_count++] = rs232_Buf;
            }
            else
            {
                rs232_Buf_count = 0;
            }
            HAL_UART_Receive_IT(&huart4, &rs232_Buf, 1);   //这个地方,是防止下去也能进入接收中断   
    }
}

串口调试打印

#define DEBUG

#ifdef DEBUG
#define Debug_Print(format, ...)                                                      \
{                                                                                   \
	printf("\r\nFile : %s, Line : %04d, %s," format, __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \
	fflush(stdout);                                                                   \
}
#define Printf(format, ...)               \
{                                       \
	printf(format "\r\n", ##__VA_ARGS__); \
	fflush(stdout);                       \
}
#define Print(format, ...)         \
  {                                \
    printf(format, ##__VA_ARGS__); \
    fflush(stdout);                \
  }
#else
#define Debug_Print(format, ...)
#define Printf(format, ...)
#define Print(format, ...)
#endif

串口发送

unsigned char str[100];	
memset(str, 0, 100);
sprintf((char *)str, "AT+CIPSTART=\"TCP\",\"%s\",%d\r\n", ServerIP, ServerPort);
HAL_UART_Transmit_IT(&huart4, (uint8_t *)str, strlen(str));

定时器

开启定时器

__HAL_TIM_CLEAR_FLAG(&htim3, TIM_SR_UIF); //很重要,清掉标志位
HAL_TIM_Base_Start_IT(&htim3);//开启定时器前一定要加入以上代码
__HAL_TIM_SET_COUNTER(&htim3, 0);//定时器手动清零
HAL_TIM_Base_Stop_IT(&htim2);//关闭定时器

定时器中断

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if (htim == &htim3)
  {
  }
  if (htim == &htim2)
  {
    if (time_count++ >= maximum_time)
    {
      time_count = 0;
  }
}

你可能感兴趣的:(STM32 Cubemx)