Gå til innhold

21. desember

I dag kobler vi opp litt flere knapper sammen med den passive buzzeren og lager oss et lite mini piano.

buzzer + → D15
buzzer - → jord (blå linje)
b1 → D4
b2 → D22
b3 → D18
b4 → D19
b1/b2/b3/b4 → rød linje

https://gist.github.com/senikk/44b1dfc0c5033ab24985ae063c957a4f

#include <Bounce2.h>
int b1Pin = 4;
int b2Pin = 22;
int b3Pin = 18;
int b4Pin = 19;
int buzzerPin = 15;
// Toner
#define NOTE_C4 261
#define NOTE_C4S 277 // C♯4
#define NOTE_D4 294
#define NOTE_D4S 311 // D♯4
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_F4S 370 // F♯4
#define NOTE_G4 392
#define NOTE_G4S 415 // G♯4
#define NOTE_A4 440
#define NOTE_A4S 466 // A♯4
#define NOTE_B4 466
#define NOTE_C5 523
// PWM-kanal for ESP32
int buzzerChannel = 0;
Bounce b1 = Bounce();
Bounce b2 = Bounce();
Bounce b3 = Bounce();
Bounce b4 = Bounce();
void setup() {
ledcAttachChannel(buzzerPin, 2000, 8, buzzerChannel);
pinMode(b1Pin, INPUT_PULLDOWN);
pinMode(b2Pin, INPUT_PULLDOWN);
pinMode(b3Pin, INPUT_PULLDOWN);
pinMode(b4Pin, INPUT_PULLDOWN);
b1.attach(b1Pin);
b1.interval(50);
b2.attach(b2Pin);
b2.interval(50);
b3.attach(b3Pin);
b3.interval(50);
b4.attach(b4Pin);
b4.interval(50);
}
void loop() {
b1.update();
b2.update();
b3.update();
b4.update();
if (b1.rose()) {
tone(buzzerPin, NOTE_C4, 250);
}
if (b2.rose()) {
tone(buzzerPin, NOTE_C4S, 250);
}
if (b3.rose()) {
tone(buzzerPin, NOTE_D4, 250);
}
if (b4.rose()) {
tone(buzzerPin, NOTE_D4S, 250);
}
}
void tone(int pin, int frequency, int duration) {
ledcWriteTone(pin, frequency); // Start tone på ønsket frekvens
delay(duration); // Vent i den ønskede varigheten
ledcWriteTone(pin, 0); // Stopp tonen
}
view raw 21.12.piano.ino hosted with ❤ by GitHub