Firmware, iOS-App und Gehäuse für den 5x5x5-LED-Würfel
ESP32-S3-Firmware mit 18 Effekten, Mikrofon (Klatschen, Beat, Spektrum) und REST-API, Testprogramme, SwiftUI-Fernbedienung und OpenSCAD-Sockel. Die WLAN-Zugangsdaten (secrets.h) sind nicht enthalten. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
55b94475a5
22 files changed
+52104
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# ESP32-S3-DevKitC-1 (N16R8: 16 MB Flash, 8 MB OPI-PSRAM), am USB-Anschluss direkt am Chip.
|
||||
# Früheres Board: FQBN=esp32:esp32:nologo_esp32c3_super_mini
|
||||
FQBN ?= esp32:esp32:esp32s3:FlashSize=16M,PSRAM=opi,PartitionScheme=app3M_fat9M_16MB,CDCOnBoot=cdc,USBMode=hwcdc
|
||||
# Der ESP meldet sich per nativem USB als usbmodem
|
||||
PORT ?= $(firstword $(wildcard /dev/cu.usbmodem*))
|
||||
|
||||
.PHONY: build upload monitor flash test hwtest
|
||||
|
||||
build:
|
||||
arduino-cli compile --fqbn $(FQBN) .
|
||||
|
||||
upload: build
|
||||
@test -n "$(PORT)" || (echo "Kein /dev/cu.usbmodem* gefunden – ESP angesteckt? Sonst PORT=... setzen"; exit 1)
|
||||
arduino-cli upload --fqbn $(FQBN) -p $(PORT) .
|
||||
|
||||
monitor:
|
||||
arduino-cli monitor -p $(PORT) -c baudrate=115200
|
||||
|
||||
flash: upload monitor
|
||||
|
||||
# Löttest-Firmware (statischer Regenbogen) statt der Demo aufspielen
|
||||
test:
|
||||
@test -n "$(PORT)" || (echo "Kein /dev/cu.usbmodem* gefunden – ESP angesteckt? Sonst PORT=... setzen"; exit 1)
|
||||
arduino-cli compile --fqbn $(FQBN) rainbow_test
|
||||
arduino-cli upload --fqbn $(FQBN) -p $(PORT) rainbow_test
|
||||
|
||||
# Hardwaretest: Mikrofon-Pegel und Taster über die serielle Konsole (make monitor)
|
||||
hwtest:
|
||||
@test -n "$(PORT)" || (echo "Kein /dev/cu.usbmodem* gefunden – ESP angesteckt? Sonst PORT=... setzen"; exit 1)
|
||||
arduino-cli compile --fqbn $(FQBN) hw_test
|
||||
arduino-cli upload --fqbn $(FQBN) -p $(PORT) hw_test
|
||||
@@ -0,0 +1,173 @@
|
||||
// Mikrofon: der ADC tastet per DMA dauerhaft im Hintergrund ab, audioUpdate()
|
||||
// holt einmal pro Frame die neuen Werte ab.
|
||||
|
||||
#include "cube.h"
|
||||
#include <arduinoFFT.h>
|
||||
#include "esp_adc/adc_continuous.h"
|
||||
|
||||
const uint32_t SAMPLE_RATE = 10000; // Hz -> Frequenzen bis 5 kHz
|
||||
const uint16_t FFT_SIZE = 256; // 25,6 ms Fenster, 39 Hz pro FFT-Stufe
|
||||
|
||||
// Frequenzbänder in FFT-Stufen (x 39 Hz): Bass, untere Mitten, Mitten, obere Mitten, Höhen
|
||||
const uint8_t BAND_EDGES[CUBE_SIZE + 1] = {1, 4, 12, 38, 77, 128};
|
||||
|
||||
adc_continuous_handle_t adc;
|
||||
adc_channel_t micChannel;
|
||||
|
||||
float ring[FFT_SIZE]; // letzte Abtastwerte ohne Gleichanteil
|
||||
uint16_t ringPos = 0;
|
||||
float dc = -1; // Gleichanteil (MAX9814 liegt bei ~1,25 V)
|
||||
float lastSample = 0;
|
||||
|
||||
float highAvg = 0; // mittlere Höhen-Energie der letzten Sekunde
|
||||
uint32_t lastClap = 0;
|
||||
bool clapPending = false;
|
||||
float loudness = 0;
|
||||
|
||||
float bassLow = 0; // Tiefpass (~150 Hz) für die Beat-Erkennung
|
||||
float bassAvg = 0; // mittlere Bass-Energie der letzten ~0,4 s
|
||||
uint32_t lastBeat = 0;
|
||||
bool beatPending = false;
|
||||
|
||||
// Passt einen Wert in dB an den Bereich der letzten Sekunden an -> 0..1
|
||||
struct AutoRange {
|
||||
float lo = 1e9f, hi = -1e9f;
|
||||
float operator()(float db) {
|
||||
lo = db < lo ? db : lo + 0.02f; // Grundgeräusch wandert langsam nach oben
|
||||
hi = db > hi ? db : hi - 0.05f; // Spitzen fallen langsam ab
|
||||
// Bis 3 dB über dem Grundrauschen gilt als Stille (das Mikro rauscht bei Ruhe kräftig)
|
||||
float range = max(hi - lo, 12.0f);
|
||||
return constrain((db - lo - 3) / (range - 3), 0.0f, 1.0f);
|
||||
}
|
||||
};
|
||||
AutoRange levelRange, bassRange, bandRange[CUBE_SIZE];
|
||||
|
||||
void audioBegin() {
|
||||
adc_unit_t unit;
|
||||
adc_continuous_io_to_channel(MIC_PIN, &unit, &micChannel);
|
||||
|
||||
adc_continuous_handle_cfg_t handleCfg = {};
|
||||
handleCfg.max_store_buf_size = 4096;
|
||||
handleCfg.conv_frame_size = 256;
|
||||
adc_continuous_new_handle(&handleCfg, &adc);
|
||||
|
||||
adc_digi_pattern_config_t pattern = {};
|
||||
pattern.atten = ADC_ATTEN_DB_12;
|
||||
pattern.channel = micChannel;
|
||||
pattern.unit = ADC_UNIT_1;
|
||||
pattern.bit_width = SOC_ADC_DIGI_MAX_BITWIDTH;
|
||||
|
||||
adc_continuous_config_t cfg = {};
|
||||
cfg.pattern_num = 1;
|
||||
cfg.adc_pattern = &pattern;
|
||||
cfg.sample_freq_hz = SAMPLE_RATE;
|
||||
cfg.conv_mode = ADC_CONV_SINGLE_UNIT_1;
|
||||
cfg.format = ADC_DIGI_OUTPUT_FORMAT_TYPE2;
|
||||
adc_continuous_config(adc, &cfg);
|
||||
adc_continuous_start(adc);
|
||||
}
|
||||
|
||||
uint32_t lastData = 0;
|
||||
|
||||
void audioUpdate(uint32_t now) {
|
||||
uint8_t buf[256];
|
||||
uint32_t len;
|
||||
float energy = 0, highEnergy = 0, bassEnergy = 0;
|
||||
uint32_t n = 0;
|
||||
|
||||
while (adc_continuous_read(adc, buf, sizeof(buf), &len, 0) == ESP_OK) {
|
||||
for (uint32_t i = 0; i < len; i += SOC_ADC_DIGI_RESULT_BYTES) {
|
||||
auto *d = reinterpret_cast<adc_digi_output_data_t *>(&buf[i]);
|
||||
if (d->type2.channel != micChannel) continue;
|
||||
float x = d->type2.data;
|
||||
if (dc < 0) dc = x;
|
||||
dc += (x - dc) * 0.001f;
|
||||
float s = x - dc;
|
||||
ring[ringPos] = s;
|
||||
ringPos = (ringPos + 1) % FFT_SIZE;
|
||||
float diff = s - lastSample; // Hochpass: betont Klatschen, dämpft Bass
|
||||
lastSample = s;
|
||||
energy += s * s;
|
||||
highEnergy += diff * diff;
|
||||
bassLow += (s - bassLow) * 0.09f; // Tiefpass 150 Hz bei 10 kHz
|
||||
bassEnergy += bassLow * bassLow;
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
// Der WLAN-Start nutzt denselben ADC und lässt die Abtastung manchmal hängen:
|
||||
// kommen keine Werte mehr, den ADC neu starten.
|
||||
if (n) {
|
||||
lastData = now;
|
||||
} else if (now - lastData > 250) {
|
||||
adc_continuous_stop(adc);
|
||||
adc_continuous_start(adc);
|
||||
lastData = now;
|
||||
Serial.println("Mikrofon: ADC neu gestartet");
|
||||
}
|
||||
if (!n) return;
|
||||
|
||||
// Klatschen: plötzlich viel mehr Höhen als im Mittel der letzten Sekunde und
|
||||
// absolut kräftig (sonst lösen harte Konsonanten beim Sprechen aus)
|
||||
float high = sqrtf(highEnergy / n);
|
||||
if (highAvg == 0) highAvg = high; // Start: kein Fehlalarm, solange der Mittelwert fehlt
|
||||
float ratio = high / (highAvg + 1);
|
||||
if (ratio > CLAP_RATIO && high > CLAP_MIN && now - lastClap > 300) {
|
||||
lastClap = now;
|
||||
clapPending = true;
|
||||
Serial.printf("Klatschen erkannt (%.1f-fach)\n", ratio);
|
||||
}
|
||||
highAvg += (high - highAvg) * 0.02f;
|
||||
|
||||
// Beat: Bass-Energie springt deutlich über ihr kurzes Mittel und ist laut genug
|
||||
float bass = sqrtf(bassEnergy / n);
|
||||
if (bassAvg == 0) bassAvg = bass;
|
||||
bool bassLoud = bassRange(20 * log10f(bass + 1)) > 0.3f;
|
||||
if (bass > bassAvg * 2.0f && bassLoud && now - lastBeat > 250) {
|
||||
lastBeat = now;
|
||||
beatPending = true;
|
||||
}
|
||||
bassAvg += (bass - bassAvg) * 0.05f;
|
||||
|
||||
// Lautstärke: schnell hoch, langsam runter
|
||||
float l = levelRange(20 * log10f(sqrtf(energy / n) + 1));
|
||||
loudness = l > loudness ? l : loudness - 0.02f;
|
||||
}
|
||||
|
||||
bool audioBeat() {
|
||||
bool b = beatPending;
|
||||
beatPending = false;
|
||||
return b;
|
||||
}
|
||||
|
||||
bool audioClap() {
|
||||
bool c = clapPending;
|
||||
clapPending = false;
|
||||
return c;
|
||||
}
|
||||
|
||||
float audioLevel() {
|
||||
return max(loudness, 0.0f);
|
||||
}
|
||||
|
||||
void audioSpectrum(float bands[CUBE_SIZE]) {
|
||||
static float re[FFT_SIZE], im[FFT_SIZE];
|
||||
static ArduinoFFT<float> fft(re, im, FFT_SIZE, SAMPLE_RATE);
|
||||
static float shown[CUBE_SIZE];
|
||||
|
||||
for (uint16_t i = 0; i < FFT_SIZE; i++) {
|
||||
re[i] = ring[(ringPos + i) % FFT_SIZE];
|
||||
im[i] = 0;
|
||||
}
|
||||
fft.windowing(FFTWindow::Hann, FFTDirection::Forward);
|
||||
fft.compute(FFTDirection::Forward);
|
||||
fft.complexToMagnitude();
|
||||
|
||||
for (uint8_t b = 0; b < CUBE_SIZE; b++) {
|
||||
float sum = 0;
|
||||
for (uint8_t k = BAND_EDGES[b]; k < BAND_EDGES[b + 1]; k++) sum += re[k];
|
||||
float v = bandRange[b](20 * log10f(sum + 1));
|
||||
shown[b] = v > shown[b] ? v : max(shown[b] - 0.04f, 0.0f); // Säulen fallen langsam
|
||||
bands[b] = shown[b];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// Sockel für den 5x5x5-LED-Würfel (ESP32-S3-DevKitC-1 + Mikrofon MAX9814)
|
||||
//
|
||||
// Aufbau: Wanne (Boden + Wände + Halterungen) und flacher Deckel, auf dem der
|
||||
// Würfel steht. Der Deckel hat unten einen umlaufenden Steckrand mit Rastwulsten
|
||||
// und schnappt ohne Schrauben in eine Rille innen in der Wanne. Die 4 Messingbolzen
|
||||
// des Würfels gehen mit ihrem M3-Gewinde durch den Deckel und werden unten mit
|
||||
// M3-Muttern festgezogen. Beide Teile brauchen keine Stützen.
|
||||
//
|
||||
// Druckteile (Parameter "part"):
|
||||
// "wanne" Boden nach unten drucken
|
||||
// "deckel" Oberseite nach unten drucken (wird schon so herum ausgegeben)
|
||||
// "schablone" 2 mm dünne Lochschablone: vorab drucken und auf die Bolzen stecken
|
||||
// "vorschau" alles zusammen mit Würfel und Platinen (nur zum Ansehen)
|
||||
// "explosion" wie "vorschau", auseinandergezogen
|
||||
//
|
||||
// Alle Maße in mm. Werte mit "MESSEN" sind aus Fotos geschätzt.
|
||||
|
||||
part = "vorschau";
|
||||
|
||||
/* [Würfel] */
|
||||
cube_pcb = 70; // MESSEN: Kantenlänge einer Etagen-Platine
|
||||
// Die Bolzen sitzen wie ein Windrad bei (bolt_a, bolt_b), jeweils um 90° gedreht.
|
||||
// Abstand benachbarter Bolzen = sqrt((a-b)^2 + (a+b)^2) ≈ 60 mm
|
||||
bolt_a = 33.6; // MESSEN
|
||||
bolt_b = 26.9; // MESSEN
|
||||
bolt_hole = 3.4; // Durchgang für das M3-Gewinde der Bolzen
|
||||
spacer = 2.4; // je eine M3-Mutter zwischen Würfel und Deckel als Abstandshalter,
|
||||
// damit die Lötstellen der unteren Etage nicht aufliegen (nur Vorschau)
|
||||
cable_pos = [27, 19]; // Kabeldurchführung unter der DI/DO-Ecke
|
||||
cable_d = 8;
|
||||
|
||||
/* [Sockel] */
|
||||
size = 96; // Außenmaß (quadratisch)
|
||||
height = 28; // Gesamthöhe
|
||||
radius = 0; // Eckenradius (0 = spitze Ecken)
|
||||
round_top = 0; // Rundung der oberen Deckelkante (0 = scharfe Kante)
|
||||
chamfer_bottom = 0; // Fase an der Unterkante
|
||||
seam = 0; // kleine Fase an der Fuge Wanne/Deckel, versteckt Druckversatz
|
||||
wall = 2.4;
|
||||
lid_t = 3; // Dicke des Deckels
|
||||
floor_t = 2.4; // Dicke des Bodens
|
||||
foot_d = 10; // Vertiefungen unten für Gummifüße (0 = keine)
|
||||
pry_w = 10; // Kerbe hinten, um den Deckel aufzuhebeln (0 = keine)
|
||||
|
||||
/* [Schnappverschluss] */
|
||||
lip_t = 1.6; // Steckrand unter dem Deckel
|
||||
lip_h = 8;
|
||||
gap = 0.25; // Spiel zwischen Steckrand und Wanne (Deckel geht schwer rein: größer)
|
||||
snap = 0.6; // Höhe der Rastwulste (hält zu schwach: größer, zu fest: kleiner)
|
||||
snap_z = 5.5; // Wulst so weit unter dem Deckel
|
||||
snap_len = 34; // Wulstlänge je Seite, nur auf den geraden Stücken (federn dort)
|
||||
|
||||
/* [ESP32-S3-DevKitC-1] */
|
||||
esp_l = 57.5; // MESSEN: Platinenlänge ohne Antennenüberstand
|
||||
esp_w = 28.5; // MESSEN: Platinenbreite
|
||||
esp_t = 1.6;
|
||||
esp_lift = 4; // Platine liegt so hoch über dem Boden (Lötstellen unten)
|
||||
// MESSEN: Mitte der beiden USB-C-Buchsen, gemessen von der Platinenkante
|
||||
// mit der Pin-Reihe "GND TX RX 1 2 ..."
|
||||
usb_x = [6.7, 19.2];
|
||||
usb_h = 3.3; // Höhe der Buchsen über der Platine
|
||||
usb_open = [27, 8]; // gemeinsame Öffnung für beide Stecker (Breite, Höhe)
|
||||
|
||||
/* [Mikrofon MAX9814] */
|
||||
mic_l = 26; // MESSEN: Modullänge
|
||||
mic_w = 16; // MESSEN: Modulbreite (das Modul steht hochkant)
|
||||
mic_t = 1.6;
|
||||
capsule_h = 7; // Höhe der Kapsel über der Modul-Platine
|
||||
grille_n = 7; // Schlitze im Gitter vor dem Mikrofon
|
||||
grille_h = 10;
|
||||
|
||||
$fn = 64;
|
||||
eps = 0.01;
|
||||
|
||||
// --- abgeleitete Maße -----------------------------------------------------------
|
||||
|
||||
inner = size - 2 * wall;
|
||||
inner_r = max(radius - wall, 0);
|
||||
tub_h = height - lid_t; // Höhe der Wanne = Unterseite des Deckels
|
||||
bolts = [for (k = [0:3]) rot2([bolt_a, bolt_b], 90 * k)];
|
||||
|
||||
// Rastrille: etwas tiefer als die Wulst und so weit nach unten versetzt, dass die
|
||||
// 45°-Flächen von Wulst und Rille aufeinanderliegen (Deckel sitzt ohne Spiel)
|
||||
groove_d = snap + 0.2;
|
||||
groove_z = tub_h - snap_z - (groove_d - snap + gap);
|
||||
|
||||
// ESP: USB-Ende zeigt nach hinten (+y), Platinenkante 1 mm vor der Innenwand
|
||||
esp_y1 = inner / 2 - 1;
|
||||
esp_y0 = esp_y1 - esp_l;
|
||||
esp_z = floor_t + esp_lift; // Unterseite der Platine
|
||||
usb_z = esp_z + esp_t + usb_h / 2; // Mitte der USB-Buchsen
|
||||
usb_cx = -esp_w / 2 + (usb_x[0] + usb_x[1]) / 2;
|
||||
|
||||
// Mikrofon: steht hochkant parallel zur Vorderwand, Kapsel zeigt nach vorn (-y)
|
||||
mic_y = -inner / 2 + 0.5 + capsule_h; // Vorderseite der Modul-Platine
|
||||
mic_z = floor_t + 1; // Unterkante des Moduls
|
||||
mic_cz = mic_z + mic_w / 2; // Höhe der Kapselmitte
|
||||
|
||||
function rot2(p, a) = [p[0] * cos(a) - p[1] * sin(a), p[0] * sin(a) + p[1] * cos(a)];
|
||||
|
||||
module outline(s, r) {
|
||||
if (r > 0) offset(r) square(s - 2 * r, center = true);
|
||||
else square(s, center = true);
|
||||
}
|
||||
|
||||
// Dünne Scheibe der abgerundeten Grundform auf Höhe z, um "inset" nach innen
|
||||
// versetzt (negativ = nach außen). Mehrere davon mit hull() ergeben Fasen und Rundungen.
|
||||
// Spitze Ecken (r = 0) bleiben dabei spitz.
|
||||
module slice(z, inset, s = size, r = radius) {
|
||||
translate([0, 0, z]) linear_extrude(eps) outline(s - 2 * inset, r > 0 ? max(r - inset, 0) : 0);
|
||||
}
|
||||
|
||||
// Außenform: unten abgeschrägt, oben gerundet (top_r) oder abgeschrägt (top_c)
|
||||
module block(h, top_r = 0, top_c = 0, bot_c = 0) {
|
||||
hull() {
|
||||
slice(0, bot_c);
|
||||
slice(bot_c, 0);
|
||||
if (top_r > 0)
|
||||
for (i = [0:8]) let(a = 90 * i / 8)
|
||||
slice(h - top_r + top_r * sin(a) - eps, top_r * (1 - cos(a)));
|
||||
else {
|
||||
slice(h - top_c - eps, 0);
|
||||
slice(h - eps, top_c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Wanne: Boden, Wände, Halterungen -------------------------------------------
|
||||
|
||||
module tub() {
|
||||
difference() {
|
||||
block(tub_h, top_c = seam, bot_c = chamfer_bottom);
|
||||
// Innenraum, oben mit Einführschräge für den Steckrand
|
||||
translate([0, 0, floor_t]) linear_extrude(tub_h) outline(inner, inner_r);
|
||||
hull() {
|
||||
slice(tub_h - 0.8, 0, inner, inner_r);
|
||||
slice(tub_h + eps, -0.8, inner, inner_r);
|
||||
}
|
||||
// umlaufende Rastrille, Oberseite 45° (druckt ohne Stützen)
|
||||
hull() {
|
||||
slice(groove_z - 2 * groove_d, 0, inner, inner_r);
|
||||
slice(groove_z, -groove_d, inner, inner_r);
|
||||
slice(groove_z + groove_d, 0, inner, inner_r);
|
||||
}
|
||||
// Kerbe hinten zum Aufhebeln des Deckels
|
||||
if (pry_w > 0)
|
||||
translate([0, size / 2, tub_h]) rotate([90, 0, 0])
|
||||
scale([pry_w / 2, 1.5]) cylinder(r = 1, h = 3 * wall, center = true);
|
||||
// USB-C hinten
|
||||
translate([usb_cx, size / 2 - wall / 2, usb_z])
|
||||
cube([usb_open[0], wall + 2, usb_open[1]], center = true);
|
||||
// Schlitzgitter vorn vor dem Mikrofon
|
||||
for (i = [0:grille_n - 1])
|
||||
translate([(i - (grille_n - 1) / 2) * 3.2, -size / 2 + wall / 2, mic_cz])
|
||||
hull() for (dz = [-1, 1]) translate([0, 0, dz * (grille_h / 2 - 0.9)])
|
||||
rotate([90, 0, 0]) cylinder(d = 1.8, h = wall + 2, center = true);
|
||||
// Vertiefungen für Gummifüße
|
||||
if (foot_d > 0)
|
||||
for (sx = [-1, 1], sy = [-1, 1]) translate([sx * 30, sy * 30, -eps]) cylinder(d = foot_d, h = 1);
|
||||
}
|
||||
esp_holder();
|
||||
mic_holder();
|
||||
}
|
||||
|
||||
module esp_holder() {
|
||||
// Stützen unter der Platinenmitte (zwischen den Pin-Reihen ist unten alles flach)
|
||||
for (y = [esp_y0 + 8, (esp_y0 + esp_y1) / 2, esp_y1 - 10])
|
||||
translate([0, y, floor_t - eps]) cylinder(d = 5, h = esp_lift + eps);
|
||||
// Eckwinkel halten die Platine seitlich und vorne
|
||||
c = 0.5; // Spiel
|
||||
t = 1.6; // Wandstärke der Winkel
|
||||
leg = 6;
|
||||
h = esp_lift + esp_t + 1.5;
|
||||
for (sx = [-1, 1], end = [0, 1]) {
|
||||
y = end ? esp_y1 : esp_y0;
|
||||
sy = end ? 1 : -1;
|
||||
translate([sx * (esp_w / 2 + c), y + sy * c, floor_t - eps])
|
||||
mirror([sx < 0 ? 1 : 0, 0, 0]) mirror([0, sy < 0 ? 1 : 0, 0]) {
|
||||
translate([0, -leg, 0]) cube([t, leg + t, h]); // seitlich
|
||||
// vorne als Anschlag, nur bis Platinenoberkante: darüber steht die Antenne über
|
||||
if (!end) translate([-leg, 0, 0]) cube([leg + t, t, esp_lift + esp_t]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module mic_holder() {
|
||||
// Leiste mit Nut, in der das Modul hochkant steht (ggf. ein Tropfen Heißkleber)
|
||||
difference() {
|
||||
translate([-mic_l / 2 - 3, mic_y - 1.5, floor_t - eps]) cube([mic_l + 6, mic_t + 4.5, mic_z - floor_t + 3]);
|
||||
translate([-mic_l / 2 - 0.3, mic_y - 0.2, mic_z]) cube([mic_l + 0.6, mic_t + 0.4, 10]);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Deckel, auf dem der Würfel steht --------------------------------------------
|
||||
// Koordinaten wie eingebaut: Unterseite der Platte bei z = 0, Steckrand nach unten.
|
||||
|
||||
module lid() {
|
||||
lip_out = [inner - 2 * gap, inner_r - gap];
|
||||
lip_in = [inner - 2 * gap - 2 * lip_t, inner_r - gap - lip_t];
|
||||
difference() {
|
||||
union() {
|
||||
block(lid_t, top_r = round_top, bot_c = seam);
|
||||
// Steckrand
|
||||
translate([0, 0, -lip_h]) linear_extrude(lip_h + eps) difference() {
|
||||
outline(lip_out[0], lip_out[1]);
|
||||
outline(lip_in[0], lip_in[1]);
|
||||
}
|
||||
// Rastwulste: unten flache Auflaufschräge, oben 45°
|
||||
intersection() {
|
||||
difference() {
|
||||
hull() {
|
||||
slice(-snap_z - 2.5 * snap, gap, inner, inner_r);
|
||||
slice(-snap_z, gap - snap, inner, inner_r);
|
||||
slice(-snap_z + snap, gap, inner, inner_r);
|
||||
}
|
||||
translate([0, 0, -lip_h - 1]) linear_extrude(lip_h) outline(lip_in[0], lip_in[1]);
|
||||
}
|
||||
union() {
|
||||
cube([snap_len, 2 * size, 4 * lip_h], center = true);
|
||||
cube([2 * size, snap_len, 4 * lip_h], center = true);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (p = bolts) translate([p[0], p[1], -1]) cylinder(d = bolt_hole, h = lid_t + 2);
|
||||
translate([cable_pos[0], cable_pos[1], -1]) cylinder(d = cable_d, h = lid_t + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Lochschablone zum Prüfen der Bolzen-Positionen -----------------------------
|
||||
|
||||
module template() {
|
||||
difference() {
|
||||
linear_extrude(2) outline(cube_pcb, 3);
|
||||
for (p = bolts) translate([p[0], p[1], -1]) cylinder(d = bolt_hole, h = 4);
|
||||
translate([cable_pos[0], cable_pos[1], -1]) cylinder(d = cable_d, h = 4);
|
||||
translate([0, 0, -1]) linear_extrude(4) outline(cube_pcb - 30, 4); // spart Material
|
||||
}
|
||||
}
|
||||
|
||||
// --- Vorschau mit Platinen und Würfel -------------------------------------------
|
||||
|
||||
module nut() cylinder(d = 6.35, h = 2.4, $fn = 6);
|
||||
|
||||
module preview(explode = 0) {
|
||||
color("dimgray", 0.45) tub();
|
||||
color("gray", 0.9) translate([0, 0, tub_h + explode]) lid();
|
||||
// ESP32-S3 mit Antennenüberstand und USB-Buchsen
|
||||
color("black") translate([-esp_w / 2, esp_y0 - 6.5, esp_z]) cube([esp_w, esp_l + 6.5, esp_t]);
|
||||
for (x = usb_x) color("lightgray")
|
||||
translate([-esp_w / 2 + x - 4.5, esp_y1 - 7, esp_z + esp_t]) cube([9, 7.8, usb_h]);
|
||||
// Mikrofon-Modul mit Kapsel
|
||||
color("slateblue") translate([-mic_l / 2, mic_y, mic_z]) cube([mic_l, mic_t, mic_w]);
|
||||
color("silver") translate([-mic_l / 2 + 7, mic_y, mic_cz]) rotate([90, 0, 0]) cylinder(d = 9.7, h = capsule_h);
|
||||
// Würfel: 5 Etagen, Bolzen und Muttern
|
||||
base = height + spacer + explode;
|
||||
for (z = [0:4]) color("black", 0.85)
|
||||
translate([0, 0, base + z * 16]) linear_extrude(1.6) difference() {
|
||||
outline(cube_pcb, 2);
|
||||
outline(cube_pcb - 8, 1);
|
||||
}
|
||||
for (p = bolts) translate([p[0], p[1], 0]) {
|
||||
color("gold") translate([0, 0, tub_h - 2.4 + explode]) cylinder(d = 3, h = base + 4 * 16 + 8 - tub_h + 2.4 - explode);
|
||||
color("gold") translate([0, 0, base + 1.6]) cylinder(d = 4.5, h = 4 * 16 + 6);
|
||||
color("silver") {
|
||||
translate([0, 0, tub_h - 2.4 + explode]) nut();
|
||||
if (spacer > 0) translate([0, 0, height + explode]) nut();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (part == "wanne") tub();
|
||||
else if (part == "deckel") translate([0, 0, lid_t]) rotate([180, 0, 0]) lid();
|
||||
else if (part == "schablone") template();
|
||||
else if (part == "explosion") preview(40);
|
||||
else if (part == "vorschau") preview();
|
||||
+10082
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+28184
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 84 KiB |
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hardware: ESP32-C3 SuperMini + adressierbare RGB-LEDs (5 Ebenen à 5x5)
|
||||
//
|
||||
// Verdrahtung erste Ebene:
|
||||
// ESP 5V -> V (nur für eine Ebene mit begrenzter Helligkeit, s.u.)
|
||||
// ESP G -> G
|
||||
// ESP GPIO DATA_PIN -> DI (330 Ohm in Serie empfohlen)
|
||||
// Weitere Ebenen: DO der Ebene n -> DI der Ebene n+1
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// GPIO 10: kein Strapping-Pin, nicht USB/UART. Vermeiden: 2, 8, 9 (Strapping),
|
||||
// 20/21 (UART).
|
||||
#define DATA_PIN 10
|
||||
|
||||
// Mikrofon MAX9814: VDD -> 3.3, GND -> G, OUT -> MIC_PIN (muss ADC1 sein: GPIO 0-4)
|
||||
#define MIC_PIN 4
|
||||
// Taster jeweils zwischen Pin und G (interne Pull-ups)
|
||||
#define BUTTON1_PIN 6 // nächster Effekt
|
||||
#define BUTTON2_PIN 7 // Helligkeit umschalten
|
||||
|
||||
#define LED_TYPE WS2812B // Alternativen: PL9823, WS2811
|
||||
#define COLOR_ORDER GRB // bei falschen Farben ggf. RGB
|
||||
|
||||
#define CUBE_SIZE 5
|
||||
#define NUM_LAYERS 5 // aktuell verbaute Ebenen (Endausbau: 5)
|
||||
#define NUM_LEDS (CUBE_SIZE * CUBE_SIZE * NUM_LAYERS)
|
||||
|
||||
// Leistung: volles Weiß ~60 mA/LED -> 1,5 A pro Ebene, 7,5 A für den Würfel.
|
||||
// FastLED dimmt automatisch, damit MAX_MILLIAMPS nicht überschritten wird.
|
||||
// Über USB max. ~500 mA; mit externem 5V-Netzteil entsprechend erhöhen.
|
||||
#define BRIGHTNESS 32 // Grundhelligkeit beim Start 0..255; Taster 2: halb/normal/doppelt
|
||||
#define MAX_MILLIAMPS 500
|
||||
|
||||
// Klatschen -> Blitz: so viel lauter (Höhen) als im Mittel der letzten Sekunde
|
||||
// muss ein Knall sein. Kleiner = empfindlicher.
|
||||
#define CLAP_RATIO 5.0 // gemessen: Musik+3D-Drucker < 2,5, Sprechen <= 5,4, Klatschen 6-25
|
||||
// ... und so stark (Höhen, ADC-Einheiten) muss er mindestens sein.
|
||||
#define CLAP_MIN 700 // gemessen (ESP32-S3): Sprechen <= 540, Klatschen 1270-1600
|
||||
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <FastLED.h>
|
||||
#include "config.h"
|
||||
|
||||
extern CRGB leds[NUM_LEDS];
|
||||
|
||||
// Grundhelligkeit der Effekte und Helligkeit für Funken, Raketen, Bälle
|
||||
// (per Taster 2 oder REST-API einstellbar, siehe cube.ino)
|
||||
extern uint8_t brightness, highlight;
|
||||
|
||||
const uint8_t TOP = NUM_LAYERS - 1; // oberste Etage
|
||||
|
||||
// Koordinaten: z = Etage (0 = Etage 1 am ESP, unten), x/y = Position in der Etage.
|
||||
// Reihenfolge der LEDs innerhalb einer Etage – ungeprüfte Annahme (Schlangenlinie).
|
||||
const uint8_t LAYER_MAP[CUBE_SIZE][CUBE_SIZE] = {
|
||||
{ 0, 1, 2, 3, 4 },
|
||||
{ 9, 8, 7, 6, 5 },
|
||||
{ 10, 11, 12, 13, 14 },
|
||||
{ 19, 18, 17, 16, 15 },
|
||||
{ 20, 21, 22, 23, 24 },
|
||||
};
|
||||
|
||||
inline CRGB &at(uint8_t x, uint8_t y, uint8_t z) {
|
||||
return leds[z * CUBE_SIZE * CUBE_SIZE + LAYER_MAP[y][x]];
|
||||
}
|
||||
|
||||
// Steuerung (cube.ino), z. B. für die REST-API
|
||||
uint8_t numEffects();
|
||||
const char *effectId(uint8_t i); // feste Kennung, z. B. "feuer"
|
||||
const char *effectName(uint8_t i); // Anzeigename, z. B. "Feuer"
|
||||
bool effectIsMusic(uint8_t i); // Musik-Visualisierung?
|
||||
uint8_t currentEffect();
|
||||
void selectEffect(uint8_t i);
|
||||
void setBaseBrightness(uint8_t b); // Grundhelligkeit 0..255
|
||||
extern bool autoAdvance; // Effekte automatisch weiterschalten
|
||||
|
||||
// WLAN und REST-API (web.cpp)
|
||||
void webBegin();
|
||||
void webUpdate(uint32_t now); // einmal pro Frame aufrufen
|
||||
|
||||
// Mikrofon (audio.cpp)
|
||||
void audioBegin();
|
||||
void audioUpdate(uint32_t now); // einmal pro Frame aufrufen
|
||||
bool audioClap(); // true, wenn seit dem letzten Aufruf geklatscht wurde
|
||||
bool audioBeat(); // true, wenn seit dem letzten Aufruf ein Bass-Schlag kam
|
||||
float audioLevel(); // Lautstärke 0..1, passt sich automatisch an
|
||||
void audioSpectrum(float bands[CUBE_SIZE]); // 5 Frequenzbänder 0..1, Bass zuerst
|
||||
|
||||
// Spezialeffekte, die kurz über jedem Effekt laufen (effects.cpp)
|
||||
void triggerLightning(uint32_t now);
|
||||
void triggerExplosion(uint32_t now);
|
||||
void triggerRainbowWave(uint32_t now);
|
||||
void drawLightning(uint32_t now);
|
||||
void drawSpecials(uint32_t now); // alle laufenden Spezialeffekte zeichnen
|
||||
|
||||
// Effekte (effects.cpp); now = millis()
|
||||
void resetEffects(); // beim Effektwechsel
|
||||
void renderStorm(uint32_t now);
|
||||
void renderFire(uint32_t now);
|
||||
void renderRainbow(uint32_t now);
|
||||
void renderWave(uint32_t now);
|
||||
void renderGlitter(uint32_t now);
|
||||
void renderFireworks(uint32_t now);
|
||||
void renderMatrix(uint32_t now);
|
||||
void renderSnow(uint32_t now);
|
||||
void renderLava(uint32_t now);
|
||||
void renderHelix(uint32_t now);
|
||||
void renderBounce(uint32_t now);
|
||||
void renderShells(uint32_t now);
|
||||
// Musik-Effekte
|
||||
void renderSpectrum(uint32_t now);
|
||||
void renderPulse(uint32_t now);
|
||||
void renderShockwave(uint32_t now);
|
||||
void renderSoundLayers(uint32_t now);
|
||||
void renderSoundWave(uint32_t now);
|
||||
void renderDisco(uint32_t now);
|
||||
@@ -0,0 +1,140 @@
|
||||
// 5x5x5 RGB-LED-Würfel – Demo
|
||||
//
|
||||
// Die Effekte (effects.cpp) laufen nacheinander in Endlosschleife und werden
|
||||
// weich überblendet – jeweils innerhalb ihrer Kategorie (normal oder Musik). Taster 1: nächster Effekt, Taster 2: Helligkeit.
|
||||
// Klatschen löst in jedem Effekt einen Blitz aus (audio.cpp).
|
||||
// Steuerung per REST-API im WLAN: http://cube.local/api/... (web.cpp)
|
||||
|
||||
#include "cube.h"
|
||||
|
||||
CRGB leds[NUM_LEDS];
|
||||
|
||||
const uint8_t LEVELS[] = {BRIGHTNESS / 2, BRIGHTNESS, BRIGHTNESS * 2};
|
||||
uint8_t brightnessLevel = 1;
|
||||
uint8_t brightness, highlight;
|
||||
bool autoAdvance = true;
|
||||
|
||||
void setBaseBrightness(uint8_t b) {
|
||||
brightness = b;
|
||||
highlight = min(255, b * 4);
|
||||
}
|
||||
|
||||
void setLevel(uint8_t l) {
|
||||
brightnessLevel = l % sizeof(LEVELS);
|
||||
setBaseBrightness(LEVELS[brightnessLevel]);
|
||||
}
|
||||
|
||||
struct Effect {
|
||||
const char *id; // feste Kennung für die API
|
||||
const char *name;
|
||||
void (*render)(uint32_t now);
|
||||
uint32_t ms;
|
||||
bool music; // Musik-Visualisierung (reagiert auf das Mikrofon)
|
||||
};
|
||||
const Effect EFFECTS[] = {
|
||||
{"gewitter", "Gewitter", renderStorm, 40000, false},
|
||||
{"feuerwerk", "Feuerwerk", renderFireworks, 25000, false},
|
||||
{"wuerfel", "Würfel im Würfel", renderShells, 20000, false},
|
||||
{"feuer", "Feuer", renderFire, 20000, false},
|
||||
{"matrix", "Matrix", renderMatrix, 20000, false},
|
||||
{"regenbogen", "Regenbogen", renderRainbow, 20000, false},
|
||||
{"flummis", "Flummis", renderBounce, 20000, false},
|
||||
{"lavalampe", "Lavalampe", renderLava, 25000, false},
|
||||
{"sinuswelle", "Sinuswelle", renderWave, 21000, false},
|
||||
{"schnee", "Schnee", renderSnow, 25000, false},
|
||||
{"doppelhelix", "Doppelhelix", renderHelix, 20000, false},
|
||||
{"glitzer", "Glitzer", renderGlitter, 20000, false},
|
||||
{"spektrum", "Spektrum", renderSpectrum, 30000, true},
|
||||
{"puls", "Puls", renderPulse, 30000, true},
|
||||
{"schockwelle", "Schockwelle", renderShockwave, 30000, true},
|
||||
{"klangschichten", "Klangschichten", renderSoundLayers, 30000, true},
|
||||
{"klangwelle", "Klangwelle", renderSoundWave, 30000, true},
|
||||
{"disko", "Disko", renderDisco, 30000, true},
|
||||
};
|
||||
const uint8_t NUM_EFFECTS = sizeof(EFFECTS) / sizeof(EFFECTS[0]);
|
||||
const uint32_t FADE_MS = 500;
|
||||
|
||||
uint8_t current = 0;
|
||||
uint32_t effectStart = 0;
|
||||
|
||||
void startEffect(uint8_t i, uint32_t now) {
|
||||
current = i % NUM_EFFECTS;
|
||||
effectStart = now;
|
||||
resetEffects();
|
||||
FastLED.clear();
|
||||
Serial.printf("Effekt: %s\n", EFFECTS[current].name);
|
||||
}
|
||||
|
||||
// Nächster Effekt derselben Kategorie (Musik bzw. normale Effekte)
|
||||
uint8_t nextEffect(uint8_t i) {
|
||||
uint8_t n = i;
|
||||
do n = (n + 1) % NUM_EFFECTS;
|
||||
while (EFFECTS[n].music != EFFECTS[i].music);
|
||||
return n;
|
||||
}
|
||||
|
||||
uint8_t numEffects() { return NUM_EFFECTS; }
|
||||
bool effectIsMusic(uint8_t i) { return EFFECTS[i % NUM_EFFECTS].music; }
|
||||
const char *effectId(uint8_t i) { return EFFECTS[i % NUM_EFFECTS].id; }
|
||||
const char *effectName(uint8_t i) { return EFFECTS[i % NUM_EFFECTS].name; }
|
||||
uint8_t currentEffect() { return current; }
|
||||
void selectEffect(uint8_t i) { startEffect(i, millis()); }
|
||||
|
||||
// Taster gegen GND mit Entprellung; pressed() meldet jeden Druck einmal.
|
||||
struct Button {
|
||||
uint8_t pin;
|
||||
bool down = false;
|
||||
uint32_t changed = 0;
|
||||
|
||||
bool pressed(uint32_t now) {
|
||||
bool d = digitalRead(pin) == LOW;
|
||||
if (d == down || now - changed < 30) return false;
|
||||
down = d;
|
||||
changed = now;
|
||||
return d;
|
||||
}
|
||||
};
|
||||
Button button1{BUTTON1_PIN}, button2{BUTTON2_PIN};
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.setTxTimeoutMs(0); // Ausgaben nie blockieren, wenn am USB niemand mitliest
|
||||
pinMode(BUTTON1_PIN, INPUT_PULLUP);
|
||||
pinMode(BUTTON2_PIN, INPUT_PULLUP);
|
||||
setLevel(1);
|
||||
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
|
||||
FastLED.setMaxPowerInVoltsAndMilliamps(5, MAX_MILLIAMPS);
|
||||
#ifdef RGB_BUILTIN
|
||||
rgbLedWrite(RGB_BUILTIN, 0, 0, 0); // RGB-LED auf dem Board aus
|
||||
#endif
|
||||
random16_set_seed(esp_random());
|
||||
audioBegin();
|
||||
webBegin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Webseite zuerst: ihre Aktionen (Blitz, Effektwahl) nutzen millis() und
|
||||
// dürfen nicht nach dem Zeitpunkt "now" dieses Frames liegen.
|
||||
webUpdate(millis());
|
||||
uint32_t now = millis();
|
||||
|
||||
if (button1.pressed(now)) startEffect(nextEffect(current), now);
|
||||
if (button2.pressed(now)) {
|
||||
setLevel(brightnessLevel + 1);
|
||||
Serial.printf("Helligkeit: %u\n", brightness);
|
||||
}
|
||||
if (autoAdvance && now - effectStart >= EFFECTS[current].ms) startEffect(nextEffect(current), now);
|
||||
|
||||
audioUpdate(now);
|
||||
if (audioClap()) triggerLightning(now);
|
||||
|
||||
EFFECTS[current].render(now);
|
||||
drawSpecials(now);
|
||||
|
||||
// Ein- und Ausblenden beim Effektwechsel
|
||||
uint32_t t = now - effectStart;
|
||||
uint32_t edge = autoAdvance ? min(t, EFFECTS[current].ms - t) : t; // ohne Autowechsel kein Ausblenden
|
||||
FastLED.setBrightness(edge < FADE_MS ? edge * 255 / FADE_MS : 255);
|
||||
FastLED.show();
|
||||
delay(16);
|
||||
}
|
||||
+591
@@ -0,0 +1,591 @@
|
||||
#include "cube.h"
|
||||
|
||||
const float MID = (CUBE_SIZE - 1) / 2.0f; // Mitte des Würfels
|
||||
|
||||
float rnd(float a, float b) {
|
||||
return a + (b - a) * random16() / 65535.0f;
|
||||
}
|
||||
|
||||
// Setzt einen Punkt an die nächstgelegene LED (addiert, außerhalb wird ignoriert).
|
||||
void plot(float x, float y, float z, const CRGB &c) {
|
||||
int ix = lroundf(x), iy = lroundf(y), iz = lroundf(z);
|
||||
if (ix < 0 || iy < 0 || iz < 0 || ix >= CUBE_SIZE || iy >= CUBE_SIZE || iz >= NUM_LAYERS) return;
|
||||
at(ix, iy, iz) += c;
|
||||
}
|
||||
|
||||
// --- Partikel (Feuerwerk, Matrix, Schnee) ------------------------------------
|
||||
|
||||
struct Particle {
|
||||
float x, y, z, vx, vy, vz;
|
||||
CRGB color;
|
||||
uint8_t life; // 0 = frei, sonst Helligkeit
|
||||
};
|
||||
const uint8_t MAX_PARTICLES = 48;
|
||||
Particle particles[MAX_PARTICLES];
|
||||
|
||||
void spawnParticle(float x, float y, float z, float vx, float vy, float vz, const CRGB &color) {
|
||||
for (Particle &p : particles)
|
||||
if (!p.life) {
|
||||
p = {x, y, z, vx, vy, vz, color, 255};
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Bewegt alle Partikel; wer verglüht oder den Würfel verlässt, wird frei.
|
||||
void moveParticles(float gravity, float drag, uint8_t fade) {
|
||||
for (Particle &p : particles) {
|
||||
if (!p.life) continue;
|
||||
p.vx *= drag;
|
||||
p.vy *= drag;
|
||||
p.vz = p.vz * drag - gravity;
|
||||
p.x += p.vx;
|
||||
p.y += p.vy;
|
||||
p.z += p.vz;
|
||||
p.life = qsub8(p.life, fade);
|
||||
if (p.z < -0.5f || p.x < -0.5f || p.y < -0.5f || p.x > CUBE_SIZE - 0.5f || p.y > CUBE_SIZE - 0.5f)
|
||||
p.life = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void drawParticles() {
|
||||
for (const Particle &p : particles)
|
||||
if (p.life) plot(p.x, p.y, p.z, CRGB(p.color).nscale8(p.life));
|
||||
}
|
||||
|
||||
// --- Gewitter (für Manuel); Blitze gibt es auch beim Klatschen in jedem Effekt --
|
||||
|
||||
const uint8_t MAX_DROPS = 16;
|
||||
const uint8_t MAX_POINTS = 16; // Punkte pro Blitz
|
||||
const uint8_t MAX_PULSES = 4; // Teilentladungen pro Blitz
|
||||
|
||||
struct Drop {
|
||||
bool active;
|
||||
uint8_t x, y;
|
||||
int16_t z16; // Höhe in 1/16 Etagen
|
||||
};
|
||||
Drop drops[MAX_DROPS];
|
||||
|
||||
struct Bolt {
|
||||
bool active;
|
||||
uint32_t start;
|
||||
uint8_t n, x[MAX_POINTS], y[MAX_POINTS], z[MAX_POINTS];
|
||||
uint8_t pulses;
|
||||
uint16_t on[MAX_PULSES], len[MAX_PULSES], end; // ms nach start
|
||||
};
|
||||
Bolt bolt;
|
||||
uint32_t nextStrike = 0;
|
||||
|
||||
void addPoint(uint8_t x, uint8_t y, uint8_t z) {
|
||||
if (bolt.n == MAX_POINTS) return;
|
||||
bolt.x[bolt.n] = x;
|
||||
bolt.y[bolt.n] = y;
|
||||
bolt.z[bolt.n] = z;
|
||||
bolt.n++;
|
||||
}
|
||||
|
||||
// Ein Schritt zur Seite (±1 in x oder y), am Rand nach innen.
|
||||
void zigzag(uint8_t &x, uint8_t &y) {
|
||||
uint8_t &c = random8(2) ? x : y;
|
||||
if (c == 0) c = 1;
|
||||
else if (c == CUBE_SIZE - 1) c--;
|
||||
else if (random8(2)) c++;
|
||||
else c--;
|
||||
}
|
||||
|
||||
void triggerLightning(uint32_t now) {
|
||||
// Zickzack-Pfad von der Wolke nach unten, manchmal mit Verzweigung
|
||||
bolt.n = 0;
|
||||
uint8_t x = random8(CUBE_SIZE), y = random8(CUBE_SIZE);
|
||||
int8_t branchAt = random8(2) ? random8(1, TOP) : -1;
|
||||
for (int8_t z = TOP; z >= 0; z--) {
|
||||
addPoint(x, y, z);
|
||||
if (z == branchAt) {
|
||||
uint8_t bx = x, by = y;
|
||||
for (int8_t bz = z - 1; bz >= 0 && bz >= z - 2; bz--) {
|
||||
zigzag(bx, by);
|
||||
addPoint(bx, by, bz);
|
||||
}
|
||||
}
|
||||
switch (random8(3)) {
|
||||
case 0: break; // senkrecht weiter
|
||||
case 1: zigzag(x, y); break; // schräg weiter
|
||||
case 2: zigzag(x, y); addPoint(x, y, z); break; // Knick in der Etage
|
||||
}
|
||||
}
|
||||
|
||||
// Ein Blitz flackert mehrmals kurz hintereinander
|
||||
bolt.pulses = random8(2, MAX_PULSES + 1);
|
||||
uint16_t t = 0;
|
||||
for (uint8_t i = 0; i < bolt.pulses; i++) {
|
||||
bolt.on[i] = t;
|
||||
bolt.len[i] = random8(30, 90);
|
||||
t += bolt.len[i] + random8(40, 140);
|
||||
}
|
||||
bolt.end = bolt.on[bolt.pulses - 1] + bolt.len[bolt.pulses - 1];
|
||||
bolt.start = now;
|
||||
bolt.active = true;
|
||||
}
|
||||
|
||||
void renderStorm(uint32_t now) {
|
||||
FastLED.clear();
|
||||
|
||||
// Wolken: oberste Etage, dunkel grau-blau wabernd
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++)
|
||||
at(x, y, TOP) = CHSV(160, 120, scale8(inoise8(x * 80, y * 80, now / 4), brightness));
|
||||
|
||||
// Regen: Tropfen fallen unter den Wolken nach unten
|
||||
for (Drop &d : drops) {
|
||||
if (!d.active) {
|
||||
if (random8() < 10) d = {true, random8(CUBE_SIZE), random8(CUBE_SIZE), int16_t(TOP * 16 - 1)};
|
||||
continue;
|
||||
}
|
||||
at(d.x, d.y, d.z16 / 16) += CRGB(0, brightness / 3, brightness);
|
||||
d.z16 -= 4;
|
||||
if (d.z16 < 0) d.active = false;
|
||||
}
|
||||
|
||||
// Blitze in zufälligen Abständen (gezeichnet wird in drawLightning)
|
||||
if (!bolt.active && int32_t(now - nextStrike) >= 0) {
|
||||
triggerLightning(now);
|
||||
nextStrike = now + bolt.end + 300 + random16(500, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// Zeichnet einen laufenden Blitz über den aktuellen Effekt.
|
||||
void drawLightning(uint32_t now) {
|
||||
if (!bolt.active) return;
|
||||
uint32_t dt = now - bolt.start;
|
||||
bool flash = false;
|
||||
for (uint8_t i = 0; i < bolt.pulses; i++)
|
||||
if (dt >= bolt.on[i] && dt < bolt.on[i] + bolt.len[i]) flash = true;
|
||||
|
||||
CRGB c;
|
||||
if (flash) {
|
||||
c = CRGB(220, 220, 255);
|
||||
for (CRGB &l : leds) l += CRGB(brightness / 4, brightness / 4, brightness / 2); // Himmel leuchtet mit auf
|
||||
} else if (dt < bolt.end) {
|
||||
c = CRGB(30, 20, 60); // Kanal glimmt zwischen den Entladungen
|
||||
} else if (dt < bolt.end + 300u) {
|
||||
uint8_t v = 120 - 120 * (dt - bolt.end) / 300; // Nachglühen
|
||||
c = CRGB(v / 2, v / 3, v);
|
||||
} else {
|
||||
bolt.active = false;
|
||||
return;
|
||||
}
|
||||
for (uint8_t i = 0; i < bolt.n; i++) at(bolt.x[i], bolt.y[i], bolt.z[i]) = c;
|
||||
}
|
||||
|
||||
// --- Feuer: Flammen in jeder Säule, unten heiß, oben glimmend ----------------
|
||||
|
||||
uint8_t heat[CUBE_SIZE][CUBE_SIZE][NUM_LAYERS];
|
||||
|
||||
void renderFire(uint32_t now) {
|
||||
static uint32_t last = 0;
|
||||
if (now - last >= 30) {
|
||||
last = now;
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
uint8_t *h = heat[x][y];
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) h[z] = qsub8(h[z], random8(0, 90)); // abkühlen
|
||||
for (uint8_t z = TOP; z >= 2; z--) h[z] = (h[z - 1] + 2 * h[z - 2]) / 3; // Hitze steigt
|
||||
if (random8() < 100) { // Funken unten
|
||||
uint8_t s = random8(2);
|
||||
h[s] = qadd8(h[s], random8(150, 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++)
|
||||
at(x, y, z) = HeatColor(heat[x][y][z]).nscale8(brightness);
|
||||
}
|
||||
|
||||
// --- Regenbogen, der nach oben steigt -----------------------------------------
|
||||
|
||||
void renderRainbow(uint32_t now) {
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++)
|
||||
at(x, y, z) = CHSV(uint8_t(now / 8 - z * 32 + (x + y) * 6), 255, brightness);
|
||||
}
|
||||
|
||||
// --- Sinuswelle: eine wogende Fläche, wechselt zwischen drei Wellenformen ------
|
||||
|
||||
// Höhe der Fläche über Säule (x, y), 0 .. TOP
|
||||
float waveHeight(uint8_t form, uint8_t x, uint8_t y, float phase) {
|
||||
float s;
|
||||
switch (form) {
|
||||
case 0: s = x * 1.2f; break; // läuft quer durch
|
||||
case 1: s = (x + y) * 0.8f; break; // diagonal
|
||||
default: s = hypotf(x - MID, y - MID) * 1.6f; break; // Kreiswellen von der Mitte
|
||||
}
|
||||
return MID + MID * sinf(s - phase);
|
||||
}
|
||||
|
||||
void renderWave(uint32_t now) {
|
||||
const uint32_t FORM_MS = 7000, BLEND_MS = 1000;
|
||||
float phase = (now % 1600) / 1600.0f * TWO_PI; // eine Schwingung in 1,6 s
|
||||
|
||||
// Am Ende jeder Wellenform weich in die nächste überblenden
|
||||
uint32_t slot = now / FORM_MS, inSlot = now % FORM_MS;
|
||||
uint8_t a = slot % 3, b = (slot + 1) % 3;
|
||||
float w = inSlot > FORM_MS - BLEND_MS ? float(inSlot - (FORM_MS - BLEND_MS)) / BLEND_MS : 0;
|
||||
w = w * w * (3 - 2 * w);
|
||||
|
||||
FastLED.clear();
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float h = (1 - w) * waveHeight(a, x, y, phase) + w * waveHeight(b, x, y, phase);
|
||||
uint8_t hue = now / 50 + uint8_t(h * 25); // Berge und Täler in verschiedenen Farben
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float d = fabsf(z - h); // zwischen zwei Etagen weich verteilen
|
||||
if (d < 1) at(x, y, z) = CHSV(hue, 255, uint8_t((1 - d) * highlight));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Glitzer: bunte Funken, die langsam verglühen -----------------------------
|
||||
|
||||
void renderGlitter(uint32_t now) {
|
||||
fadeToBlackBy(leds, NUM_LEDS, 12);
|
||||
if (random8() < 100) leds[random16(NUM_LEDS)] = CHSV(random8(), 160, highlight);
|
||||
}
|
||||
|
||||
// --- Feuerwerk: Raketen steigen auf und zerplatzen in bunte Funken -------------
|
||||
|
||||
struct Rocket {
|
||||
bool active;
|
||||
uint8_t x, y, hue;
|
||||
float z, target;
|
||||
};
|
||||
Rocket rocket;
|
||||
uint32_t nextLaunch = 0;
|
||||
|
||||
void renderFireworks(uint32_t now) {
|
||||
FastLED.clear();
|
||||
if (!rocket.active && int32_t(now - nextLaunch) >= 0) {
|
||||
rocket = {true, random8(1, CUBE_SIZE - 1), random8(1, CUBE_SIZE - 1), random8(), 0, rnd(2.5f, TOP)};
|
||||
nextLaunch = now + random16(800, 2200);
|
||||
}
|
||||
if (rocket.active) {
|
||||
rocket.z += 0.1f;
|
||||
if (rocket.z < rocket.target) {
|
||||
plot(rocket.x, rocket.y, rocket.z, CRGB(highlight, highlight / 2, highlight / 6)); // Kopf
|
||||
plot(rocket.x, rocket.y, rocket.z - 1, CRGB(brightness, brightness / 4, 0)); // Schweif
|
||||
} else {
|
||||
rocket.active = false;
|
||||
uint8_t n = random8(14, 24);
|
||||
for (uint8_t i = 0; i < n; i++) {
|
||||
float vx = rnd(-1, 1), vy = rnd(-1, 1), vz = rnd(-1, 1);
|
||||
float k = rnd(0.05f, 0.12f) / (sqrtf(vx * vx + vy * vy + vz * vz) + 0.01f);
|
||||
CRGB c = CHSV(rocket.hue + random8(40), random8(4) ? 255 : 0, highlight); // ab und zu weiß
|
||||
spawnParticle(rocket.x, rocket.y, rocket.z, vx * k, vy * k, vz * k, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
moveParticles(0.004f, 0.96f, 5);
|
||||
drawParticles();
|
||||
}
|
||||
|
||||
// --- Matrix: grüne Zeichenketten rieseln herab --------------------------------
|
||||
|
||||
void renderMatrix(uint32_t now) {
|
||||
FastLED.clear();
|
||||
if (random8() < 40)
|
||||
spawnParticle(random8(CUBE_SIZE), random8(CUBE_SIZE), TOP, 0, 0, -rnd(0.06f, 0.15f), CRGB::Black);
|
||||
moveParticles(0, 1, 0);
|
||||
for (const Particle &p : particles) {
|
||||
if (!p.life) continue;
|
||||
plot(p.x, p.y, p.z + 2, CRGB(0, brightness / 4, 0));
|
||||
plot(p.x, p.y, p.z + 1, CRGB(0, brightness, 0));
|
||||
plot(p.x, p.y, p.z, CRGB(highlight / 2, highlight, highlight / 2));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Schnee: Flocken taumeln herab und bleiben unten kurz liegen ---------------
|
||||
|
||||
uint8_t ground[CUBE_SIZE][CUBE_SIZE];
|
||||
|
||||
void renderSnow(uint32_t now) {
|
||||
FastLED.clear();
|
||||
if (random8() < 15) {
|
||||
CRGB white(highlight / 2, highlight / 2, highlight / 2);
|
||||
spawnParticle(rnd(0, CUBE_SIZE - 1), rnd(0, CUBE_SIZE - 1), TOP + 0.4f, 0, 0, -rnd(0.012f, 0.02f), white);
|
||||
}
|
||||
for (Particle &p : particles) {
|
||||
if (!p.life) continue;
|
||||
p.vx = constrain(p.vx + rnd(-0.002f, 0.002f), -0.015f, 0.015f); // taumeln
|
||||
p.vy = constrain(p.vy + rnd(-0.002f, 0.002f), -0.015f, 0.015f);
|
||||
if (p.z + p.vz < 0) { // gelandet
|
||||
uint8_t &g = ground[constrain(lroundf(p.x), 0, CUBE_SIZE - 1)][constrain(lroundf(p.y), 0, CUBE_SIZE - 1)];
|
||||
g = qadd8(g, 80);
|
||||
p.life = 0;
|
||||
}
|
||||
}
|
||||
moveParticles(0, 1, 0);
|
||||
|
||||
static uint8_t frame = 0;
|
||||
bool melt = ++frame % 6 == 0;
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
if (melt) ground[x][y] = qsub8(ground[x][y], 1);
|
||||
at(x, y, 0) = CRGB(brightness, brightness, brightness).nscale8(ground[x][y]);
|
||||
}
|
||||
drawParticles();
|
||||
}
|
||||
|
||||
// --- Lavalampe: glühende Blasen steigen langsam auf ---------------------------
|
||||
|
||||
void renderLava(uint32_t now) {
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
uint8_t n = inoise8(x * 50, uint16_t(y * 50 + now / 20), uint16_t(z * 50 - now / 8));
|
||||
n = qsub8(n, 60);
|
||||
n = qadd8(n, n); // Kontrast erhöhen
|
||||
at(x, y, z) = ColorFromPalette(LavaColors_p, n, brightness);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Doppelhelix: zwei Stränge winden sich um die Mitte -----------------------
|
||||
|
||||
void renderHelix(uint32_t now) {
|
||||
fadeToBlackBy(leds, NUM_LEDS, 60);
|
||||
float turn = (now % 2000) / 2000.0f * TWO_PI; // eine Umdrehung in 2 s
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float a = turn + z * TWO_PI / NUM_LAYERS;
|
||||
float dx = 1.9f * cosf(a), dy = 1.9f * sinf(a);
|
||||
uint8_t hue = now / 30 + z * 12;
|
||||
plot(MID + dx, MID + dy, z, CHSV(hue, 255, highlight));
|
||||
plot(MID - dx, MID - dy, z, CHSV(hue + 128, 255, highlight));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flummis: zwei Bälle springen durch den Würfel ----------------------------
|
||||
|
||||
struct Ball {
|
||||
float x, y, z, vx, vy, vz;
|
||||
uint8_t hue;
|
||||
};
|
||||
Ball balls[] = {{1, 1, TOP, 0.04f, 0.03f, 0, 0}, {3, 2, 2, -0.03f, 0.05f, 0, 128}};
|
||||
|
||||
void renderBounce(uint32_t now) {
|
||||
fadeToBlackBy(leds, NUM_LEDS, 50);
|
||||
const float g = 0.006f, hi = CUBE_SIZE - 1;
|
||||
for (Ball &b : balls) {
|
||||
b.vz -= g;
|
||||
b.x += b.vx;
|
||||
b.y += b.vy;
|
||||
b.z += b.vz;
|
||||
if (b.x < 0 || b.x > hi) { b.vx = -b.vx; b.x = constrain(b.x, 0, hi); b.hue += 30; }
|
||||
if (b.y < 0 || b.y > hi) { b.vy = -b.vy; b.y = constrain(b.y, 0, hi); b.hue += 30; }
|
||||
if (b.z < 0) { // Aufprall: springt immer wieder fast bis oben
|
||||
b.z = 0;
|
||||
b.vz = sqrtf(2 * g * rnd(2.5f, TOP));
|
||||
b.hue += 30;
|
||||
}
|
||||
plot(b.x, b.y, b.z, CHSV(b.hue, 255, highlight));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Würfel im Würfel: Wellen laufen von der Mitte zur Außenhaut ---------------
|
||||
|
||||
void renderShells(uint32_t now) {
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
int d = max(max(abs(x - 2), abs(y - 2)), abs(z - 2)); // 0 = Mitte, 2 = außen
|
||||
uint8_t wave = sin8(uint8_t(now / 4 - d * 70));
|
||||
wave = scale8(wave, wave); // schärfere Pulse
|
||||
at(x, y, z) = CHSV(uint8_t(now / 40 + d * 40), 255, scale8(wave, brightness));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Spektrum: Frequenzbänder als Säulen (Bass links), Verlauf wandert nach hinten
|
||||
|
||||
float history[CUBE_SIZE][CUBE_SIZE]; // [Alter][Band], Höhe 0..1
|
||||
|
||||
void renderSpectrum(uint32_t now) {
|
||||
static uint32_t lastShift = 0;
|
||||
if (now - lastShift >= 120) {
|
||||
lastShift = now;
|
||||
memmove(history[1], history[0], sizeof(history[0]) * (CUBE_SIZE - 1));
|
||||
}
|
||||
audioSpectrum(history[0]);
|
||||
|
||||
FastLED.clear();
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++) {
|
||||
uint8_t v = scale8(highlight, 255 - y * 40); // nach hinten sanft dunkler: 100 %, 84 %, 69 %, 53 %, 37 %
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float h = history[y][x] * NUM_LAYERS;
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float f = constrain(h - z, 0.0f, 1.0f);
|
||||
if (f > 0) at(x, y, z) = CHSV(x * 45, 255, uint8_t(f * v));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Puls: eine Kugel in der Mitte wächst mit der Lautstärke ------------------
|
||||
|
||||
void renderPulse(uint32_t now) {
|
||||
float l = audioLevel();
|
||||
float r = 0.6f + l * 2.6f;
|
||||
uint8_t hue = now / 60 + uint8_t(l * 60);
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float d = sqrtf(sq(x - MID) + sq(y - MID) + sq(z - MID));
|
||||
float f = constrain(r - d, 0.0f, 1.0f);
|
||||
at(x, y, z) = CHSV(hue + uint8_t(d * 20), 255, uint8_t(f * min(255, brightness * 2)));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Schockwelle: jeder Bass-Schlag schickt eine Kugelwelle von der Mitte los --
|
||||
|
||||
struct Shock {
|
||||
uint32_t start; // 0 = frei
|
||||
uint8_t hue;
|
||||
};
|
||||
Shock shocks[4];
|
||||
|
||||
void renderShockwave(uint32_t now) {
|
||||
static uint8_t next = 0, hue = 0;
|
||||
if (audioBeat()) {
|
||||
shocks[next] = {now, hue};
|
||||
next = (next + 1) % 4;
|
||||
hue += 40;
|
||||
}
|
||||
|
||||
FastLED.clear();
|
||||
float glow = audioLevel();
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float d = sqrtf(sq(x - MID) + sq(y - MID) + sq(z - MID));
|
||||
CRGB &led = at(x, y, z);
|
||||
// Glühen in der Mitte mit der Lautstärke
|
||||
float core = constrain(glow * 1.5f - d, 0.0f, 1.0f);
|
||||
led += CHSV(hue, 200, uint8_t(core * brightness));
|
||||
// Wellen: Radius wächst 8 Einheiten pro Sekunde, wird dabei schwächer
|
||||
for (Shock &w : shocks) {
|
||||
if (!w.start) continue;
|
||||
float r = (now - w.start) * 0.008f;
|
||||
float f = constrain(1 - fabsf(d - r), 0.0f, 1.0f) * constrain(1 - r / 4, 0.0f, 1.0f);
|
||||
if (f > 0) led += CHSV(w.hue, 255, uint8_t(f * highlight));
|
||||
}
|
||||
}
|
||||
for (Shock &w : shocks)
|
||||
if (w.start && now - w.start > 500) w.start = 0;
|
||||
}
|
||||
|
||||
// --- Klangschichten: unten Bass, oben Höhen; Lautstärke = Fläche in der Etage --
|
||||
|
||||
void renderSoundLayers(uint32_t now) {
|
||||
float bands[CUBE_SIZE];
|
||||
audioSpectrum(bands);
|
||||
FastLED.clear();
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float r = bands[z % CUBE_SIZE] * 3.2f; // 0 = nur Mitte, 3,2 = ganze Etage
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float d = sqrtf(sq(x - MID) + sq(y - MID));
|
||||
float f = constrain(r - d + 0.5f, 0.0f, 1.0f);
|
||||
if (f > 0) at(x, y, z) = CHSV(uint8_t(z * 45 + d * 8), 255, uint8_t(f * min(255, brightness * 3)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Klangwelle: Kreiswellen, deren Höhe der Lautstärke folgt -----------------
|
||||
|
||||
void renderSoundWave(uint32_t now) {
|
||||
static float amp = 0;
|
||||
float l = audioLevel();
|
||||
amp = l > amp ? l : amp * 0.97f; // schnell hoch, sanft zurück
|
||||
float phase = (now % 1200) / 1200.0f * TWO_PI;
|
||||
|
||||
FastLED.clear();
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float h = MID + MID * (0.15f + 0.85f * amp) * sinf(hypotf(x - MID, y - MID) * 1.6f - phase);
|
||||
uint8_t hue = now / 40 + uint8_t(h * 30);
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float d = fabsf(z - h);
|
||||
if (d < 1) at(x, y, z) = CHSV(hue, 255, uint8_t((1 - d) * highlight));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Disko: bunte Funken mit der Lautstärke, bei jedem Beat ein ganzer Schwall --
|
||||
|
||||
void renderDisco(uint32_t now) {
|
||||
fadeToBlackBy(leds, NUM_LEDS, 25);
|
||||
uint8_t sparks = audioLevel() * 3;
|
||||
if (audioBeat()) sparks += 20;
|
||||
for (uint8_t i = 0; i < sparks; i++)
|
||||
leds[random16(NUM_LEDS)] = CHSV(random8(), 220, highlight);
|
||||
}
|
||||
|
||||
// --- Spezialeffekte, die wie der Blitz kurz über jedem Effekt laufen --------------
|
||||
|
||||
uint32_t explosionStart = 0, rainbowStart = 0; // 0 = aus
|
||||
|
||||
void triggerExplosion(uint32_t now) { explosionStart = now; }
|
||||
void triggerRainbowWave(uint32_t now) { rainbowStart = now; }
|
||||
|
||||
// Feuerball aus der Mitte: weißer Kern, Schale wird von Weiß über Gelb zu Rot
|
||||
void drawExplosion(uint32_t now) {
|
||||
if (!explosionStart) return;
|
||||
uint32_t t = now - explosionStart;
|
||||
if (t > 550) {
|
||||
explosionStart = 0;
|
||||
return;
|
||||
}
|
||||
float r = t * 0.008f; // Radius: 4,4 Einheiten in 0,55 s
|
||||
float fade = 1 - t / 550.0f;
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++)
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++) {
|
||||
float d = sqrtf(sq(x - MID) + sq(y - MID) + sq(z - MID));
|
||||
float shell = constrain(1 - fabsf(d - r) / 1.2f, 0.0f, 1.0f) * fade;
|
||||
if (shell <= 0) continue;
|
||||
uint8_t heat = constrain(255 - int(t * 0.33f) - int(d * 20), 60, 255);
|
||||
at(x, y, z) += HeatColor(heat).nscale8(uint8_t(shell * 255));
|
||||
}
|
||||
}
|
||||
|
||||
// Regenbogen-Ebene rauscht einmal von unten nach oben
|
||||
void drawRainbowWave(uint32_t now) {
|
||||
if (!rainbowStart) return;
|
||||
uint32_t t = now - rainbowStart;
|
||||
if (t > 700) {
|
||||
rainbowStart = 0;
|
||||
return;
|
||||
}
|
||||
float pos = -1 + t / 700.0f * (NUM_LAYERS + 1); // in 0,7 s von unter Etage 0 bis über die oberste
|
||||
for (uint8_t z = 0; z < NUM_LAYERS; z++) {
|
||||
float f = constrain(1 - fabsf(z - pos) / 1.2f, 0.0f, 1.0f);
|
||||
if (f <= 0) continue;
|
||||
for (uint8_t y = 0; y < CUBE_SIZE; y++)
|
||||
for (uint8_t x = 0; x < CUBE_SIZE; x++)
|
||||
at(x, y, z) += CHSV(uint8_t((x + y) * 25 + t / 2), 255, uint8_t(f * 255));
|
||||
}
|
||||
}
|
||||
|
||||
void drawSpecials(uint32_t now) {
|
||||
drawRainbowWave(now);
|
||||
drawExplosion(now);
|
||||
drawLightning(now);
|
||||
}
|
||||
|
||||
// --- Effektwechsel ---------------------------------------------------------
|
||||
|
||||
void resetEffects() {
|
||||
for (Particle &p : particles) p.life = 0;
|
||||
for (Shock &w : shocks) w.start = 0;
|
||||
audioBeat(); // alten Beat verwerfen
|
||||
memset(history, 0, sizeof(history));
|
||||
memset(ground, 0, sizeof(ground));
|
||||
rocket.active = false;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Hardwaretest: Mikrofon (MAX9814 OUT an GPIO 4) und zwei Taster (GPIO 6/7 gegen GND).
|
||||
// Serielle Ausgabe; der Würfel zeigt die Lautstärke als Etagen von unten.
|
||||
// Farbe: grün = kein Taster, blau = Taster 1, rot = Taster 2, lila = beide.
|
||||
|
||||
#include <FastLED.h>
|
||||
|
||||
#define DATA_PIN 10
|
||||
#define NUM_LEDS 125
|
||||
#define MIC_PIN 4
|
||||
#define BTN1_PIN 6
|
||||
#define BTN2_PIN 7
|
||||
|
||||
CRGB leds[NUM_LEDS];
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
pinMode(BTN1_PIN, INPUT_PULLUP);
|
||||
pinMode(BTN2_PIN, INPUT_PULLUP);
|
||||
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
|
||||
FastLED.setBrightness(32);
|
||||
FastLED.setMaxPowerInVoltsAndMilliamps(5, 500);
|
||||
delay(1500);
|
||||
Serial.printf("Hardwaretest: Mikrofon GPIO %u, Taster GPIO %u und %u\n", MIC_PIN, BTN1_PIN, BTN2_PIN);
|
||||
Serial.print("ADC-Scan (mV):");
|
||||
for (uint8_t pin = 0; pin <= 4; pin++) Serial.printf(" GPIO%u=%lu", pin, analogReadMilliVolts(pin));
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
static uint32_t lastPrint = 0;
|
||||
static uint16_t maxPP = 0;
|
||||
static bool last1 = false, last2 = false;
|
||||
|
||||
// 20 ms lang so schnell wie möglich messen: Mittelwert und Spitze-Spitze
|
||||
uint16_t lo = 65535, hi = 0;
|
||||
uint32_t sum = 0, n = 0, start = millis();
|
||||
while (millis() - start < 20) {
|
||||
uint16_t v = analogReadMilliVolts(MIC_PIN);
|
||||
lo = min(lo, v);
|
||||
hi = max(hi, v);
|
||||
sum += v;
|
||||
n++;
|
||||
}
|
||||
uint16_t pp = hi - lo;
|
||||
maxPP = max(maxPP, pp);
|
||||
|
||||
bool b1 = digitalRead(BTN1_PIN) == LOW, b2 = digitalRead(BTN2_PIN) == LOW;
|
||||
if (b1 != last1) Serial.printf(">>> Taster 1 %s\n", b1 ? "gedrueckt" : "losgelassen");
|
||||
if (b2 != last2) Serial.printf(">>> Taster 2 %s\n", b2 ? "gedrueckt" : "losgelassen");
|
||||
last1 = b1;
|
||||
last2 = b2;
|
||||
|
||||
if (millis() - lastPrint >= 250) {
|
||||
lastPrint = millis();
|
||||
Serial.printf("t=%6.1fs Mikro: Mitte %4lu mV, Pegel %4u mV (%lu Messungen) | T1 %s T2 %s\n",
|
||||
millis() / 1000.0, sum / n, maxPP, n, b1 ? "GEDRUECKT" : "offen", b2 ? "GEDRUECKT" : "offen");
|
||||
maxPP = 0;
|
||||
}
|
||||
|
||||
// Lautstärke als Säule: 200 mV Spitze-Spitze pro Etage
|
||||
CRGB color = b1 && b2 ? CRGB::Purple : b1 ? CRGB::Blue : b2 ? CRGB::Red : CRGB::Green;
|
||||
uint8_t layers = min(5, (pp + 100) / 200);
|
||||
FastLED.clear();
|
||||
fill_solid(leds, layers * 25, color);
|
||||
FastLED.show();
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 77;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C0BE00000000000000000001 /* CubeRemote.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CubeRemote.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
||||
C0BE00000000000000000002 /* CubeRemote */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
path = CubeRemote;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXFileSystemSynchronizedRootGroup section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C0BE00000000000000000003 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C0BE00000000000000000004 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C0BE00000000000000000002 /* CubeRemote */,
|
||||
C0BE00000000000000000005 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C0BE00000000000000000005 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C0BE00000000000000000001 /* CubeRemote.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C0BE00000000000000000006 /* CubeRemote */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C0BE00000000000000000007 /* Build configuration list for PBXNativeTarget "CubeRemote" */;
|
||||
buildPhases = (
|
||||
C0BE00000000000000000008 /* Sources */,
|
||||
C0BE00000000000000000003 /* Frameworks */,
|
||||
C0BE00000000000000000009 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
fileSystemSynchronizedGroups = (
|
||||
C0BE00000000000000000002 /* CubeRemote */,
|
||||
);
|
||||
name = CubeRemote;
|
||||
packageProductDependencies = (
|
||||
);
|
||||
productName = CubeRemote;
|
||||
productReference = C0BE00000000000000000001 /* CubeRemote.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
C0BE0000000000000000000A /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
C0BE00000000000000000006 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C0BE0000000000000000000B /* Build configuration list for PBXProject "CubeRemote" */;
|
||||
developmentRegion = de;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
de,
|
||||
Base,
|
||||
);
|
||||
mainGroup = C0BE00000000000000000004;
|
||||
minimizedProjectReferenceProxies = 1;
|
||||
preferredProjectObjectVersion = 77;
|
||||
productRefGroup = C0BE00000000000000000005 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C0BE00000000000000000006 /* CubeRemote */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
C0BE00000000000000000009 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C0BE00000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
C0BE0000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
C0BE0000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
C0BE0000000000000000000E /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = RX5EBCNNWW;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Cube;
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Die App steuert den LED-Würfel in deinem WLAN.";
|
||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Dark;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = de.wesemann.CubeRemote;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
C0BE0000000000000000000F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = RX5EBCNNWW;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Cube;
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Die App steuert den LED-Würfel in deinem WLAN.";
|
||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Dark;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = de.wesemann.CubeRemote;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C0BE0000000000000000000B /* Build configuration list for PBXProject "CubeRemote" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C0BE0000000000000000000C /* Debug */,
|
||||
C0BE0000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
C0BE00000000000000000007 /* Build configuration list for PBXNativeTarget "CubeRemote" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C0BE0000000000000000000E /* Debug */,
|
||||
C0BE0000000000000000000F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = C0BE0000000000000000000A /* Project object */;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 557 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "filename" : "AppIcon.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
@State private var model = CubeModel()
|
||||
@State private var showSettings = false
|
||||
@State private var flashes = 0
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
// Kein Scrollen: die Effekt-Kacheln teilen sich die restliche Höhe
|
||||
VStack(spacing: 12) {
|
||||
status
|
||||
specials
|
||||
brightness
|
||||
autoToggle
|
||||
effectGrid
|
||||
}
|
||||
.padding(.horizontal)
|
||||
.padding(.vertical, 8)
|
||||
.navigationTitle("LED-Würfel")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
Button("Einstellungen", systemImage: "gearshape") { showSettings = true }
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $showSettings) {
|
||||
SettingsView(host: model.host) { model.host = CubeModel.cleanHost($0) }
|
||||
}
|
||||
// Nur abfragen, solange die App im Vordergrund ist
|
||||
.task(id: scenePhase) {
|
||||
if scenePhase == .active { await model.poll() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var status: some View {
|
||||
HStack(spacing: 6) {
|
||||
Circle()
|
||||
.fill(model.isConnected ? .green : model.error == nil ? .gray : .red)
|
||||
.frame(width: 8, height: 8)
|
||||
Text(model.error ?? (model.isConnected ? "Verbunden mit \(model.host)" : "Verbinde mit \(model.host) …"))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
/// Spezialeffekte, die kurz über dem laufenden Effekt abgespielt werden
|
||||
private var specials: some View {
|
||||
HStack(spacing: 8) {
|
||||
specialButton("blitz", "Blitz", "bolt.fill", .yellow)
|
||||
specialButton("explosion", "Explosion", "burst.fill", .orange)
|
||||
specialButton("regenbogen", "Regenbogen", "rainbow", .pink)
|
||||
}
|
||||
.sensoryFeedback(.impact(weight: .heavy), trigger: flashes)
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
private func specialButton(_ id: String, _ title: String, _ symbol: String, _ color: Color) -> some View {
|
||||
Button {
|
||||
flashes += 1
|
||||
Task { await model.special(id) }
|
||||
} label: {
|
||||
VStack(spacing: 4) {
|
||||
Image(systemName: symbol).font(.title2)
|
||||
Text(title)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.7)
|
||||
}
|
||||
.foregroundStyle(.black)
|
||||
.frame(maxWidth: .infinity, minHeight: 56)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.buttonBorderShape(.roundedRectangle(radius: 14))
|
||||
.tint(color)
|
||||
}
|
||||
|
||||
private var brightness: some View {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "sun.min.fill")
|
||||
.foregroundStyle(.secondary)
|
||||
Slider(value: $model.brightness, in: 0...255, step: 1) { editing in
|
||||
model.isDraggingBrightness = editing
|
||||
if !editing { Task { await model.commitBrightness() } }
|
||||
}
|
||||
.accessibilityLabel("Helligkeit")
|
||||
Image(systemName: "sun.max.fill")
|
||||
.foregroundStyle(.secondary)
|
||||
Text("\(Int(model.brightness))")
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 36, alignment: .trailing)
|
||||
}
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
private var autoToggle: some View {
|
||||
Toggle("Automatisch wechseln", isOn: Binding(
|
||||
get: { model.state?.auto ?? true },
|
||||
set: { on in Task { await model.setAuto(on) } }
|
||||
))
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
/// Links zwei Spalten normale Effekte, rechts eine Spalte Musik-Effekte.
|
||||
/// Die Zeilen wachsen mit dem Platz (32 bis 56 Punkte hoch).
|
||||
private var effectGrid: some View {
|
||||
let normal = model.effects.filter { !$0.isMusic }
|
||||
let music = model.effects.filter(\.isMusic)
|
||||
let rowCount = max((normal.count + 1) / 2, music.count)
|
||||
return VStack(spacing: 8) {
|
||||
HStack(spacing: 8) {
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
Label("Musik", systemImage: "music.note")
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
.opacity(model.effects.isEmpty ? 0 : 1)
|
||||
ForEach(0..<rowCount, id: \.self) { row in
|
||||
HStack(spacing: 8) {
|
||||
cell(normal, 2 * row)
|
||||
cell(normal, 2 * row + 1)
|
||||
cell(music, row)
|
||||
}
|
||||
.frame(minHeight: 32, maxHeight: 56)
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity, alignment: .top)
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func cell(_ effects: [CubeEffect], _ index: Int) -> some View {
|
||||
if index < effects.count {
|
||||
tile(effects[index])
|
||||
} else {
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
private func tile(_ effect: CubeEffect) -> some View {
|
||||
let active = effect.id == model.state?.effect
|
||||
let idle = effect.isMusic ? Color.indigo.opacity(0.35) : Color(.secondarySystemBackground)
|
||||
return Button {
|
||||
Task { await model.select(effect) }
|
||||
} label: {
|
||||
Text(effect.name)
|
||||
.font(.subheadline)
|
||||
.fontWeight(active ? .semibold : .regular)
|
||||
.multilineTextAlignment(.center)
|
||||
// Nur an Leerzeichen umbrechen; einzelne Wörter lieber verkleinern als trennen
|
||||
.lineLimit(effect.name.contains(" ") ? 2 : 1)
|
||||
.minimumScaleFactor(0.6)
|
||||
.foregroundStyle(active ? .black : .primary)
|
||||
.padding(.horizontal, 4)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(active ? Color.green : idle, in: .rect(cornerRadius: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
struct SettingsView: View {
|
||||
let host: String
|
||||
let save: (String) -> Void
|
||||
@State private var draft = ""
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
Form {
|
||||
Section {
|
||||
TextField("cube.local", text: $draft)
|
||||
.keyboardType(.URL)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
} header: {
|
||||
Text("Adresse des Würfels")
|
||||
} footer: {
|
||||
Text("Name oder IP-Adresse im WLAN, z. B. cube.local oder 10.0.1.8")
|
||||
}
|
||||
}
|
||||
.navigationTitle("Einstellungen")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button("Abbrechen") { dismiss() }
|
||||
}
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("Fertig") {
|
||||
save(draft)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
.onAppear { draft = host }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ContentView()
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import Foundation
|
||||
|
||||
/// Zustand des Würfels, wie ihn GET/PATCH /api/state liefern.
|
||||
struct CubeState: Codable, Equatable {
|
||||
var effect: String
|
||||
var auto: Bool
|
||||
var brightness: Int
|
||||
}
|
||||
|
||||
/// Ein Eintrag aus GET /api/effects.
|
||||
struct CubeEffect: Codable, Identifiable, Hashable {
|
||||
let id: String
|
||||
let name: String
|
||||
let music: Bool?
|
||||
|
||||
/// Musik-Visualisierung (reagiert auf das Mikrofon des Würfels)
|
||||
var isMusic: Bool { music ?? false }
|
||||
}
|
||||
|
||||
/// Änderung für PATCH /api/state – nur gesetzte Felder werden gesendet.
|
||||
struct CubeStatePatch: Encodable {
|
||||
var effect: String?
|
||||
var auto: Bool?
|
||||
var brightness: Int?
|
||||
}
|
||||
|
||||
struct CubeAPIError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
/// Zugriff auf die REST-API des Würfels (siehe web.cpp in der Firmware).
|
||||
struct CubeAPI {
|
||||
let host: String
|
||||
|
||||
private static let session: URLSession = {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 4
|
||||
return URLSession(configuration: config)
|
||||
}()
|
||||
|
||||
func state() async throws -> CubeState {
|
||||
let data = try await request("state")
|
||||
return try JSONDecoder().decode(CubeState.self, from: data)
|
||||
}
|
||||
|
||||
func effects() async throws -> [CubeEffect] {
|
||||
let data = try await request("effects")
|
||||
return try JSONDecoder().decode([CubeEffect].self, from: data)
|
||||
}
|
||||
|
||||
func update(_ patch: CubeStatePatch) async throws -> CubeState {
|
||||
let data = try await request("state", method: "PATCH", json: JSONEncoder().encode(patch))
|
||||
return try JSONDecoder().decode(CubeState.self, from: data)
|
||||
}
|
||||
|
||||
/// Spezialeffekt auslösen: "blitz", "explosion" oder "regenbogen"
|
||||
func special(_ id: String) async throws {
|
||||
_ = try await request("specials/\(id)", method: "POST")
|
||||
}
|
||||
|
||||
private func request(_ path: String, method: String = "GET", json: Data? = nil) async throws -> Data {
|
||||
guard let url = URL(string: "http://\(host)/api/\(path)") else {
|
||||
throw CubeAPIError(message: "Ungültige Adresse: \(host)")
|
||||
}
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
if let json {
|
||||
request.httpBody = json
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
}
|
||||
|
||||
let data: Data
|
||||
let response: URLResponse
|
||||
do {
|
||||
(data, response) = try await Self.session.data(for: request)
|
||||
} catch let error as URLError {
|
||||
throw CubeAPIError(message: Self.describe(error))
|
||||
}
|
||||
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw CubeAPIError(message: "Keine gültige Antwort vom Würfel")
|
||||
}
|
||||
guard (200..<300).contains(http.statusCode) else {
|
||||
let message = (try? JSONDecoder().decode([String: String].self, from: data))?["error"]
|
||||
throw CubeAPIError(message: message ?? "Fehler \(http.statusCode)")
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
private static func describe(_ error: URLError) -> String {
|
||||
switch error.code {
|
||||
case .notConnectedToInternet:
|
||||
return "Kein Netzwerk – ist das iPhone im WLAN und „Lokales Netzwerk“ für die App erlaubt?"
|
||||
case .cannotFindHost, .dnsLookupFailed:
|
||||
return "Würfel nicht gefunden – ist er eingeschaltet und im selben WLAN?"
|
||||
case .timedOut, .cannotConnectToHost, .networkConnectionLost:
|
||||
return "Würfel antwortet nicht"
|
||||
default:
|
||||
return error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// Hält den Zustand des Würfels und gleicht ihn regelmäßig mit der API ab.
|
||||
@MainActor @Observable
|
||||
final class CubeModel {
|
||||
/// Name oder IP-Adresse des Würfels, wird gespeichert.
|
||||
var host: String {
|
||||
didSet {
|
||||
UserDefaults.standard.set(host, forKey: "host")
|
||||
state = nil
|
||||
effects = []
|
||||
error = nil
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var state: CubeState?
|
||||
private(set) var effects: [CubeEffect] = []
|
||||
private(set) var error: String?
|
||||
|
||||
/// Wert des Helligkeitsreglers; folgt dem Würfel, solange nicht gezogen wird.
|
||||
var brightness: Double = 32
|
||||
var isDraggingBrightness = false
|
||||
|
||||
var isConnected: Bool { state != nil && error == nil }
|
||||
|
||||
private var api: CubeAPI { CubeAPI(host: host) }
|
||||
|
||||
init() {
|
||||
host = UserDefaults.standard.string(forKey: "host") ?? "cube.local"
|
||||
}
|
||||
|
||||
/// Fragt den Zustand alle 2 Sekunden ab, bis die Aufgabe abgebrochen wird.
|
||||
func poll() async {
|
||||
while !Task.isCancelled {
|
||||
await refresh()
|
||||
try? await Task.sleep(for: .seconds(2))
|
||||
}
|
||||
}
|
||||
|
||||
func refresh() async {
|
||||
do {
|
||||
if effects.isEmpty { effects = try await api.effects() }
|
||||
apply(try await api.state())
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func select(_ effect: CubeEffect) async {
|
||||
await update(CubeStatePatch(effect: effect.id))
|
||||
}
|
||||
|
||||
func setAuto(_ on: Bool) async {
|
||||
await update(CubeStatePatch(auto: on))
|
||||
}
|
||||
|
||||
func commitBrightness() async {
|
||||
await update(CubeStatePatch(brightness: Int(brightness)))
|
||||
}
|
||||
|
||||
func special(_ id: String) async {
|
||||
do {
|
||||
try await api.special(id)
|
||||
error = nil
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func update(_ patch: CubeStatePatch) async {
|
||||
do {
|
||||
apply(try await api.update(patch))
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func apply(_ newState: CubeState) {
|
||||
state = newState
|
||||
error = nil
|
||||
if !isDraggingBrightness { brightness = Double(newState.brightness) }
|
||||
}
|
||||
|
||||
/// Macht aus Eingaben wie "http://10.0.1.8/" ein "10.0.1.8".
|
||||
static func cleanHost(_ input: String) -> String {
|
||||
var host = input.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
for prefix in ["http://", "https://"] where host.lowercased().hasPrefix(prefix) {
|
||||
host.removeFirst(prefix.count)
|
||||
}
|
||||
while host.hasSuffix("/") { host.removeLast() }
|
||||
return host.isEmpty ? "cube.local" : host
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct CubeRemoteApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Löttest: alle 125 LEDs statisch in Regenbogenfarben, gedimmt.
|
||||
// Aufspielen mit: make test (Pin/LED-Typ wie in ../config.h)
|
||||
|
||||
#include <FastLED.h>
|
||||
|
||||
#define DATA_PIN 10
|
||||
#define NUM_LEDS 125
|
||||
|
||||
CRGB leds[NUM_LEDS];
|
||||
|
||||
void setup() {
|
||||
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
|
||||
FastLED.setBrightness(16);
|
||||
fill_rainbow(leds, NUM_LEDS, 0, 256 / NUM_LEDS);
|
||||
FastLED.show();
|
||||
}
|
||||
|
||||
void loop() {}
|
||||
@@ -0,0 +1,178 @@
|
||||
// WLAN und REST-API (JSON), erreichbar unter http://cube.local oder per IP.
|
||||
// Suchen und Verbinden laufen ohne Blockieren, die Animation läuft weiter.
|
||||
//
|
||||
// GET /api/state aktueller Zustand
|
||||
// PUT/PATCH /api/state ändern, alle Felder optional:
|
||||
// {"effect": "feuer", "auto": false, "brightness": 64}
|
||||
// GET /api/effects alle Effekte: [{"id": "gewitter", "name": "Gewitter", "music": false}, ...]
|
||||
// POST /api/specials/{id} Spezialeffekt auslösen: blitz, explosion, regenbogen
|
||||
// POST /api/lightning Blitz auslösen (wie /api/specials/blitz)
|
||||
//
|
||||
// Anfragen mit Body brauchen "Content-Type: application/json".
|
||||
// Fehler antworten mit 4xx und {"error": "..."}.
|
||||
|
||||
#include "cube.h"
|
||||
#include "secrets.h"
|
||||
#include <WiFi.h>
|
||||
#include <WebServer.h>
|
||||
#include <ESPmDNS.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <uri/UriBraces.h>
|
||||
|
||||
WebServer server(80);
|
||||
|
||||
enum WifiState { WIFI_IDLE, WIFI_SCANNING, WIFI_CONNECTING, WIFI_ONLINE };
|
||||
WifiState wifiState = WIFI_IDLE;
|
||||
uint32_t wifiSince = 0;
|
||||
|
||||
void sendJson(int code, const JsonDocument &doc) {
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
server.send(code, "application/json", out);
|
||||
}
|
||||
|
||||
void sendError(int code, const char *message) {
|
||||
JsonDocument doc;
|
||||
doc["error"] = message;
|
||||
sendJson(code, doc);
|
||||
}
|
||||
|
||||
void sendState() {
|
||||
JsonDocument doc;
|
||||
doc["effect"] = effectId(currentEffect());
|
||||
doc["auto"] = autoAdvance;
|
||||
doc["brightness"] = brightness;
|
||||
sendJson(200, doc);
|
||||
}
|
||||
|
||||
void sendEffects() {
|
||||
JsonDocument doc;
|
||||
for (uint8_t i = 0; i < numEffects(); i++) {
|
||||
JsonObject e = doc.add<JsonObject>();
|
||||
e["id"] = effectId(i);
|
||||
e["name"] = effectName(i);
|
||||
e["music"] = effectIsMusic(i);
|
||||
}
|
||||
sendJson(200, doc);
|
||||
}
|
||||
|
||||
int findEffect(const char *id) {
|
||||
for (uint8_t i = 0; i < numEffects(); i++)
|
||||
if (strcmp(id, effectId(i)) == 0) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Erst alles prüfen, dann übernehmen: eine fehlerhafte Anfrage ändert nichts.
|
||||
void updateState() {
|
||||
// Ohne "Content-Type: application/json" zerlegt der Webserver den Body als Formular
|
||||
if (!server.hasArg("plain")) return sendError(415, "Body als JSON mit Content-Type: application/json senden");
|
||||
JsonDocument body;
|
||||
if (deserializeJson(body, server.arg("plain")) || !body.is<JsonObject>())
|
||||
return sendError(400, "JSON-Objekt erwartet");
|
||||
|
||||
JsonVariant effect = body["effect"], autoOn = body["auto"], level = body["brightness"];
|
||||
int index = -1;
|
||||
if (!effect.isNull()) {
|
||||
if (!effect.is<const char *>()) return sendError(400, "effect muss eine Effekt-id sein, siehe /api/effects");
|
||||
index = findEffect(effect.as<const char *>());
|
||||
if (index < 0) return sendError(400, "unbekannter Effekt, siehe /api/effects");
|
||||
}
|
||||
if (!autoOn.isNull() && !autoOn.is<bool>()) return sendError(400, "auto muss true oder false sein");
|
||||
if (!level.isNull() && !(level.is<int>() && level.as<int>() >= 0 && level.as<int>() <= 255))
|
||||
return sendError(400, "brightness muss eine ganze Zahl von 0 bis 255 sein");
|
||||
|
||||
if (index >= 0) selectEffect(index);
|
||||
if (!autoOn.isNull()) autoAdvance = autoOn.as<bool>();
|
||||
if (!level.isNull()) setBaseBrightness(level.as<int>());
|
||||
sendState();
|
||||
}
|
||||
|
||||
void webBegin() {
|
||||
WiFi.setHostname("cube");
|
||||
WiFi.mode(WIFI_STA);
|
||||
#if CONFIG_IDF_TARGET_ESP32C3
|
||||
WiFi.setTxPower(WIFI_POWER_8_5dBm); // viele C3-SuperMini verbinden sich sonst schlecht (Antenne)
|
||||
#endif
|
||||
|
||||
server.on("/api/state", HTTP_GET, sendState);
|
||||
server.on("/api/state", HTTP_PUT, updateState);
|
||||
server.on("/api/state", HTTP_PATCH, updateState);
|
||||
server.on("/api/effects", HTTP_GET, sendEffects);
|
||||
server.on("/api/lightning", HTTP_POST, [] {
|
||||
triggerLightning(millis());
|
||||
server.send(204);
|
||||
});
|
||||
server.on(UriBraces("/api/specials/{}"), HTTP_POST, [] {
|
||||
String id = server.pathArg(0);
|
||||
if (id == "blitz") triggerLightning(millis());
|
||||
else if (id == "explosion") triggerExplosion(millis());
|
||||
else if (id == "regenbogen") triggerRainbowWave(millis());
|
||||
else return sendError(404, "unbekannter Spezialeffekt: blitz, explosion oder regenbogen");
|
||||
server.send(204);
|
||||
});
|
||||
server.onNotFound([] { sendError(404, "unbekannter Pfad oder Methode"); });
|
||||
server.begin();
|
||||
WiFi.onEvent([](WiFiEvent_t e, WiFiEventInfo_t info) {
|
||||
if (e == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) Serial.printf("WLAN: getrennt (Grund %u)\n", info.wifi_sta_disconnected.reason);
|
||||
});
|
||||
}
|
||||
|
||||
void webUpdate(uint32_t now) {
|
||||
switch (wifiState) {
|
||||
case WIFI_IDLE: // (erneut) nach Netzen suchen, im Hintergrund
|
||||
if (now - wifiSince >= 5000 || wifiSince == 0) {
|
||||
WiFi.scanNetworks(true);
|
||||
wifiState = WIFI_SCANNING;
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_SCANNING: {
|
||||
int16_t n = WiFi.scanComplete();
|
||||
if (n == WIFI_SCAN_RUNNING) break;
|
||||
int8_t best = -1;
|
||||
int32_t bestRssi = -1000;
|
||||
for (int16_t i = 0; i < n; i++)
|
||||
for (uint8_t k = 0; k < sizeof(WLANS) / sizeof(WLANS[0]); k++)
|
||||
if (WiFi.SSID(i) == WLANS[k].ssid && WiFi.RSSI(i) > bestRssi) {
|
||||
best = k;
|
||||
bestRssi = WiFi.RSSI(i);
|
||||
}
|
||||
WiFi.scanDelete();
|
||||
wifiSince = now;
|
||||
if (best < 0) {
|
||||
wifiState = WIFI_IDLE;
|
||||
break;
|
||||
}
|
||||
Serial.printf("WLAN: verbinde mit %s (%ld dBm)\n", WLANS[best].ssid, (long)bestRssi);
|
||||
WiFi.begin(WLANS[best].ssid, WLANS[best].pass);
|
||||
wifiState = WIFI_CONNECTING;
|
||||
break;
|
||||
}
|
||||
|
||||
case WIFI_CONNECTING:
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
static bool mdns = false;
|
||||
if (!mdns && MDNS.begin("cube")) {
|
||||
MDNS.addService("http", "tcp", 80);
|
||||
mdns = true;
|
||||
}
|
||||
Serial.printf("WLAN: verbunden, REST-API unter http://%s/api/state oder http://cube.local/api/state\n", WiFi.localIP().toString().c_str());
|
||||
wifiState = WIFI_ONLINE;
|
||||
} else if (now - wifiSince > 15000) {
|
||||
Serial.println("WLAN: Verbindung fehlgeschlagen, suche erneut");
|
||||
WiFi.disconnect();
|
||||
wifiSince = now;
|
||||
wifiState = WIFI_IDLE;
|
||||
}
|
||||
break;
|
||||
|
||||
case WIFI_ONLINE:
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
Serial.println("WLAN: Verbindung verloren");
|
||||
wifiSince = now;
|
||||
wifiState = WIFI_CONNECTING; // automatische Wiederverbindung abwarten, sonst neu suchen
|
||||
}
|
||||
server.handleClient();
|
||||
break;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user