外设GPIO配置(即在哪种情况下使用的输出输入模式–浮空?):
《stm32中文参考手册 P-110 》下载地址:https://pan.lanzou.com/i11020j
一、使能时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1,ENABLE);
二、配置GPIO
//USART1 Tx(PA.09)
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART1 Rx(PA.10)
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
三、配置USART
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControlUSART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
四、发送与接收
发送单字节:
void sendByte(unsigned char byte) //串口发送一个字节
{
USART_SendData(USART1, byte); //通过库函数 发送数据
while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET); //等待发送完成,检测 USART_FLAG_TC 是否置1
}
发送字符串:
void sendString(uint8_t* cp)
{
while((*cp)!='\0')
{
sendByte(*cp);
cp++;
}
}
中断接收:
void USART2_IRQHandler ( void )
{
uint8_t res;
if ( USART_GetITStatus ( USART2, USART_IT_RXNE ) != RESET ) //接收1字节数据
{
res =USART_ReceiveData ( USART2 ); //读取接收到的数据
USART2_RX_BUF[USART2_RX_STA]=res; //记录接收到的值
USART_SendData ( USART1, res ); //发送数据----回显;
USART2_RX_STA++; //接收数据增加1
}
//接收到一帧数据
if ( USART_GetITStatus ( USART2, USART_IT_IDLE ) == SET )
{
flag= 1;
//清除中断位
res = USART_ReceiveData ( USART2 );
}
}
注意:
嵌套双引号: 应使用\” \”