esp32使用光敏传感器实现LED灯的亮暗线性调节

LED灯接ESP32的18口和GND。

光敏传感器VCC接3.3,GND接GND,DO不接,AO接35口,注意这里不需要接DO,如果接DO,无法实现线性调光,只返回两个固定值。

int freq = 5000;    // 频率
int channel = 0;    // 通道
int resolution = 8;   // 分辨率
const int led = 18;
const int gm = 35; //光敏电阻引脚
int Filter_Value;
void setup()
{
  Serial.begin(115200); 
    
  //设置光敏电阻输入
  pinMode(gm,INPUT); //光敏电阻
  randomSeed(analogRead(gm));
  
  ledcSetup(channel, freq, resolution); // 设置通道
  ledcAttachPin(led, channel);  // 将通道与对应的引脚连接
  
}
#define FILTER_N 20
int Filter() {
  int i;
  int filter_sum = 0;
  int filter_max, filter_min;
  int filter_buf[FILTER_N];
  for(i = 0; i < FILTER_N; i++) {
    filter_buf[i] = analogRead(gm);
    delay(1);
  }
  filter_max = filter_buf[0];
  filter_min = filter_buf[0];
  filter_sum = filter_buf[0];
  for(i = FILTER_N - 1; i > 0; i--) {
    if(filter_buf[i] > filter_max)
      filter_max=filter_buf[i];
    else if(filter_buf[i] < filter_min)
      filter_min=filter_buf[i];
    filter_sum = filter_sum + filter_buf[i];
    filter_buf[i] = filter_buf[i - 1];
  }
  i = FILTER_N - 2;
  filter_sum = filter_sum - filter_max - filter_min + i / 2; // +i/2 的目的是为了四舍五入
  filter_sum = filter_sum / i;
  return filter_sum;
}
void loop()
{
  Filter_Value = Filter();
  ledcWrite(0,map(Filter_Value,0,4095,0,255));
}

 

posted @ 2021-11-11 09:31  盛世芳华  阅读(1645)  评论(0编辑  收藏  举报