STM32F10X_485通讯

目录

1、参考

2、接收和发送引脚

2.1、硬件相关

2.2、软件相关

3、控制485芯片接收或发送的引脚

3.1、硬件相关

3.2、软件相关

4、串口配置

4.1、配置USART2

5、主程序中

6、实验现象


1、参考

用开发板做485实验;

2、接收和发送引脚

2.1、硬件相关

PA2作为485的发送引脚;

PA3作为485的接收引脚;

2.2、软件相关

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    //打开GPIOA的时钟

    /* Configure USART2 Tx (PA.02) as alternate function push-pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
	//配置PA2为发送
    
    /* Configure USART2 Rx (PA.03) as input floating */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    //配置PA3为接收

3、控制485芯片接收或发送的引脚

3.1、硬件相关

PC2置高,485芯片处于发送,485_D发送信息;

PC2置低,485芯片处于接收,485_R接收信息;

3.2、软件相关

  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
  //打开GPIOC的时钟

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP ;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOC, &GPIO_InitStructure);
  //控制485芯片处于接收或发送的IO引脚(PC2)

4、串口配置

4.1、配置USART2

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
    //打开USART2时钟

    /* USART2 mode config */
	USART_InitStructure.USART_BaudRate = 115200;//波特率
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;//8位
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//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;//收发都行

	USART_Init(USART2, &USART_InitStructure); 
    USART_Cmd(USART2, ENABLE);//使能USART2

5、主程序中

  while(1)
  {
    GPIO_SetBits(GPIOC,GPIO_Pin_2); 
    //GPIOC.2置高,485芯片处于发送
    USART_SendData(USART2, temp);	
    //发送一个字节
    while (USART_GetFlagStatus(USART2,USART_FLAG_TC) !=SET);
    //等待发送完毕
    delay(1000);
    //让485芯片等一会再变为接收
    GPIO_ResetBits(GPIOC,GPIO_Pin_2);	
    //GPIOC.2置低,485芯片处于接收
    while(	USART_GetFlagStatus(USART2,USART_FLAG_RXNE)!= SET); 
    //等待接收完毕
	delay(1000);
    temp = USART_ReceiveData(USART2);
		
  }

6、实验现象

上电后,串口会接收到0x00字节,如下图;

在串口中,发送0x01后,串口助手会接收到返回值0x01,如下图;

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值