Add NPN buzzer projects
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
#define PIN_BUZZER_SWITCH 14
|
||||
#define PIN_BUTTON 21
|
||||
#define PWM_CHANNEL 0
|
||||
|
||||
void setup() {
|
||||
pinMode(PIN_BUZZER_SWITCH, OUTPUT);
|
||||
pinMode(PIN_BUTTON, INPUT);
|
||||
// Tutorial had a bug here. Needs to be freq=1000, not freq=1.
|
||||
ledcAttachChannel(PIN_BUZZER_SWITCH, 1000, 10, PWM_CHANNEL);
|
||||
ledcWriteTone(PIN_BUZZER_SWITCH, 2000);
|
||||
delay(300);
|
||||
}
|
||||
|
||||
void alarm() {
|
||||
float sine;
|
||||
int tone;
|
||||
for ( int i = 0; i < 360 ; i += 10 ) {
|
||||
sine = sin(i * (PI / 180));
|
||||
tone = 2000 + sine * 500;
|
||||
ledcWriteTone(PIN_BUZZER_SWITCH, tone);
|
||||
delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if ( digitalRead(PIN_BUTTON) == LOW ) {
|
||||
alarm();
|
||||
} else {
|
||||
ledcWriteTone(PIN_BUZZER_SWITCH, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
#define PIN_BUZZER_SWITCH 14
|
||||
#define PIN_BUTTON 21
|
||||
|
||||
void setup() {
|
||||
pinMode(PIN_BUZZER_SWITCH, OUTPUT);
|
||||
pinMode(PIN_BUTTON, INPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if ( digitalRead(PIN_BUTTON) == LOW ) {
|
||||
digitalWrite(PIN_BUZZER_SWITCH, HIGH);
|
||||
} else {
|
||||
digitalWrite(PIN_BUZZER_SWITCH, LOW);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ if (digitalRead(PIN_BUTTON) == LOW) {
|
||||
// do something with the pin
|
||||
```
|
||||
|
||||
... This is really wasteful. I paid good money for those CPU cycles, and on embedded hardware we don't have a lot of them to go around. (The ESP32-S3 has an Xtensa dual-core 32-bit LX7 running up to 240Mhz - stunning when you think about the price and size of the package, but still, not enough to be wasteful.) I improved that by using a timer in a function that yields time back to the CPU while it's waiting to verify that the button is debounced.
|
||||
... This is not great. First, we are wasting CPU cycles (The ESP32-S3 has an Xtensa dual-core 32-bit LX7 running up to 240Mhz - stunning when you think about the price and size of the package, but still, not enough to be wasteful). But on the ESP32-S3 in particular, the solution package as a whole isn't losing those cycles - it runs Arduino on top of an RTOS, so `delay()` is actually yielding back to the RTOS scheduler so that things like bluetooth and wifi stacks can continue. But *our* program is fully blocked here. If I want to scan additional buttons, or perform some other task, we're locked in here. So I improved that by using a timer in a function that yields time back to the CPU while it's waiting to verify that the button is debounced.
|
||||
|
||||
```arduino
|
||||
void checkButtonPressed(void) {
|
||||
|
||||
Reference in New Issue
Block a user