声控传感器在stm32上代码
时间: 2023-08-14 17:04:11 浏览: 119
下面是一个基于STM32的声控传感器代码示例,仅供参考:
```c
#include "stm32f10x.h"
#include "usart.h"
#include "delay.h"
#include "stdio.h"
#define MIC_PORT GPIOA
#define MIC_PIN GPIO_Pin_0
uint16_t adc_value = 0;
void ADC_Config(void)
{
ADC_InitTypeDef ADC_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = MIC_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(MIC_PORT, &GPIO_InitStructure);
ADC_DeInit(ADC1);
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
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_Cmd(ADC1, ENABLE);
ADC_ResetCalibration(ADC1);
while(ADC_GetResetCalibrationStatus(ADC1));
ADC_StartCalibration(ADC1);
while(ADC_GetCalibrationStatus(ADC1));
}
u16 Get_Adc(u8 ch)
{
ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_55Cycles5);
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
return ADC_GetConversionValue(ADC1);
}
int main(void)
{
u16 adc_temp = 0;
u16 adc_max = 0;
u16 adc_min = 4095;
u16 adc_threshold = 0;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
delay_init(72);
USART_Config();
ADC_Config();
printf("STM32 Mic Test...\r\n");
while(1)
{
adc_temp = Get_Adc(ADC_Channel_0);
if(adc_temp > adc_max) adc_max = adc_temp;
if(adc_temp < adc_min) adc_min = adc_temp;
adc_threshold = (adc_max + adc_min) / 2;
adc_value = adc_temp;
if(adc_value > adc_threshold + 50)
{
printf("Sound detected! ADC Value: %d\r\n", adc_value);
}
delay_ms(10);
}
}
```
这段代码使用了STM32的ADC模块来采集麦克风的声音信号,并进行处理。当声音信号超过一定阈值时,会通过串口输出提示信息。需要注意的是,声音信号的阈值需要在实际应用中进行调整。
阅读全文