Arduino tone generator

Звук на Arduino

В этой статье я рассмотрю примеры работы со звуков на контроллере Arduino

Данный пример я планирую использовать в системе звукового оповещения домашней метеостанции, чтобы своевременно реагировать на критические значения измеряемых параметров.

Подключение пьезоизлучателя к Arduino

На самом деле подключение очень простое:

  • 1 вывод пьезоизлучателя подключаем к 9 дискретному пину Arduino
  • 2 вывод пьезоизлучателя подключаем к GND Arduino

Генерация звуков на Arduino

Для генерации звуков на Arduino существует функция tone()

Функция tone()

Генерирует сигнал прямоугольной формы с заданной частотой. Длительность может быть задана параметром. Без указания длительности сигнал генерируется пока не будет вызвана функция noTone(). К порту Arduino может быть подключен к пьезо или другой высокоомный динамик для воспроизведения сигнала. Одновременно может воспроизводиться только один сигнал.

Синтаксис функции tone()

  • tone(pin, частота)
  • tone(pin, частота, длительность)

Пример использования функции tone()

const int SoundPin = 9; // Пин подключения пьезоизлучателя – 9 дискретный
int DelaySound = 1000; // Пауза 1 секунда

void loop()
<
// Пример использования tone()
//tone(pin, частота)
tone(SoundPin, 1915); // Воспроизводим сигнал с частотой 1915 Гц
delay(DelaySound); // Пауза 1 секунда (1000 миллисекунд – значение переменной DelaySound ) – длительность воспроизведения сигнала

tone(SoundPin, 1700);
delay(DelaySound);

tone(SoundPin, 1519);
delay(DelaySound);

tone(SoundPin, 1432);
delay(DelaySound);

tone(SoundPin, 1275);
delay(DelaySound);

tone(SoundPin, 1136);
delay(DelaySound);

tone(SoundPin, 1014);
delay(DelaySound);

Источник

Звук в ардуино. Урок 7. Ардуино

Генерировать звук в Ардуино можно многими способами. Самый простой — это использовать функцию tone(). Поэтому, прежде всего, посмотрим как работает эта функция.

Генерируем звук на ардуино

Также существуют дополнительные платы, которые можно подключить к Ардуино с помощью перемычек. Но о них мы поговорим в дугой раз.

Сейчас посмотрим, как можно запрограммировать Ардуино для вывода звука. Для этого просто используем небольшой динамик.

В предыдущем уроке мы научились использовать последовательный порт для ввода информации и управления подключенным оборудованием. Сейчас попробуем использовать его для вывода звука. Так что, если вы забыли или пропустили предыдущий урок, пожалуйста, посмотрите его.

Для выполнения этого урока нам понадобятся

  • Ардуино Uno
  • Макетная плата
  • Перемычки
  • 1 резистор номиналом 150 Ом
  • Потенциометр 10 кОм
  • Динамик 8 Ом
  • Кабель USB

Что такое звук

Во-первых, несколько слов о звуке. Что такое звук, какими свойствами он обладает, как люди воспринимают звук?

Прежде всего, мы знаем, что звук распространяется по воздуху в виде волны. Работа звуковых колонок, удар в барабан или колокол создают вибрацию воздуха. Таким образом, частицы воздуха за счет колебаний передают энергию все дальше и дальше. В результате волна давления передается от источника к вашей барабанной перепонке через реакцию вибрирующих частиц.

Звук в ардуино управляется двумя свойствами этих частиц. Частотой и амплитудой. Частота — это скорость вибрации, а амплитуда — это размах колебаний.

В физическом смысле звуки с большой амплитудой громче, чем с малой. Тон высокочастотных звуков выше, а низкочастотных, как видим на графике, — ниже.

Частота и амплитуда звуковой волны

Как работает динамик

В предыдущих уроках мы рассматривали как работают электродвигатели. Двигатели используют электромагниты для превращения электрической энергии в механическую.

Динамики работают так же для создания звука.

Схема громкоговорителя

Перед постоянным магнитом размещена звуковая катушка. Когда вы подаете на нее электрический сигнал, переменный ток создает магнитное поле, звуковая катушка перемещает диффузор вверх и вниз. Из-за вибрации диффузора из динамика раздается звук.

Функция tone()

Для работы со звуком в Ардуино предусмотрена функция tone(). Она создает меандр с заданной частотой и выводит его на выбранный контакт.

Функция tone() взаимодействует с одним из аппаратных таймеров контроллера ATmega, так что ее можно вызвать и продолжать работать с Ардуино, а звук будет играть в фоновом режиме.

Программа и схема

На этом теоретическая часть закончена. Так что, давайте соберем небольшую схему и попробуем запрограммировать воспроизведение звука.

