编写stm32f103c8t6利用AD采集电压信号并通过串口输出的程序
时间: 2023-08-01 19:12:38 浏览: 76
好的,下面是代码:
```
#include "stm32f10x.h"
#include "stdio.h"
#define ADC1_DR_Address ((uint32_t)0x4001244C)
void RCC_Configuration(void);
void GPIO_Configuration(void);
void USART_Configuration(void);
void ADC_Configuration(void);
void NVIC_Configuration(void);
void USART1_SendChar(uint8_t ch);
void USART1_SendString(char* str);
int main(void)
{
RCC_Configuration();
GPIO_Configuration();
USART_Configuration();
NVIC_Configuration();
ADC_Configuration();
while(1)
{
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
uint16_t ADC_Result = ADC_GetConversionValue(ADC1);
float Voltage = ADC_Result * 3.3 / 4096;
char str[50];
sprintf(str, "Voltage: %.2fV\r\n", Voltage);
USART1_SendString(str);
Delay(1000);
}
}
void RCC_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_ADC1 | RCC_APB2Periph_USART1, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART_Configuration(void)
{
USART_InitTypeDef USART_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_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void ADC_Configuration(void)
{
ADC_InitTypeDef ADC_InitStructure;
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;
ADC_Init(ADC1, &ADC_InitStructure);
ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_28Cycles5);
ADC_Cmd(ADC1, ENABLE);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = ADC1_2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART1_SendChar(uint8_t ch)
{
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, ch);
}
void USART1_SendString(char* str)
{
while(*str)
{
USART1_SendChar(*str++);
}
}
```
这是一个简单的程序,它利用ADC采集电压信号,并通过串口输出。程序需要在stm32f103c8t6单片机上运行。主要特点如下:
1. 通过ADC采集电压信号,计算出电压值。
2. 通过串口输出电压值。
3. 由于程序中使用了printf函数,因此需要在编译器中开启printf支持。
希望能对你有所帮助!
阅读全文