STM32 RS485 通信光照传感器代码示例
#include "stm32f10x.h" #include "stm32f10x_gpio.h" #include "stm32f10x_rcc.h" #include "stm32f10x_usart.h" #include "stm32f10x_dma.h"
#define RS485_DE_PIN GPIO_Pin_8 #define RS485_DE_PORT GPIOA
#define USART1_TX_PIN GPIO_Pin_9 #define USART1_RX_PIN GPIO_Pin_10 #define USART1_PORT GPIOA
#define RS485_DMA_CH DMA1_Channel4
void GPIO_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
// RS485 DE Pin
GPIO_InitStructure.GPIO_Pin = RS485_DE_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(RS485_DE_PORT, &GPIO_InitStructure);
// USART1 Pins
GPIO_InitStructure.GPIO_Pin = USART1_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(USART1_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USART1_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART1_PORT, &GPIO_InitStructure);
}
void USART_Configuration(void) { USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
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_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void DMA_Configuration(void) { DMA_InitTypeDef DMA_InitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_DeInit(RS485_DMA_CH);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART1->DR;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)0;
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = 0;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Disable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(RS485_DMA_CH, &DMA_InitStructure);
USART_DMACmd(USART1, USART_DMAReq_Tx, ENABLE);
}
void RS485_SendData(uint8_t *data, uint16_t size) { GPIO_SetBits(RS485_DE_PORT, RS485_DE_PIN); // Set DE pin to high DMA_InitStructure.DMA_BufferSize = size; DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)data; DMA_Init(RS485_DMA_CH, &DMA_InitStructure); DMA_Cmd(RS485_DMA_CH, ENABLE); }
int main(void) { GPIO_Configuration(); USART_Configuration(); DMA_Configuration();
uint8_t sendData[] = "Hello, World!";
RS485_SendData(sendData, sizeof(sendData));
while (1)
{
// 你的代码
}
}
原文地址: https://www.cveoy.top/t/topic/pQMg 著作权归作者所有。请勿转载和采集!