Сегодня мы хотим передавать на динамик данные из последовательного порта. А также, играть уже готовую мелодию.

Принципиальная схема подключения динамика к ардуино

Подключим динамик к ардуино последовательно с резистором и с потенциометром, таким образом мы сможем регулировать громкость звука.

Проверить работоспособность схемы очень просто. Используем функцию tone() и напишем простую программу чтобы продемонстрировать ее работу.

Поскольку функция tone() принимает несколько параметров, мы можем указать длительность сигнала. Поэтому будем использовать оператор setup() а не loop().

В результате выполнения этого кода, мы услышим высокий звук длительностью 1 секунду.

Ардуино и динамик

Теперь, если мы хотим использовать последовательный порт и принимать команды из него, используем функцию Serial.parseInt(). Для этого, будем считывать число из порта и передавать его как частоту в функцию tone().

Не забудем ограничить максимальные и минимальные значения, а так же включить последовательный порт в функции setup().

Полный текст программы

Заключение

Сегодня мы рассмотрели еще один аспект работы с Ардуино. А именно звук в Ардуино. Более того, в будущем мы будем улучшать схему и программу этого урока. А в следующий раз подключим к схеме несколько кнопок и попробуем сыграть настоящую мелодию.

Источник

Arduino tone generator

by admin · Published March 27, 2017 · Updated December 2, 2020

This method is to generate a simple square wave tone using Arduino.

Connect the output pin 9 to a buzzer or speaker.

Code 1

In the above program, the tone() function generates a square wave of frequency 260HZ with a duty cycle of 50%. Tone() function can generate only square waves of fixed 50% duty cycle.

The output pin and frequency can be varied by changing the values in the tone function.

tone (pin, frequency)

The frequency value should be between minimum 31HZ and maximum 65535HZ; the minimum and maximum frequency values that can be produced by the AVR boards.

An optional duration value can be added if the tone required only to ON for a short period of time.

tone (pin, frequency, duration)

Code 2

Here the tone will be ON only for 500ms and OFFs, then repeats function after a 1s delay in OFF state which generates a beep-beep sound; half-second beep with a one-second gap between each beep.

If the function tone is used without a duration value then the function noTone() should be called to turn OFF the tone. Otherwise, it continues the tone generation.

Code 3

Arduino half-hour Beeping Timer

The Arduino beeping timer generates a beep tone with an interval of 30 minutes between each beeping sound. The beep sound has a duration of 3 seconds and a frequency of 1500Hz. Instead of the delay function, the code uses millis ( ) function to obtain the time. So between each tone, additional codes can be added to execute in the 30 minutes time interval.

Источник

bhagman/Tone

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is an Arduino Library to produce square-wave of the specified frequency (and 50% duty cycle) on any Arduino pin.

A duration can optionally be specified, otherwise the wave continues until stop() is called.

The pin can be connected to a piezo buzzer or other speaker to play tones.

Be sure to try out the RTTTL (RingTone Text Transfer Language) example!

Arduino Core Version

A simplified version of the Tone library has been incorporated into the Arduino core since 0018. It only provides a single tone (since only one timer is used). You can find the core documentation here.

Check out the tutorial by Tom Igoe at NYU’s Interactive Telecommunications Program (ITP). It demonstrates how to use the core tone() and noTone() commands.

Do not connect the pin directly to some sort of audio input. The voltage is considerably higher than a standard line level voltages, and can damage sound card inputs, etc. You could use a voltage divider to bring the voltage down, but you have been warned.

You MUST have a resistor in line with the speaker, or you WILL damage your controller.

Download and Installation

