STM32串口的发送与接收 考虑到modbus的使用场合大多为半双工而非全双工,所以,串口接收采用DMA+空闲中断,发送则直接发送。
#include "serial.h" #include "string.h" _serialbuf_st serialRXbuf_st; _serialbuf_st serialTXbuf_st; /*DMA接收数据缓存*/ u8 g_uart1DmaRXBuf[UART_DMARX_SIZE]; /* 说明:3个串口直接发送函数 编写:林 */ void myUSART_Sendbyte(USART_TypeDef* USARTx, uint16_t Data) { while((USARTx->SR&0X40)==0); USARTx->DR = (Data & (uint16_t)0x01FF); } void myUSART_Sendstr(USART_TypeDef* USARTx, const char *s) { while(*s != '\0') { myUSART_Sendbyte( USARTx, *s) ; s++; } } void myUSART_Sendarr(USART_TypeDef* USARTx, u8 a[] ,uint8_t len) { uint8_t i=0; while(i < len ) { myUSART_Sendbyte( USARTx, a) ; i++; } } /* 说明: 串口1初始化 串口1使用DMA 接收 编写:林 */ void Usart1_init(u32 baud) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; DMA_InitTypeDef DMA_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1, ENABLE); RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 ; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate =baud;//一秒发送BaudRate个bit 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); DMA_DeInit(DMA1_Channel5); DMA_InitStructure.DMA_PeripheralBaseAddr = (u32)(&(USART1->DR)); DMA_InitStructure.DMA_MemoryBaseAddr = (u32)g_uart1DmaRXBuf; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC; DMA_InitStructure.DMA_BufferSize = UART_DMARX_SIZE; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; 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(DMA1_Channel5,&DMA_InitStructure); USART_ITConfig(USART1,USART_IT_TC,DISABLE); USART_ITConfig(USART1,USART_IT_RXNE,DISABLE); USART_ITConfig(USART1,USART_IT_IDLE,ENABLE); NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; // NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; // NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; // NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // NVIC_Init(&NVIC_InitStructure); USART_DMACmd(USART1,USART_DMAReq_Rx,ENABLE); USART_Cmd(USART1, ENABLE); DMA_Cmd(DMA1_Channel5,ENABLE); memset( & serialRXbuf_st ,0, sizeof ( serialRXbuf_st ) ) ; }
|