编写stm32f103c8t6利用AD采集电压信号并通过串口输出的程序
时间: 2023-03-03 08:57:31 浏览: 217
以下是一份基于STM32F103C8T6的AD采集电压信号并通过串口输出的示例代码,您可以参考使用:
```
#include "stm32f10x.h"
#include "stdio.h"
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
ADC_InitTypeDef ADC_InitStructure;
void USART1_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
// USART1_TX -> PA9, USART1_RX -> PA10
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);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
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);
USART_Cmd(USART1, ENABLE);
}
void ADC1_Init(void)
{
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
RCC_ADCCLKConfig(RCC_PCLK2_Div6);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
ADC_Init(ADC1, &ADC_InitStructure);
ADC_Cmd(ADC1, ENABLE);
}
int main(void)
{
float voltage;
char s[10];
USART1_Init();
ADC1_Init();
while (1)
{
ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_239Cycles5);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while (ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
voltage = ADC_GetConversionValue(ADC1) * 3.3 / 4096;
sprintf(s, "%5.2fV\r\n", voltage);
USART_SendString(USART1, s);
Delay(1000);
}
}
void USART_SendString(USART_TypeDef* USARTx, char *s)
{
while (*s)
{
while (USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
USART_SendData(USARTx, *s++);
}
}
void Delay(__IO uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
```
该代码中通过USART1串口发送ADC采集到的电压值,采集的通道为PA1,采样时间为239.5个ADC时钟周期,电压值的精度为12位。如果需要采集其他通道的电压值,则需要更改ADC_RegularChannelConfig函数中的第二个参数。
该代码
阅读全文