1. 实验目的
使用485接口接收数据,然后返回接收的数据。
2. 实验步骤
- USART_Configuration();
- while(1){ //当接收到数据,发送数据}
2.1.USART_Configuration();
- 开起时钟:IO口时钟、串口开时钟、[开启复用时钟、复用设置]
- 中断初始化:
- IO输入输出设置:485共有3个引脚,收发控制引脚(默认为收),收引脚,发引脚。
- 串口通信格式配置并初始化:主要是串口波特率等配置。
- 开启中断、串口。
//串口初始化
void USART_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
//串口和IO口使能
#ifdef USE_USART3
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
#endif
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_FullRemap_USART3, ENABLE);
//中断分组配置 组2
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
#ifdef USE_USART3
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_Init(&NVIC_InitStructure);
#endif
/*---------------------485控制引脚配置---------------------*/
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //注意这里的频率需要与对应串口的频率相一致
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
//485A -- R/D1 -- 485A 的方向控制管脚
GPIO_InitStructure.GPIO_Pin = _485A_PIN;
GPIO_Init(_485A_PORT, &GPIO_InitStructure);
/*---------------------485输入输出配置---------------------*/
//串口3 输出 TX配置
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
#ifdef USE_485A
GPIO_InitStructure.GPIO_Pin=USART3_TX_PIN;
GPIO_Init(GPIOD,&GPIO_InitStructure);
#endif
/*---------------------串口输入配置---------------------*/
//串口3
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
#ifdef USE_485A
GPIO_InitStructure.GPIO_Pin=USART3_RX_PIN;
GPIO_Init(GPIOD,&GPIO_InitStructure);
#endif
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3,DISABLE);
/*---------------------串口通信格式配置---------------------*/
USART_InitStructure.USART_BaudRate=USART_WordLength_8b;
USART_InitStructure.USART_StopBits=USART_StopBits_1;
USART_InitStructure.USART_Parity=USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
#ifdef USE_USART3
USART_InitStructure.USART_BaudRate = USART3_BAUDRATE;
USART_Init(USART3,&USART_InitStructure);
USART_ITConfig(USART3,USART_IT_RXNE,ENABLE);
USART_Cmd(USART3, ENABLE);
//初始化时,拉低485A、485B的相关引脚
GPIO_ResetBits(_485A_PORT, _485A_PIN);
#endif
}
2.2 while()
USART_Configuration();
while(1)
{
LED_BLink(1000);
if(buf_uart3.index>0)
{
send_string_uart3(buf_uart3.buf);
clear_buf_uart3();
}
}
3. 注意事项
1. 485线别错了,如果错了可能会乱码。
2. 库函数名字别写错,
。。。。。。。