Сейчас ваша корзина пуста!
Buzzer
Töö kirjeldus:
Looda Pieso muusikat mängida
Komponendid:
Pieso
Juhtmed 4 tk
Programm:
// Этот скетч использует зуммер для воспроизведения мелодий.
// Команда Arduino tone() будет издавать звуки определенной частоты.
// Мы создаем функцию, которая сопоставляет символ нотной гаммы
// ("До-ре-ми-фа...До") соответствующей частоте из следующей таблицы:
// note frequency
// c 262 Hz
// d 294 Hz
// e 330 Hz
// f 349 Hz
// g 392 Hz
// a 440 Hz
// b 494 Hz
// C 523 Hz
const int buzzerPin = 9;
// Мы создали массив с нотами, которые хотим воспроизвести, измените эти значения, чтобы создать свои мелодии!
// Длина должна равняться общему количеству нот и пауз
const int songLength = 18;
// Обозначение нот представляет собой массив из текстовых символов,
// соответствующим нотам в песне. Пробел означает паузу (пустую ноту)
char notes[] = "cdfda ag cdfdg gf "; // пробелы означают паузы
// Ритм задается массивом из длительности нот и пауз между ними.
// "1" - четвертная нота, "2" - половинная, и т.д.
// Не забывайте, что пробелы должны быть тоже определенной длинны.
int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};
// "tempo" это скорость проигрывания мелодии.
// Для того, чтобы мелодия проигрывалась быстрее, вы
// должны уменьшить следующее значение.
int tempo = 150;
void setup()
{
pinMode(buzzerPin, OUTPUT);
}
void loop()
{
int i, duration;
for (i = 0; i < songLength; i++) // пошаговое воспроизведение из массива
{
duration = beats[i] * tempo; // длительность нот/пауз в ms
if (notes[i] == ' ') // если нота отсутствует?
{
delay(duration); // тогда не большая пауза
}
else // в противном случае играть
{
tone(buzzerPin, frequency(notes[i]), duration);
delay(duration); // ждать пока проигрывается
}
delay(tempo/10); // маленькая пауза между нотами
}
// Мы хотим, чтобы мелодия проиграла всего один раз, так что здесь остановимся окончательно:
while(true){}
// Если же вы хотите, чтобы мелодия играть снова и снова, Удалить вышеуказанное заявление
}
int frequency(char note)
{
// Эта функция принимает символ ноты (a-g), и возвращает
// частоту в Гц для функции tone().
int i;
const int numNotes = 8; // количество хранимых нот
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};
// Теперь мы будем искать во всем массиве, символ ноты и если находим, возвращаем частоту для этой ноты.
for (i = 0; i < numNotes; i++) // пошаговый перебор нот
{
if (names[i] == note) // если находим
{
return(frequencies[i]); // возвращаем частоту
}
}
return(0); // Поиск символа не дал результата? Но, необходимо вернуть какое-то значение, так вернем 0.
}

Meloodia mängija
Skeem:

