串口通信(打印输出)
①GPIO_InitTypeDef GPIO_InitStructure; //结构体定义
USART_InitTypeDef USART_InitStructure;
②RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOx, ENABLE); //开时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USARTx, ENABLE);
③GPIO_PinAFConfig(GPIOx, GPIO_PinSourcex, GPIO_AF_USART1); //开启管脚复用
/* Connect PXx to USARTx_Tx*/
GPIO_PinAFConfig(GPIOx, GPIO_PinSourcex, GPIO_AF_USART1);
/* Connect PXx to USARTx_Rx*/
④GPIO_InitStructure
推挽,不拉,复用,2MHz
GPIO_Init(GPIOx, &GPIO_InitStructure);
⑤USART_InitStructure
typedef struct
{
uint32_t USART_BaudRate; /*!< This member configures the USART communication baud rate.
波特率:9600 典型
uint16_t USART_WordLength; /*!< Specifies the number of data bits transmitted or received in a frame.
This parameter can be a value of @ref USART_Word_Length */ 8个位宽
USART_WordLength_8b
uint16_t USART_StopBits; /*!< Specifies the number of stop bits transmitted.
This parameter can be a value of @ref USART_Stop_Bits */ 停止位
#define USART_StopBits_1 ((uint16_t)0x0000) √
#define USART_StopBits_0_5 ((uint16_t)0x1000)
#define USART_StopBits_2 ((uint16_t)0x2000)
#define USART_StopBits_1_5 ((uint16_t)0x3000)
uint16_t USART_Parity; /*!< Specifies the parity mode.
This parameter can be a value of @ref USART_Parity
@note When parity is enabled, the computed parity is inserted
at the MSB position of the transmitted data (9th bit when
the word length is set to 9 data bits; 8th bit when the
word length is set to 8 data bits). */ 奇偶校验
#define USART_Parity_No ((uint16_t)0x0000) √
#define USART_Parity_Even ((uint16_t)0x0400)
#define USART_Parity_Odd ((uint16_t)0x0600)
uint16_t USART_Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled.
This parameter can be a value of @ref USART_Mode */ 模式
#define USART_Mode_Rx ((uint16_t)0x0004) √ 使用 | 符号
#define USART_Mode_Tx ((uint16_t)0x0008) √
uint16_t USART_HardwareFlowControl; /*!< Specifies wether the hardware flow control mode is enabled or disabled.
This parameter can be a value of @ref USART_Hardware_Flow_Control */
#define USART_HardwareFlowControl_None ((uint16_t)0x0000) √
#define USART_HardwareFlowControl_RTS ((uint16_t)0x0100)
#define USART_HardwareFlowControl_CTS ((uint16_t)0x0200)
#define USART_HardwareFlowControl_RTS_CTS ((uint16_t)0x0300)
} USART_InitTypeDef;
⑥USART_Init(USARTx, &USART_InitStructure);
USART_Cmd(USARTx, ENABLE);
附加:改变过采样位数:默认16位
USART_OneBitMethodCmd(USARTx,ENABLE); //1位
USART_OverSampling8Cmd(USARTx, ENABLE); //8位
⑦构建上位机打印输出
void USART_Printf(USART_TypeDef* USARTx,const char *p) //输入字符和端口
{
if(USARTx==USART1)
{
uint8_t l,i;
l=strlen(p);
for(i=0;i<l;i++)
{
USART_SendData(USART1,*(p+i)); //单字符发送函数
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET){} //等待发送
}
}
}
附:转义序列
\\ 反斜杠 \a 警告 \b 退格 \f 换页 \n 换行 \r 回车 \t 跳格 \v 垂直跳格