STM32F103C8T6 PA4PA5PA6PA7PB0高低电平输出使用DMA高速处理代码并通过ODR切换电平
以下是使用DMA高速处理代码,并通过ODR切换电平的示例代码:
#include "stm32f10x.h"
#define BUFFER_SIZE 4
GPIO_InitTypeDef GPIO_InitStructure;
DMA_InitTypeDef DMA_InitStructure;
uint16_t buffer[BUFFER_SIZE] = {GPIO_Pin_4, GPIO_Pin_5, GPIO_Pin_6, GPIO_Pin_7};
uint32_t bufferIndex = 0;
void GPIO_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
void DMA_Configuration(void)
{
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
DMA_DeInit(DMA1_Channel1);
DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&GPIOA->ODR;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&buffer[bufferIndex];
DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST;
DMA_InitStructure.DMA_BufferSize = BUFFER_SIZE;
DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
DMA_InitStructure.DMA_Priority = DMA_Priority_High;
DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;
DMA_Init(DMA1_Channel1, &DMA_InitStructure);
DMA_Cmd(DMA1_Channel1, ENABLE);
}
int main(void)
{
GPIO_Configuration();
DMA_Configuration();
while (1)
{
// 切换电平
GPIOA->ODR ^= buffer[bufferIndex];
// 延时
for (int i = 0; i < 1000000; i++);
// 切换到下一个输出
bufferIndex = (bufferIndex + 1) % BUFFER_SIZE;
DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)&buffer[bufferIndex];
DMA_Init(DMA1_Channel1, &DMA_InitStructure);
}
}
该代码使用了DMA1的通道1,将GPIOA的ODR寄存器作为目标地址,将buffer数组中的值作为源地址,实现了高速切换电平的功能。代码中使用了循环模式,即当DMA传输完buffer数组中的数据后,会重新从buffer数组的开头开始传输。
原文地址: https://www.cveoy.top/t/topic/h65z 著作权归作者所有。请勿转载和采集!