esp32使用光敏感測器實現LED燈的亮暗線性調節
阿新 • • 發佈:2021-11-11
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)); }