-
Notifications
You must be signed in to change notification settings - Fork 0
/
NewToneLib.cpp
31 lines (27 loc) · 954 Bytes
/
NewToneLib.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "NewToneLib.h"
MyTone::MyTone(bool displayMsg) {
// Anything you need when instantiating your object goes here
//_msg = displayMsg;
}
void MyTone::tone(int pin, int freq, unsigned long duration)
{
//freq in Hz; min = 31Hz; max = 333Hz
//duration in milliseconds; max = 4290000ms
//duty cycle is 50%
//pin shoud be declared as output in setup
if (freq >= 31 && freq <= 333333 && duration > 0 && duration <= 4290000)
{
duration *= 1000; //duration in microseconds
unsigned long halfT = (unsigned long)(float(1000000) / float(2 * freq) + 0.5); //half period in microseconds
if (2 * halfT > duration)
return;
unsigned long cycles = (unsigned long)(float(duration) / float(2 * halfT) + 0.5);
for (unsigned long i = 0; i < cycles; i++)
{
digitalWrite(pin, 1);
delayMicroseconds(halfT);
digitalWrite(pin, 0);
delayMicroseconds(halfT);
}
}
}