stm32f103温度控制led灯主函数代码
时间: 2023-08-06 15:03:01 浏览: 49
以下是一个简单的温度控制 LED 灯的主函数代码,使用 STM32F103 微控制器:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOC
int main(void)
{
// 初始化时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
// 初始化 LED 引脚
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
// 初始化温度传感器
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
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));
// 循环读取温度并控制 LED
while (1)
{
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
while (!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
uint16_t temperature = ADC_GetConversionValue(ADC1);
if (temperature > 2000)
GPIO_SetBits(LED_PORT, LED_PIN);
else
GPIO_ResetBits(LED_PORT, LED_PIN);
}
}
```
这个代码使用了 ADC1 通道 0 来读取外部温度传感器的模拟值,并将其转换为数字温度。如果温度高于 20°C,LED 将点亮,否则将关闭。请注意,该代码仅供参考,可能需要进行一些修改才能适应您的具体应用场景。