STM32F103C8T6 RS485转串口,USB TO RS485

本文详细介绍了如何在STM32F10x平台上配置RS485接口,包括GPIO设置、USART参数配置、中断启用等步骤,以便于在嵌入式系统中实现串口通信。
摘要由CSDN通过智能技术生成

RS485.c

#include "stm32f10x.h"

#include "RS485.h"



// 配置串口为RS485模式
void RS485_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    // 使能GPIO和USART时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

    // 配置USART1_TX引脚为推挽输出
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // 配置USART1_RX引脚为浮空输入
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // 配置RS485芯片的使能引脚
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

        GPIO_SetBits(GPIOB, GPIO_Pin_5);                              //485芯片高电平

    // 配置USART1为RS485模式
    USART_InitStructure.USART_BaudRate = 9600;
    USART_InitStructure.USART_WordLength = USART_WordLength_9b;//数据位
    USART_InitStructure.USART_StopBits = USART_StopBits_1; //1位停止位
    USART_InitStructure.USART_Parity = USART_Parity_Even;//偶校验
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件流控
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//接收和发送

    USART_Init(USART1, &USART_InitStructure);

    USART_ClearFlag(USART1,USART_FLAG_RXNE);
    USART_Cmd(USART1, ENABLE);                                                        //使能串口
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);                                    //使能接收中断
    USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);

//    NVIC_InitTypeDef NVIC_InitStruct;                                                                                                                                             
//    NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
//    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
//    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 3;
//    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 3;
//    NVIC_Init(&NVIC_InitStruct);

    // 使能USART1
    USART_Cmd(USART1, ENABLE);
}

RS485.h

#ifndef __RS485_H
#define __RS485_H
#include "stm32f10x.h"


void RS485_Configuration(void);

#endif

配置完成就可以像串口一样正常使用,A接A,B接B。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值