Uuritud funktsioonid
Funktsioon: frequency(char note)
- Eesmärk: Teisendab noodi tähemärgi (nt
'c'
,'d'
,'e'
) vastavaks helisageduseks hertsides. - Kuidas töötab: Võrdleb sisestatud tähemärki massiivis
names[]
olevate nootidega ning tagastab vastava sageduse massiivistfrequencies[]
.
Funktsioon: startPlaying(const char* notes, int* beats, int length)
- Eesmärk: Käivitab uue loo mängimise.
- Kuidas töötab: Salvestab parajasti mängitava loo info (noodid, rütmid, pikkus) ja alustab esimest nooti.
Funktsioon: updateMelody()
- Eesmärk: Kontrollib, kas on aeg mängida järgmine noot.
- Kuidas töötab: Arvutab aja millis()-ega ja kui piisavalt aega on möödunud, liigutab järgmise noodi juurde.
Funktsioon: playNote(char note, int beat)
- Eesmärk: Mängib ühe noodi (või pausi).
- Kuidas töötab: Kui noot on
' '
, teebnoTone()
, muidu arvutab sageduse ja mängib sedatone()
abil.
Funktsioon: frequency(char note, int octaveOffset)
- Eesmärk: Arvutab helisageduse koos oktavi muutmise võimalusega.
- Kuidas töötab: Leiab baassageduse ja nihutab seda bittide kaupa (vasakule või paremale), et muuta oktavit.
Töö kirjeldus
Luua nutikas miniatuurne alarm süsteem, mis kogub andmeid erinevatelt sensoritelt, kuvab neid LCD-ekraanil, ning annab auditiivseid signaale buzzeri abil sõltuvalt olukorrast. Süsteemi saab aktiveerida ja deaktiveerida lüliti või potentsiomeetri abil. Tavatingimustes mängib taustaks muusika, kuid ohu korral katkeb muusika ning buzzer annab märguande.
Kasutatud komponeendid
- LCD-ekraan (16×2)
- Valguse andur (fototakisti)
- Juhtmed (22 tk)
- Takisti (3tk: 2tk 220 ohm, 1tk 10k ohm)
- Potentsiomeeter (250 kOhm)
- Buzzer
- Arduino Uno plaat
Kood:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 2, 3, 4, 5);
// Declare string literals as constant pointers
const char* myStrings[] = {"stillgrey", "back2u", "northwinds"};
const int buzzerPin = 9;
const int alarmSwitchPin = A0;
const int ldrPin = A1;
const int sensorPin = A5;
int alarmMode = 0;
int lightThreshold = 300;
const int songLengthStillGrey = 8;
const int songLengthBack2U = 16;
const int songLengthNorthWinds = 16;
const char notesStillGrey[] = "g f e d c b a g ";
int beatsStillGrey[] = {2, 1, 1, 2, 1, 1, 2, 1};
const char notesBack2U[] = "b d f a b a f d b d f a b a f d";
int beatsBack2U[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
const char notesNorthWinds[] = "e a g f d e c b a g f e d c b a";
int beatsNorthWinds[] = {2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2};
int tempo = 75;
const char alarmNotes[] = "c c c c ";
int alarmBeats[] = {4, 4, 4, 4};
const int alarmLength = 4;
// Non-blocking melody playback variables
unsigned long noteStartTime = 0;
int currentNoteIndex = 0;
int currentSongLength = 0;
const char* currentNotes = nullptr;
int* currentBeats = nullptr;
bool isPlaying = false;
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(alarmSwitchPin, INPUT);
pinMode(ldrPin, INPUT);
pinMode(sensorPin, INPUT);
lcd.begin(16, 2);
Serial.begin(9600);
}
void loop() {
int ldrValue = analogRead(ldrPin);
int alarmSwitchValue = analogRead(alarmSwitchPin);
int sensorValue = analogRead(sensorPin);
Serial.print("LDR: ");
Serial.print(ldrValue);
Serial.print(" Potentiometer: ");
Serial.print(alarmSwitchValue);
Serial.print(" Sensor: ");
Serial.println(sensorValue);
// Determine alarmMode based on the switch and light
alarmMode = (alarmSwitchValue > 512) ? 1 : 0;
if (ldrValue < lightThreshold) {
alarmMode = 1;
} else {
alarmMode = 0;
}
lcd.setCursor(0, 1);
lcd.print("Light: ");
lcd.print(ldrValue);
lcd.print(" ");
if (alarmMode == 1) {
lcd.setCursor(0, 0);
lcd.print("ALARM! no dnb :(");
// If alarm is not playing, start playing
if (!isPlaying || currentNotes != alarmNotes) {
startPlaying(alarmNotes, alarmBeats, alarmLength);
}
} else {
int mappedValue = map(sensorValue, 0, 1023, 1, 3);
if (mappedValue == 1) {
lcd.setCursor(0, 0);
lcd.print("stillgrey ");
if (!isPlaying || currentNotes != notesStillGrey) {
startPlaying(notesStillGrey, beatsStillGrey, songLengthStillGrey);
}
} else if (mappedValue == 2) {
lcd.setCursor(0, 0);
lcd.print("back2u ");
if (!isPlaying || currentNotes != notesBack2U) {
startPlaying(notesBack2U, beatsBack2U, songLengthBack2U);
}
} else if (mappedValue == 3) {
lcd.setCursor(0, 0);
lcd.print("northwinds ");
if (!isPlaying || currentNotes != notesNorthWinds) {
startPlaying(notesNorthWinds, beatsNorthWinds, songLengthNorthWinds);
}
} else {
lcd.setCursor(0, 0);
lcd.print("No music ");
noTone(buzzerPin);
isPlaying = false;
}
}
updateMelody();
}
// Start playing a new melody
void startPlaying(const char* notes, int* beats, int length) {
currentNotes = notes;
currentBeats = beats;
currentSongLength = length;
currentNoteIndex = 0;
noteStartTime = millis();
isPlaying = true;
playNote(currentNotes[currentNoteIndex], currentBeats[currentNoteIndex]);
}
// Update the melody playback in a non-blocking way
void updateMelody() {
if (!isPlaying) return;
unsigned long currentTime = millis();
int noteDuration = currentBeats[currentNoteIndex] * tempo;
if (currentTime - noteStartTime >= (unsigned long)noteDuration) {
// Move to the next note
currentNoteIndex++;
if (currentNoteIndex >= currentSongLength) {
currentNoteIndex = 0; // Loop the melody
}
noteStartTime = currentTime;
playNote(currentNotes[currentNoteIndex], currentBeats[currentNoteIndex]);
}
}
// Play a single note
void playNote(char note, int beat) {
if (note == ' ') {
noTone(buzzerPin);
} else {
tone(buzzerPin, frequency(note), beat * tempo);
}
}
// Note frequencies
int frequency(char note) {
const int numNotes = 8;
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};
for (int i = 0; i < numNotes; i++) {
if (names[i] == note) return frequencies[i];
}
return 0;
}