arduino平衡传感器控制灯带展现多种灯光效果的代码
时间: 2023-08-04 11:08:37 浏览: 59
灯带控制,利用Arduino
5星 · 资源好评率100%
以下是一个基于Arduino的平衡传感器控制灯带展现多种不同灯光效果的代码,其中使用了一个switch语句,根据传感器的读数,选择不同的灯光模式:
```
#include <FastLED.h>
#define DATA_PIN 6
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 60
CRGB leds[NUM_LEDS];
#define SAMPLE_INTERVAL 20 // 20ms sample interval
#define FILTER_FACTOR 0.1 // 10% filtering
const int xPin = A0;
const int yPin = A1;
const int zPin = A2;
float xAcc, yAcc, zAcc;
float xAccFiltered, yAccFiltered, zAccFiltered;
enum LightMode {
MODE_OFF,
MODE_COLOR_WIPE,
MODE_RAINBOW,
MODE_FADE,
MODE_STROBE
};
LightMode mode = MODE_OFF;
void setup() {
Serial.begin(115200);
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
}
void loop() {
// Read accelerometer
xAcc = analogRead(xPin);
yAcc = analogRead(yPin);
zAcc = analogRead(zPin);
// Low-pass filter
xAccFiltered = (xAcc * FILTER_FACTOR) + (xAccFiltered * (1 - FILTER_FACTOR));
yAccFiltered = (yAcc * FILTER_FACTOR) + (yAccFiltered * (1 - FILTER_FACTOR));
zAccFiltered = (zAcc * FILTER_FACTOR) + (zAccFiltered * (1 - FILTER_FACTOR));
// Convert to tilt angle
float xTilt = (xAccFiltered - 512) / 1024.0 * 90.0;
float yTilt = (yAccFiltered - 512) / 1024.0 * 90.0;
float zTilt = (zAccFiltered - 512) / 1024.0 * 90.0;
// Map tilt angle to LED index
int xIndex = map(xTilt, -90, 90, 0, NUM_LEDS - 1);
int yIndex = map(yTilt, -90, 90, 0, NUM_LEDS - 1);
int zIndex = map(zTilt, -90, 90, 0, NUM_LEDS - 1);
// Choose light mode based on tilt angle
if (zTilt < -45) {
mode = MODE_COLOR_WIPE;
} else if (zTilt < 0) {
mode = MODE_RAINBOW;
} else if (zTilt < 45) {
mode = MODE_FADE;
} else {
mode = MODE_STROBE;
}
// Update LED colors
switch (mode) {
case MODE_OFF:
fill_solid(leds, NUM_LEDS, CRGB::Black);
break;
case MODE_COLOR_WIPE:
colorWipe(CRGB::Red, 50);
break;
case MODE_RAINBOW:
rainbowCycle(20);
break;
case MODE_FADE:
fadeToBlackBy(leds, NUM_LEDS, 10);
int hue = map(xTilt, -90, 90, 0, 255);
leds[xIndex] = CHSV(hue, 255, 255);
break;
case MODE_STROBE:
fill_solid(leds, NUM_LEDS, CRGB::White);
break;
}
// Show LED colors
FastLED.show();
// Wait for next sample
delay(SAMPLE_INTERVAL);
}
void colorWipe(CRGB color, int delayTime) {
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = color;
FastLED.show();
delay(delayTime);
}
}
void rainbowCycle(int delayTime) {
uint8_t hue = 0;
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = CHSV(hue, 255, 255);
hue += 256 / NUM_LEDS;
}
FastLED.show();
delay(delayTime);
for (int j = 0; j < 8; j++) {
for (int i = 0; i < NUM_LEDS; i++) {
leds[i].fadeToBlackBy(8);
}
hue += 16;
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] |= CHSV(hue, 255, 255);
}
FastLED.show();
delay(delayTime);
}
}
```
该代码使用了一个枚举类型来表示不同的灯光模式,并使用switch语句根据传感器的读数选择不同的模式。每个模式都有一个函数来设置LED颜色,如`colorWipe()`和`rainbowCycle()`。您可以根据需要添加或修改灯光模式。
阅读全文