Unzip the folder and rename it to Tone , then move it to your arduinosketchfolder/libraries/ folder.

  • Just connect the digital pin to a speaker (with a resistor — say 1K — in line), and the other side of the speaker to ground (GND).
  • You can use a potentiometer to control the volume. Use a 10K Ohm potentiometer (variable resistor) in line with the 1K Ohm resistor connected to the speaker.

    Using this library will affect usage of the PWM outputs, so be aware.

    Also, although it’s the last timer to be allocated, timer 0 (which is used for millis() among other things) will be affected if used.

    • begin( pin ) — prepares a pin for playing a tone.
    • isPlaying() — returns true if tone is playing, false if not.
    • play( frequency [, duration ]) — play a tone.
      • frequency is in Hertz, and the duration is in milliseconds.
      • duration is optional. If duration is not given, tone will play continuously until stop() is called.
      • play() is non-blocking. Once called, play() will return immediately. If duration is given, the tone will play for that amount of time, and then stop automatically.
    • stop() — stop playing a tone.

    Below is a list of constant values of frequencies for notes. (These are included in the library).

    Constant Name Frequency (Hz)
    NOTE_B0 31
    NOTE_C1 33
    NOTE_CS1 35
    NOTE_D1 37
    NOTE_DS1 39
    NOTE_E1 41
    NOTE_F1 44
    NOTE_FS1 46
    NOTE_G1 49
    NOTE_GS1 52
    NOTE_A1 55
    NOTE_AS1 58
    NOTE_B1 62
    NOTE_C2 65
    NOTE_CS2 69
    NOTE_D2 73
    NOTE_DS2 78
    NOTE_E2 82
    NOTE_F2 87
    NOTE_FS2 93
    NOTE_G2 98
    NOTE_GS2 104
    NOTE_A2 110
    NOTE_AS2 117
    NOTE_B2 123
    NOTE_C3 131
    NOTE_CS3 139
    NOTE_D3 147
    NOTE_DS3 156
    NOTE_E3 165
    NOTE_F3 175
    NOTE_FS3 185
    NOTE_G3 196
    NOTE_GS3 208
    NOTE_A3 220
    NOTE_AS3 233
    NOTE_B3 247
    NOTE_C4 262
    NOTE_CS4 277
    NOTE_D4 294
    NOTE_DS4 311
    NOTE_E4 330
    NOTE_F4 349
    NOTE_FS4 370
    NOTE_G4 392
    NOTE_GS4 415
    NOTE_A4 440
    NOTE_AS4 466
    NOTE_B4 494
    NOTE_C5 523
    NOTE_CS5 554
    NOTE_D5 587
    NOTE_DS5 622
    NOTE_E5 659
    NOTE_F5 698
    NOTE_FS5 740
    NOTE_G5 784
    NOTE_GS5 831
    NOTE_A5 880
    NOTE_AS5 932
    NOTE_B5 988
    NOTE_C6 1047
    NOTE_CS6 1109
    NOTE_D6 1175
    NOTE_DS6 1245
    NOTE_E6 1319
    NOTE_F6 1397
    NOTE_FS6 1480
    NOTE_G6 1568
    NOTE_GS6 1661
    NOTE_A6 1760
    NOTE_AS6 1865
    NOTE_B6 1976
    NOTE_C7 2093
    NOTE_CS7 2217
    NOTE_D7 2349
    NOTE_DS7 2489
    NOTE_E7 2637
    NOTE_F7 2794
    NOTE_FS7 2960
    NOTE_G7 3136
    NOTE_GS7 3322
    NOTE_A7 3520
    NOTE_AS7 3729
    NOTE_B7 3951
    NOTE_C8 4186
    NOTE_CS8 4435
    NOTE_D8 4699
    NOTE_DS8 4978

    Play a 440 Hz — musical note of 4^th^ octave A — on pin 13:

    The library uses the hardware timers on the microcontroller to generate square-wave tones in the audible range.

    You can output the tones on any pin (arbitrary). The number of tones that can be played simultaneously depends on the number of hardware timers (with CTC capability) available on the microcontroller.

    • ATmega8: 2 (timers 2, and 1)
    • ATmega168/328: 3 (timers 2, 1, and 0)
    • ATmega1280: 6 (timers 2, 3, 4, 5, 1, 0)

    The timer order given above is the order in which the timers are allocated. Timer 0 is a sensitive timer on the Arduino since it provides millis() and PWM functionality.

    The range of frequencies that can be produced depends on the microcontroller clock frequency and the timer which is being used:

    MCU clock 8 bit timer Flow 16 bit timer Flow Fhigh
    8 MHz 16 Hz 1 Hz (1/16 Hz) 4 MHz
    16 MHz 31 Hz 1 Hz (1/8 Hz) 8 MHz

    Although Fhigh can go as high as 8 MHz, the human hearing range is typically as high as 20 kHz.

    Tone accuracy is dependent on the timer prescalar. Frequency quantization occurs as the frequencies increase per prescalar.

    If you used a 16 bit timer (e.g. timer 1, or timers 3,4,5 on ‘1280), you could generate «tones» down to 1/8 Hz (one cycle every 8 seconds), although the library only accepts integers for frequency.

    After all is said and done, because play() only accepts unsigned integers for frequency, the maximum frequency that can be produced is 65535 Hz — which, after rounding, results in a 65573.77 Hz «tone» on a 16 MHz part. Even if play accepted larger values for frequency, you couldn’t achieve better than around 80KHz with the Tone library because the pin toggling is done in software. Each toggle, in software, requires AT LEAST 50+ cycles.

    Projects/Examples Using Tone Library and Wiring Framework Version of tone()

    Источник

Adblock
detector