单片机开发常见问题集合

文章目录

发送串口数据偶尔丢失字节

场景: 在STM32单片机中进行串口数据发送,在Linux/Windows上进行串口数据接收,会偶发出现接收到的数据有某些字节丢失。
分析: 在STM32中可以使用printf用于发送串口数据,该函数内部实际上调用了接口:

c 复制代码
/*********************************************************************
 * @fn      fputc
 * @brief   Support Printf Function 
 * @param   data - UART send Data.   
 * @return  data - UART send Data.
 */
int fputc(int data, FILE *f)
{
#if (DEBUG == DEBUG_UART1)
  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
  USART_SendData(USART1, (u8) data);
#elif (DEBUG == DEBUG_UART2)
  while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET);
  USART_SendData(USART2, (u8) data);	
#elif (DEBUG == DEBUG_UART3)
  while (USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);	
  USART_SendData(USART3, (u8) data);	
#endif
  return data;
}

解决:

  • 方案1:修改fputc内部实现
c 复制代码
int fputc(int data, FILE *f)
{
#if (DEBUG == DEBUG_UART1)
  USART_SendData(USART1, (u8) data);
  while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
#elif (DEBUG == DEBUG_UART2)
  USART_SendData(USART2, (u8) data);
  while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
#elif (DEBUG == DEBUG_UART3)
  USART_SendData(USART3, (u8) data);
  while (USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);	
#endif
  return data;
}
  • 方案2:业务中不使用printf函数,使用自行实现接口
c 复制代码
/**
 * @brief 发送字节流到串口
 * @param bytes 字节流数据
 * @param length 字节流长度
 */
static void UART1_SendBytes(const uint8_t* bytes, uint32_t length)
{
    uint32_t i;
    for (i = 0; i < length; ++i)
    {
        USART_SendData(USART1, bytes[i]); /* CPU 将一个字节转入到 发送数据寄存器 */
        while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); /* 等待 发送数据寄存器 将该字节全部转入到 发送移位寄存器 */
    }
    while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET); /* 等待 发送移位寄存器 将数据帧的最后一个字节的最后一位发送出去,整个数据帧发送完毕 */
}
相关推荐
SundayBear5 小时前
零基础入门MQTT协议
c语言·单片机
嗯嗯=6 小时前
STM32单片机学习篇9
stm32·单片机·学习
松涛和鸣11 小时前
DAY63 IMX6ULL ADC Driver Development
linux·运维·arm开发·单片机·嵌入式硬件·ubuntu
想放学的刺客14 小时前
单片机嵌入式试题(第23期)嵌入式系统电源管理策略设计、嵌入式系统通信协议栈实现要点两个全新主题。
c语言·stm32·单片机·嵌入式硬件·物联网
jghhh0116 小时前
基于上海钜泉科技HT7017单相计量芯片的参考例程实现
科技·单片机·嵌入式硬件
恶魔泡泡糖16 小时前
51单片机外部中断
c语言·单片机·嵌入式硬件·51单片机
意法半导体STM3216 小时前
【官方原创】如何基于DevelopPackage开启安全启动(MP15x) LAT6036
javascript·stm32·单片机·嵌入式硬件·mcu·安全·stm32开发
v_for_van16 小时前
STM32低频函数信号发生器(四通道纯软件生成)
驱动开发·vscode·stm32·单片机·嵌入式硬件·mcu·硬件工程
电化学仪器白超17 小时前
③YT讨论
开发语言·python·单片机·嵌入式硬件
乡野码圣17 小时前
【RK3588 Android12】硬件中断IRQ
单片机·嵌入式硬件