stm32f107作为下位机,如何编写RS485通讯程序,写一段示例
时间: 2023-12-03 22:43:45 浏览: 78
基于STM32的rs485通讯例程
5星 · 资源好评率100%
下面是一个基本的STM32F107 RS485通讯程序示例:
```c
#include "stm32f10x.h"
#include "stm32f10x_usart.h"
#include "stm32f10x_gpio.h"
#define USART1_DR_Base 0x40013804
#define MAX_BUFFER_SIZE 200
void GPIO_Configuration(void);
void USART1_Configuration(void);
void USART1_SendChar(uint16_t Data);
void USART1_SendString(uint8_t *str);
void USART1_IRQHandler(void);
uint8_t RxBuffer[MAX_BUFFER_SIZE];
volatile uint8_t RxCounter = 0;
volatile uint8_t RxFlag = 0;
int main(void)
{
GPIO_Configuration();
USART1_Configuration();
while (1)
{
if (RxFlag)
{
USART1_SendString(RxBuffer);
RxFlag = 0;
RxCounter = 0;
}
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
//RS485 Driver Enable Pin
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
}
void USART1_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, 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);
//USART1 Configuration
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_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
//USART1 Interrupt Configuration
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(uint16_t Data)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
USART_SendData(USART1, Data);
}
void USART1_SendString(uint8_t *str)
{
while (*str)
{
USART1_SendChar(*str++);
}
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
RxBuffer[RxCounter++] = USART_ReceiveData(USART1);
if (RxCounter >= MAX_BUFFER_SIZE)
{
RxCounter = 0;
}
RxFlag = 1;
}
}
```
这个程序设置了RS485驱动器的使能引脚和USART1串口的配置,并且实现了一个简单的接收中断程序。在主循环中,如果接收标志被触发,则发送接收缓冲区中的数据。
阅读全文