I use the ESP32, want to write a code about automatically controlling the brightness of the Neopixel light bar
I try to sense LUX through BH1750 in the loop to write a value in the range of 300-400 so that the light bar can automatically adjust the light in this range, but I have been trying for a long time without success, please masters can help me look.
This is my code:
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif
#define LED_PIN 15
#define LED_COUNT 40
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
#include "BluetoothSerial.h"
#include "analogWrite.h"
BluetoothSerial ESP_BT;
int incoming,y,x,xin,i;
// setting PWM properties
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 12;
#include "BH1750.h"
#include "Wire.h"
BH1750 bh1750_a;
BH1750 bh1750_b;
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
x=50;
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(50);
colorWipe(strip.Color(255, 255, 255), 50);
// Set BRIGHTNESS to about 1/5 (max = 255)
// configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);
ESP_BT.begin("ESP32_Control");
// attach the channel to the GPIO to be controlled
Serial.begin(115200);
Wire.begin(5, 18);
Wire1.begin(21, 22);
bh1750_a.begin(BH1750::CONTINUOUS_HIGH_RES_MODE, 0x23, &Wire);
bh1750_b.begin(BH1750::CONTINUOUS_HIGH_RES_MODE, 0x23, &Wire1);
}
int error_counter_1_a = 0;
int error_counter_2_a = 0;
int error_counter_1_b = 0;
int error_counter_2_b = 0;
void loop() {
float light_level_a;
if (bh1750_a.measurementReady()) {
light_level_a = bh1750_a.readLightLevel();
}
float light_level_b;
if (bh1750_b.measurementReady()) {
light_level_b = bh1750_b.readLightLevel();
}
if (lround(light_level_a) == -1) {
error_counter_1_a++;
}
if (lround(light_level_a) == -2) {
error_counter_2_a++;
}
if (lround(light_level_b) == -1) {
error_counter_1_b++;
}
if (lround(light_level_b) == -2) {
error_counter_2_b++;
}
delay(1000);
if(light_level_a>400)
{
x-=5;
strip.setBrightness(x);
}
else if(light_level_a<400)
{
x+=5;
strip.setBrightness(x);
}
Serial.printf("A: %.0f lux %d:%d :: B: %.0f lux %d:%d\n", light_level_a,
error_counter_1_a, error_counter_2_a, light_level_b,
error_counter_1_b, error_counter_2_b);
}
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
// Pause for a moment
}
}
// decrease the LED brightness