📜 ⬆️ ⬇️

New Year's greetings from the robot

Already started the 31st, very soon the New Year. Still do not want to sleep, I want to feel the holiday. And then the look falls on my dusty Arduino-robot, to which hands have not reached for a couple of months. What new year robot can do? Of course, play jingle bells! Two hours of effort, struggle with the lack of a musical ear, and here it is - the result:

Happy New Year!


')
Under the cut code, and a few comments



#pragma once void beep(int tone, int duration) { for (long i = 0; i < duration * 1000L; i += tone * 2) { digitalWrite(BEEPER, HIGH); delayMicroseconds(tone); digitalWrite(BEEPER, LOW); delayMicroseconds(tone); } } void play_note(char note, int duration) { char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' }; int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 }; for (int i = 0; i < 8; i++) { if (names[i] == note) { beep(tones[i], duration); } } } void jingle_bells() { char sounds[] = "b1b1b2b1b1b2b1d1g1a1b4c1c1c1c1c1b1b1b1b1a1a1b1a2d2b1b1b2b1b1b2b1d1g1a1b4c1c1c1c1b1b1b1d1d1c1a1g6"; const int length = sizeof(sounds) / 2; char* notes = new char[length]; int* beats = new int[length]; for (int i = 0; i < length; ++i) { notes[i] = sounds[2 * i]; beats[i] = atoi(&sounds[2 * i + 1]); } static const int tempo = 300; for (int i = 0; i < length; i++) { play_note(notes[i], beats[i] * tempo); delay(tempo / 2); } delete[] notes; delete[] beats; } 


I ask you not to judge strictly, the code was written on the knee. I understand that it was possible to do much more beautiful and more efficient.

The sound format is such - odd symbols - notes, even - their duration.
BEEPER is the arduino contact number to which the piezo squeaker is connected.
Before using jingle_bells, it is worth making a contact in OUTPUT (for example, in the setup function): pinMode (BEEPER, OUTPUT);

UPD: In the comments we decided that it sounds more like when

char sounds [] = e e2e2e3c1e2e2e3c1e2g2c3d1e8f2f2f3f1f2e2e2e1e1e2d2d2e2d4g3c1e2e2e3c1e2e2e3c1e2g2c3d1e;
and
static const int tempo = 130;

Source: https://habr.com/ru/post/207912/


All Articles