Arduino Forum

Using Arduino => Audio => Topic started by: teckel on Jan 11, 2013, 09:37 am

Title: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 11, 2013, 09:37 am
toneAC Library Project Homepage
 (https://bitbucket.org/teckel12/arduino-toneac/wiki/Home)

Advantages over the standard tone library:


Download:
toneAC v1.2 (https://bitbucket.org/teckel12/arduino-toneac/downloads)

New in v1.2:
Fixed a counter error which went "over the top" and caused periods of silence (thanks Krodal). For advanced users needing tight code, the TONEAC_TINY switch in toneAC.h activates a version of toneAC() that saves 110 bytes. With TONEAC_TINY, the syntax is toneAC(frequency, length) while playing the note at full volume forever in the background. Added support for the ATmega 640, 644, 1281, 1284P and 2561 microcontrollers.

Connection:
Connection is very similar to a piezo or standard speaker.  Except, instead of connecting one speaker wire to ground you connect both speaker wires to Arduino pins.  The pins you connect to are specific, as toneAC lets the ATmega microcontroller do all the pin timing and switching.  This is important due to the high switching speed possible with toneAC and to make sure the pins are alyways perfectly out of phase with each other (push/pull).  See the below list for which pins to use for different Arduinos.  Just as usual when connecting a speaker, make sure you add an inline 100 ohm resistor between one of the pins and the speaker wire.


Example sketch:
Code: (Example toneAC sketch) [Select]
#include <toneAC.h>

void setup() {} // Nothing to setup, just start playing!

void loop() {
  for (unsigned long freq = 125; freq <= 15000; freq += 10) { 
    toneAC(freq); // Play the frequency (125 Hz to 15 kHz in 10 Hz steps).
    delay(1);     // Wait 1 ms so you can hear it.
  }
  toneAC(); // Turn off toneAC, can also use noToneAC().

  while(1); // Stop (so it doesn't repeat forever driving you crazy--you're welcome).
}


Version History:
01/16/2013 v1.1 - Option to play notes in background, returning control back to your sketch for processing while note plays (similar to the way the tone library works). Volume is now linear and in the range from 0-10. Now uses prescaler 256 instead of 64 for frequencies below 123 Hz so it can go down to 1 Hz no matter what speed the CPU is clocked at (helpful if using toneAC to control a two-pin dual LED).
01/11/2013 v1.0 - Initial release.

Enjoy!

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 11, 2013, 10:17 am
Disadvantages of using toneAC compared to the standard tone library:



But, if you're flexible with your pin choices, this is a great upgrade. It also uses timer 1 instead of timer 2, which may free up a conflict you have with the tone library. It also exclusively uses port registers for the fastest and smallest code possible.

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: sbright33 on Jan 11, 2013, 11:01 pm
Very cool keep up the good work!
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: Magician on Jan 11, 2013, 11:12 pm
I 'd be cautious to drive high capacitance load like piezo w/o current limiting resistors. Though volume 'd be limited back to 1 pin level.
Don't want to discourage an author, just something to think about, may be put some kind of warning in library header, that reliability of IC could be affected. .
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: elac on Jan 12, 2013, 12:33 am
This is great thanks alot for sharing.
**Also using your New Ping library, thanks for that too.  8)
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: cyclegadget on Jan 12, 2013, 04:52 pm

  Another good library idea teckel! Your Karma points are way lower than your efforts should show!
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 13, 2013, 02:52 am
Piezo elements are like capacitors, that is a problem for higher frequencies. For ultrasonic sound it is even very bad to use a square wave, because of the peak currents. So there should be a resistor of 220 ohm (or 100 ohm ?) to protect the outputs of the Arduino. Please add a warning about that to your library.

Tested with normal 8 ohm speaker with extra 120 ohm resistor:
- Arduino Uno, pin 9,10 : good.
- Arduino Mega 2560, pin 11,12 : good
- Arduino Leonardo, pin 9,10 : good
- ATmega8 16MHz, pin 9,10 : good

My conclusion:
- No nasty click at start and stop : Excellent. A very small click can be heard.
- Extra loud : Good
- Small, fast code : Excellent
- Flexibility : Not so good, fixed pins.
- Volume control : Good, I needed that. Working roughly, not a linear scale.
- Frequency range : The lowest frequency is not low enough for a slow blinking two-pin dual led.

If I select a ultrasonic frequency, I don't hear it, but a very small click can be heard when the sound is started and stopped.
Perhaps setting the pins floating (set as inputs) if not used could reduce that. But that will make the code larger.
The normal Arduino tone() library doesn't work for all frequencies with the ATmega8. I didn't test that for your toneAC library very well, but it sounds okay.

Its a very good library. Thank you.

PS: Do you know the Mozzi library ? http://sensorium.github.com/Mozzi/
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 13, 2013, 06:49 am

I 'd be cautious to drive high capacitance load like piezo w/o current limiting resistors. Though volume 'd be limited back to 1 pin level.
Don't want to discourage an author, just something to think about, may be put some kind of warning in library header, that reliability of IC could be affected. .
I


I followed the lead of the Arduino.cc website (http://www.arduino.cc/en/Tutorial/PlayMelody) and didn't add a resistor to the piezo circuit drawing. For an 8 Ohm speaker, a single 100 ohm resistor should be used, just like you would with one pin attached.  You don't add two resistors, just one.  Therefore, it's still twice as loud as using the tone library if you use the same resistor.

Also, isn't there normally a high resistance on a piezo and it's not till high frequencies where the resistance drops to even around 50 ohms?  I believe a resistor is only needed for very high frequencies.  Also, I believe when driving the piezo with an alternating current like toneAC it doesn't create the high capacitance load like you normally see when driving (charging) it in one direction.

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 13, 2013, 09:48 am

Piezo elements are like capacitors, that is a problem for higher frequencies. For ultrasonic sound it is even very bad to use a square wave, because of the peak currents. So there should be a resistor of 220 ohm (or 100 ohm ?) to protect the outputs of the Arduino. Please add a warning about that to your library.


I believe a piezo only acts like a capacitor when "charged" in one direction (for example, with the tone library).  The deflection of the disc is what generates the current.  However, with toneAC it can't charge in this way as an alternating current is being sent.  Therefore, the piezo is never charged and never acts like a capacitor.  From my understanding of how a charge on a piezo works, supplying an alternating current eliminates the need for a resistor.  But, maybe I'm mistaken.


Tested with normal 8 ohm speaker with extra 120 ohm resistor:
- Arduino Uno, pin 9,10 : good.
- Arduino Mega 2560, pin 11,12 : good
- Arduino Leonardo, pin 9,10 : good
- ATmega8 16MHz, pin 9,10 : good


Nice!  Mega, Leonardo, and ATmega8 were my primary concerns.  I spent a lot of time sniffing around the Arduino code so I had hoped that I got everything correct.


My conclusion:
- No nasty click at start and stop : Excellent. A very small click can be heard.
- Extra loud : Good
- Small, fast code : Excellent
- Flexibility : Not so good, fixed pins.


The reason it doesn't have any nasty clicking and noise like you get with the tone library is because I'm letting the ATmega do it's own PWM thing instead of faking it like the tone library does.  The tone library just sets up a timed event and then the library twiddles the bits.  It works, but not perfectly.  This is why I have toneAC fixed to the PWM pins.  It would be simple to allow any pins to be used, but the the accuracy wouldn't be perfect (which is required to keep things perfectly out of phase).  There would also be a little more to do than with the tone library because two pins would need to be toggled instead of one.  Also, as you get into ultrasonic frequencies, there's just not enough processing power on the poor little ATmega to do everything.


- Volume control : Good, I needed that. Working roughly, not a linear scale.


Very true, the volume is not at all linear.  It simply uses the duty cycle which is not linear for audio.  I didn't want to hold up the library being released to sort this out.  But, it's something I'm still looking into.  What I'm thinking is measuring SPL of every duty level and then creating a table of 10 duty cycles (1=min, 10=max) that are linear for volume.


- Frequency range : The lowest frequency is not low enough for a slow blinking two-pin dual led.


I've got it running here with no problem.  For v1.0 of toneAC a 16 MHz ATmega will be able to go down to 2 Hz.  My development v1.1 now goes down to 1 Hz (changed to prescaler 256).  Here's the sketch I used:

Code: [Select]
#include <toneAC.h>

void setup() {}

void loop() {
 int pot = analogRead(A0);
 int freq = map(pot, 0, 1023, 3, 30);
 toneAC(freq);
 delay(334);
}



If I select a ultrasonic frequency, I don't hear it, but a very small click can be heard when the sound is started and stopped.
Perhaps setting the pins floating (set as inputs) if not used could reduce that. But that will make the code larger.
The normal Arduino tone() library doesn't work for all frequencies with the ATmega8. I didn't test that for your toneAC library very well, but it sounds okay.


When I do this, I don't hear a click.  Then again, I used an ultrasonic (40 kHz) piezo and not a speaker.  I'm not so worried about small clicks on start/stop (this is kind of expected).  The clicking while playing a constant note or notes is what I have a problem with.


PS: Do you know the Mozzi library ? http://sensorium.github.com/Mozzi/


Not till now.  But, doing that kind of thing should be easy with toneAC.  Just convert a WAV or MP3 file to something like 8-16 kHz mono and save as RAW.  Then load it into a sktech and play the sequence.  Maybe I'll do a dog bark example or something.

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 13, 2013, 12:03 pm
As far as I know, a piezo element is always like a capacitor.
If you have a capacitance meter, try your ultrasonic piezo. It could easily be 100nF.
If the capacitance meter uses a DC signal to measure, just add a capacitor in series with the piezo. It won't make any difference.

I used a ultrasonic piezo with a square AC wave (just like toneAC) and my high speed H-bridge driver ic got very hot and got blown.
I learned that 120dB ultrasonic piezo drivers don't use a square wave because of the capacitance. They use some kind of (simulated) sine wave.

If the starting frequency could be 1Hz for a Arduino Uno at 16MHz, that would be very nice.

Can you make a very low volume ?
It is as with the PWM for leds. To get a led dimmed so that it is almost not visible, the pwm should be between 1/1000 or 1/10000.

What about H-bridge drivers for more output power. What kind of driver ic would match your library for a few different applications ?
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 14, 2013, 07:20 am
I did some testing on different acoustic transducers.  First, for my ultrasonic transducers I could not get them to draw more than 7 mA no matter the frequency (even the harmonic peak).  I have one "piezo" that seems to work more like a regular speaker at 16 ohms.  That unit can draw up to 33 mA without a resistor.  My guess is that it's not a piezo as my true piezo transducers have a resistance in the mega ohms as they should.

Because of this, I've changed my circuit drawing to include a 100 ohm resistor as it doesn't make much of a difference and it seems that maybe some that claim are piezo are not really piezo.  With that said, I'm still not certain that driving a true piezo transducer even at ultrasonic levels requires a resistor when using an alternating current.  From what I've read, the capacitance charging only occurs under a DC load, and that charged is discharged when the polarity is reversed (such as in an AC system).  Still more testing to confirm this.

For the time being, you should connect a piezo or speaker exactly as you have in the past, a decision on AC connection will need more research.  Still toneAC is twice as loud, even when you use or don't use a resistor as you would normally.

Progress on v1.1 of toneAC is coming along.  Two major changes that are being tested are a linear volume and a tone length value that works in the background like the tone library.  We should see v1.1 released sometime this week.

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 15, 2013, 08:03 am
Added background playback (timer interrupt controlled) and linear volume to my development version of toneAC.  I'll be testing it on Tuesday.  Expect a new release probably on Tuesday or Wednesday.

Tim
Title: Re: New library - toneAC - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 16, 2013, 12:43 am
While not written to do this, toneAC works well controlling a two-pin dual LED.  With this and a potentiometer, the sketch below will flash the LED alternating between the two LED colors.  This is happening in the background with control returning to your sketch to do other things as noted in the sketch.  Every half second it will look at the pot and change the LED flashing speed.  This sketch is designed to work with toneAC v1.1 that will be released once I get home

Code: [Select]
// ---------------------------------------------------------------------------
// Connect a two-pin dual LED to the following pins with inline 220 ohm resistor.
//   Pins  9 & 10 - ATmega328, ATmega128, ATmega8, Uno, Leonardo, etc.
//   Pins 11 & 12 - ATmega2560, ATmega1280, Mega
//   Pins 14 & 15 - Teensy 2.0
//   Pins 25 & 26 - Teensy++ 2.0
// Connect the center lead of a potentiometer to analog pin A0 and the other two leads to +5V and ground.
// ---------------------------------------------------------------------------

#include <toneAC.h>

unsigned long timestamp = 0; // Stores when the next time the routine is set to run.

void setup() {}

void loop() {
 if (millis() > timestamp) { // Is it time yet?
   timestamp += 500;         // Set the next time routine will run. 500 ms because the lowest frequency is 2 Hz, which is a half second.
   int pot = analogRead(A0);            // Read the potentiometer connected to analog pin A0.
   int freq = map(pot, 0, 1023, 2, 40); // Convert pot analog values to a range from 2 to 40 Hz.
   toneAC(freq, 10, 0, true);           // Set the frequency and have it run forever in the background (next event should take over in 500 ms).
 }
 /* Do a bunch of other stuff here, it won't affect toneAC doing its thing. */
}


Because toneAC is designed to be used for audio, duty has been purposed for linear volume control instead of fading the LED from one color to the other evenly.  Basically, duty is linear for audio but not for lighting an LED.  If there's a desire for linear LED duty control, making a few tweaks to the toneAC library or making a different library designed just for controlling a two color LED would be in order.  The above sketch is a teaser that may help someone with a project.

Tim
Title: toneAC v1.1 Released
Post by: teckel on Jan 17, 2013, 06:08 am
New in v1.1
Option to play notes in background, returning control back to your sketch for processing while note plays (similar to the way the tone library works). Volume is now linear and in the range from 0-10. Now uses prescaler 256 instead of 64 for frequencies below 122 Hz so it can go down to 1 Hz no matter what speed the CPU is clocked at (helpful if using toneAC to control a two-pin dual LED).

Download:
toneAC v1.1 (http://code.google.com/p/arduino-tone-ac/downloads/list)

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 17, 2013, 01:28 pm
I'm still testing it, but I think I found an error.

Code: [Select]

int f;

while(1)
{
  f = random( 50, 120);
  toneAC(f, 5, 0, true);
  delay(100);
  noToneAC();    // reset registers
}


The example is okay with the noToneAC() to reset the registers.
Try to remove the noToneAC(), that results in gaps in the sound.
Perhaps the counter has to roll-over ?
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 18, 2013, 06:33 am

The example is okay with the noToneAC() to reset the registers.
Try to remove the noToneAC(), that results in gaps in the sound.
Perhaps the counter has to roll-over ?


I heard something like this once, but couldn't duplicate it so I figured I just had a loose connection.

You're exactly correct on your diagnosis.  The counter is "over the top" so it needs to wrap before resuming the sound.  This isn't very long when using prescaler 1.  But, at 122 Hz and below, prescaler 256 is used which is 256 times longer than prescaler 1 and the reason for the long silence.

Since even more problems can happen when we play notes on each side of the prescaler cutoff frequency, I tweaked your sketch to create a torture test:

Code: [Select]
#include <toneAC.h>

void setup() {}

void loop() {
 int f = random(50, 124);
 toneAC(f, 10, 0, true);
}


Since it includes frequencies above 122Hz, it sometimes also uses prescaler 1.  Also, there's no delay so it just hammers the hell of of things.  This sketch should produce a static-like noise as it plays random notes as fast as it can.  Instead, it's a bunch of random clicks with periods of silence as it frequently goes "over the top".

After some testing, I've isolated the problem and have a fix.  In the toneAC.cpp file after the line that reads "ICR1   = top;" add the following line:

Code: [Select]
 if (TCNT1 > top) TCNT1 = top;         // Counter over the top, not good, put within range.

With this, the above sketch now produces what you'd expect, static.  During early development, I set TCNT1 = 0 when starting a tone.  That works fine for high frequencies, but poorly at lower frequencies and when changing notes (creates clicks).  It's even worse when driving a two-pin dual LED at ultra low frequencies (like at 2 Hz).  Adding the noToneAC() in your sketch works because when TCCR1A resets the PWM it automatically sets the counter to zero.  While this works, it's not ideal for the above reasons of setting the counter to zero can cause other problems.

In any case, the above line fixes things and I've added it to the development version which will be released in version 1.2.

On a side note, the volume setting doesn't really work well for low frequencies.  It doesn't do much to change the volume and lowers the quality (makes it buzzy).  I'd suggest to always use 10 for the volume, which keeps the quality high.  Only use a lower volume if it's a requirement.

Anyway, thanks for the catch!  And leading me in the right direction with the fix.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 18, 2013, 07:52 am
First of all, I love the library. It will be my first choice in most applications.
I hope to test the Uno/Mega/Leonardo/ATmega8 with version 1.2, after that it should be ready.
That single line of code makes some of my tests sound a lot better.

I have made a checklist for version 1.2, perhaps there are one to two things that make sense.

(1) The code increased a little (just a little) which is always a problem for the ATmega8
library + example version with 1.0, Arduino Uno : 1516
library + example version with 1.1, Arduino Uno : 1670
library + example version with 1.0, ATmega8 : 1336
library + example version with 1.1, ATmega8 : 1472

(2) The ISR uses millis(), so a roll-over of the millis is possible. The length is no longer fail-safe, so using the delay() function with noToneAC() is preferrable for critical situations.

(3) You don't use the 'L' for long values. I don't mind about it in the sketch, but you could use it in your library. I prefer to use 0L, 256L, - 1L and so on, when long integers are involved.

(4) The examples have the extension *.pde. I would prefer *.ino

(5) In the example you use '/* .... */' for comment, but everwhere else '//'.

(6) In the example, you use a potmeter. But for a small test with the library, a very quick result (showcase) would be needed. And a potmeter will make it unnecessary complicated.

(7) You made 10 volume steps, which is great. But for a 'ping' sound, a smooth decrease of the volume is needed. Or am I asking too much for the library ? Are there open source examples of tunes with volume ?

( 8 ) Why is the sound different for this example ?
Code: [Select]

int i, freq, vol;

for (i = 0; i<5; i++)

  freq = 900;
  for (vol=10; vol>0; vol--)
    toneAC( freq , vol, 60, false);
  freq = 540;
  for (vol=10; vol>0; vol--)
    toneAC( freq, vol, 60, false);
  delay( 3000);
}

for (i = 0; i<5; i++)

  freq = 900;
  for (vol=10; vol>0; vol--)
  {
    toneAC( freq , vol, 0, true);
    delay(60);
  }
  freq = 540;
  for (vol=10; vol>0; vol--)
  {
    toneAC( freq, vol, 0, true);
    delay(60);
  }
  noToneAC();
  delay( 3000);
}
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 18, 2013, 10:17 am

(1) The code increased a little (just a little) which is always a problem for the ATmega8

Great pains have been taken to keep the code as small as possible.  I'm a huge believer in running as much as possible in the background so around 150 additional bytes I believe are important.  It's still much smaller than the tone library.  I show the Arduino Uno code to be 1604 bytes with Arduino v1.0.2 not 1670.  And with the ATmega8 I have it as 1398 instead of 1472 (again v1.0.2).  As a test I created a toneACmini() function that only has a frequency and duration (automatically runs in the background).  With toneACmini() instead of toneAC() it went down to 1488 bytes on the Uno.  But, not sure if 116 bytes is worth confusing people.


(2) The ISR uses millis(), so a roll-over of the millis is possible. The length is no longer fail-safe, so using the delay() function with noToneAC() is preferrable for critical situations.


It uses unsigned long int, so it's about a 50 day range.  That should be good for almost any situation.  The rollover of micros is critical, but ms hardly ever happens in the real world.  Although, I am working on a project right now that I'm trying to get it to run virtually forever.


(3) You don't use the 'L' for long values. I don't mind about it in the sketch, but you could use it in your library. I prefer to use 0L, 256L, - 1L and so on, when long integers are involved.


If there's an advantage I'm not aware of let me know.  Most of my longs are unsigned longs.  Not sure if that makes a difference.


(4) The examples have the extension *.pde. I would prefer *.ino


They need to be .ino for a library so old versions of Arduino can find them.  I'm running only v1.0.2 so everything is a .pde.  I change them to .ino just for the library.  Other library creators told me to use .ino


(5) In the example you use '/* .... */' for comment, but everwhere else '//'.


I hardly ever use '/* .... */'.  I use it in that particular case to try and identify that you can do a bunch of stuff there, not just one line.


(6) In the example, you use a potmeter. But for a small test with the library, a very quick result (showcase) would be needed. And a potmeter will make it unnecessary complicated.


The library is designed for sound, not LEDs.  The sample is "toneAC_demo" which doesn't use a pot.  The one you're talking about is an advanced one that I don't mention anywhere as it's only for more advanced users that may want to use toneAC for other purposes.


(7) You made 10 volume steps, which is great. But for a 'ping' sound, a smooth decrease of the volume is needed. Or am I asking too much for the library ? Are there open source examples of tunes with volume ?


You're asking too much.  I got out my SPL meter and it was HARD to get even 10 volume levels.  A square wave just doesn't work well for creating a true volume level.  I had to cheat to get even 10, there was really only 9 but that would just be confusing.


( 8 ) Why is the sound different for this example ?


They're very close.  But, the first loop is inferior because it uses the foreground method and therefore there's a short period of time where there's no sound, producing a non-constant sound and clicking.  This way is designed for a laymen who who isn't too comfortable with programming but they can still generate sound using this method and would probably be totally happy with that.  The second way is a more proper way that a higher level programmer would use, knowing that the first way would have a very slight but still noticeable gap between notes reducing quality.  I would only ever use the second loop, as I did with the original tone() library as well.

The idea that something runs in the background is very foreign to many novice programmers.  They love delay statements, or a command that just does something for as long as they specify and then returns to them when it's done.  So, toneAC makes it easy for the masses, but still powerful for those who better understand an interrupt/timer driven paradigm.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 18, 2013, 12:21 pm
My sketch size was different, because I used my own example.

I like the mini function. Perhaps it will not be used often, it's nice to have as an extra.

Using 'L' or 'UL' for long numbers is something I do for myself, so that I know what I'm doing.

I agree with everything else. Perhaps that ping-pong sound (the second smooth one) can be used as an example ? I'm trying to make more sounds that show what the volume can do.

A page in the playground section would be nice. I can make one, with links to your code and this thread.
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: robtillaart on Jan 18, 2013, 10:40 pm
Quote
But, not sure if 116 bytes is worth confusing people.

think not, but by the time their sketches fill up all memory and the last 116 bytes are critical I assume they aren't confused any more by a stripped lib ;)
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 18, 2013, 11:42 pm

Quote
But, not sure if 116 bytes is worth confusing people.

think not, but by the time their sketches fill up all memory and the last 116 bytes are critical I assume they aren't confused any more by a stripped lib ;)


If I only knew how to set a define in a sketch so the library knew about it I'd be done by now.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 19, 2013, 12:47 am
Don't bother about the mini, it's not that important.

Example 1 : alert (soft and loud)
Code: [Select]

  // soft and loud alert.
  // For the toneAC library.
  // public domain
  int i, j;

  // Soft alert
  for( i=0; i<10; i++)
  {
    for( j=0; j<3; j++)
    {
      toneAC( 720, 3, 0, true);
      delay( 50);
      toneAC( 610, 3, 0, true);
      delay( 50);
      noToneAC();
      delay( 30);
    }
    delay( 500);
  }

  delay( 2000);
 
  // Loud alert
  for( i=0; i<10; i++)
  {
    for( j=0; j<3; j++)
    {
      toneAC( 720, 10, 0, true);
      delay( 50);
      toneAC( 610, 10, 0, true);
      delay( 50);
      noToneAC();
      delay( 30);
    }
    delay( 500);
  }

  delay( 2000);
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 19, 2013, 02:16 am

Don't bother about the mini, it's not that important.

Example 1 : alert (soft and loud)
Code: [Select]

  // soft and loud alert.
  // For the toneAC library.
  // public domain
  int i, j;

  // Soft alert
  for( i=0; i<10; i++)
  {
    for( j=0; j<3; j++)
    {
      toneAC( 720, 3, 0, true);
      delay( 50);
      toneAC( 610, 3, 0, true);
      delay( 50);
      noToneAC();
      delay( 30);
    }
    delay( 500);
  }

  delay( 2000);
 
  // Loud alert
  for( i=0; i<10; i++)
  {
    for( j=0; j<3; j++)
    {
      toneAC( 720, 10, 0, true);
      delay( 50);
      toneAC( 610, 10, 0, true);
      delay( 50);
      noToneAC();
      delay( 30);
    }
    delay( 500);
  }

  delay( 2000);



If you want a loud alert from a piezo, it's best to first find its harmonic frequency.  You can do it with a miltimeter.  Just look for the frequency where the most current is drawn.  It will typically be quite a large spike right at the loudest point.  If you want something loud, this will be the frequency to play.  With a piezo, it's typically 4,000 Hz.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 19, 2013, 03:49 am
Example 2 : A whistling kettle with boiling water sound.
This is a full sketch.

Code: [Select]

// Example for the toneAC library
// A whistling kettle with boiling water sound.
// public domain

#include <toneAC.h>

void setup()
{
}

void loop()
{
  int i, freq, freq_extra, freq_shift, vol;

  freq = 1440;
  vol = 1;

  for (i=0; i<1000; i++)
  {
    freq_shift = random (-15, 15);
    freq += freq_shift;
   
    // Stay around the frequency 1440
    if (freq < 1440)
      freq ++;
    else
      freq --;

    vol = i/50;     
    if (vol > 10)
      vol = 10;
    if (i > 800)
      freq_extra = (vol * vol) + 800;
    else
      freq_extra = (vol * vol) + i;
   
    toneAC( freq + freq_extra, vol, 0, true);
    delay(30);
  }
  noToneAC();
 
  delay(5000);
}
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 19, 2013, 06:47 am

Don't bother about the mini, it's not that important.


To save a bit of compiled code size, use toneAC(). instead of noToneAC().  noToneAC() was meant to be familiar to the Tone library and the noTone() command.  But, it's totally not needed for toneAC() and as a bonus you save 10 bytes.

Also, I created a TONEAC_TINY switch that allows you to save around 110 bytes that uses an alternate version of toneAC().  Would be useful for projects where maximum speed or the lowest code size is required.

I'm considering creating another library named something like ToneTiny or NewTone where it's a plug-in replacement for Tone including pin assignment but is much smaller, faster, and better quality.  I know lots of people that have timer interrupt issues with the Tone library and are looking for an alternative.  Not that toneAC doesn't provide that already, but toneAC is designed more for highly accurate AC switching speed and maximum volume.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 19, 2013, 08:49 am

I'm considering creating another library named something like ToneTiny or NewTone where it's a plug-in replacement for Tone including pin assignment but is much smaller, faster, and better quality.  I know lots of people that have timer interrupt issues with the Tone library and are looking for an alternative.  Not that toneAC doesn't provide that already, but toneAC is designed more for highly accurate AC switching speed and maximum volume.


It was so easy I just did it, NewTone (http://code.google.com/p/arduino-new-tone/) is a working library.  Plug-in replacement for the Tone library, but over 1,200 bytes smaller compiled code size, faster, better quality sound, etc.  Also uses timer 1 if you're having a conflict on timer 2 with the Tone library and some other library or hardware.  Seriously took 30 minutes to write.

A little bit surprising is that toneAC still produces slightly smaller code (60-170 bytes).  This is possible because toneAC doesn't need to find the ports and masks for the pins as it's fixed.  But, I believe NewTone still has a place for those who need smaller, tighter code, yet need the flexibility of connecting to any pin.  toneAC is still better in every way, with the exception being the fixed pins, but that's also why it's so good.

I'll probably package up NewTone and upload it later today for those who need a flexible drop-in replacement for the Tone library.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: robtillaart on Jan 19, 2013, 04:43 pm
Quote
I'm considering creating another library named something like ToneTiny or NewTone

TinyTony? sounds Italian, would fit the Arduino ;)
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 20, 2013, 08:50 am
Example 3: Tone Tutorial with fade out tones.
You have to listen to this for yourself. It is not like a piano, because it sounds very computer/robotic.

Use the tone tutorial : http://arduino.cc/en/Tutorial/tone
But connect the loudspeaker to two output pins as is required for the toneAC library.

Replace the setup() function with this:
Code: [Select]

// Example for toneAC with tone fade out.
// Using the tone tutorial : http://arduino.cc/en/Tutorial/Tone
// public domain

void setup()
{
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000/noteDurations[thisNote];
   
    // Add some to the length for the pauses between the notes.
    noteDuration += noteDuration/2;
    int i, vol;
    // Setting the volume to 12 is a trick to reduce the code.
    // The maximum volume is 10, but 12 is allowed.
    vol = 12;
    for (i=0; i<=noteDuration; i+=25)
    {
      // Double the frequency to make it sound better.
      toneAC( 2* melody[thisNote], vol, 0, true);
      // fade out
      if (vol > 0)
        vol--;
      delay( 25);
    }
    noToneAC();
  }
}
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: cyclegadget on Jan 20, 2013, 08:35 pm

@teckel

I tried your sketch on a Bobuino with a 1284 chip, the speaker buzzed but nothing more. The board is found halfway down this page. http://www.crossroadsfencing.com/BobuinoRev17/

This may be asking too much but, would you consider making your library work with the 1284P? I have built a few boards using the chip.

This page may help you in the process if your interested. http://maniacbug.wordpress.com/2011/11/27/arduino-on-atmega1284p-4/

I will be happy to test for you of course.  :)

Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 21, 2013, 05:04 am

I tried your sketch on a Bobuino with a 1284 chip, the speaker buzzed but nothing more. The board is found halfway down this page. http://www.crossroadsfencing.com/BobuinoRev17/

This may be asking too much but, would you consider making your library work with the 1284P? I have built a few boards using the chip.

This page may help you in the process if your interested. http://maniacbug.wordpress.com/2011/11/27/arduino-on-atmega1284p-4/

I will be happy to test for you of course.  :)


I had believed it would work with the 1284P.  Don't have one to confirm, but looking into it further I see that the ATmega1284P is different.  I've updated my development v1.2 to support ATmega640, ATmega644, ATmega1281, ATmega1284P and ATmega2561.  I've private messaged you a file for you to test to verify it works on the ATmega1284P.  The pins you should use are D12 and D13 (the timer 1 PWM pins) on that microcontroller.

Let me know how it works.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: cr0sh on Jan 21, 2013, 08:11 am

Example 2 : A whistling kettle with boiling water sound.


I don't have the code handy - but waaaay back when I was kid, I remember playing around on my TRS-80 Color Computer with the PLAY command; there was a way, via using certain values (I think random notes played with very, very short durations) with a rapidly decreasing volume level (the CoCo had a 6 bit DAC - so there were 64 volume levels) - you could make an "explosion" or "gun" sound of sort...

...care to try making something like that?

;)

Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 21, 2013, 08:33 am
Since the toneAC library is ideal for kids toys (extra loud, no nasty clicks, volume control), these kind of sounds came to my mind. But so far I could not make something that sounds right.
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 21, 2013, 09:05 am

Since the toneAC library is ideal for kids toys (extra loud, no nasty clicks, volume control), these kind of sounds came to my mind. But so far I could not make something that sounds right.


If you'd like to post your sound effect sketches to the toneAC library page I believe I can arrange it.  You need a Gmail email address and let me know what it is and I'll try to set it up for you.  Never done it before, but it seems like it's possible.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 21, 2013, 10:11 am
No need to set it up for me. I hope to add one or two more sounds with the library, and I will post them in this thread. I don't know if others want to contribute, and I also can't find a site with melodies and sounds that make use of the volume.
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 21, 2013, 07:07 pm
Example 4: Random sound

This is just a random. To make it random to the human ear, the frequency is not linear.
It can be used as startup-sound or to simulate that device is totally confused.
Set the volume to your own need.

Code: [Select]

// Random sound
// public domain

int i, j, frequency, volume, duration;

for( i=0; i<1000; i++)
{
  j = random (5, 60);
  frequency = j * j;
  volume = random(6, 11);
  toneAC( frequency, volume, 0, true);
  j = random( 1, 12);
  duration = j * j;
  delay( duration);
}
noToneAC();
 
delay(2000);




Example 5 : misuse of the toneAC library

The next example is able to generate noise sounds.
Both random functions are part of the delay. The random change in volume is needed for the noise.

Code: [Select]

// example of noise sounds with toneAC library
// public domain
//
// The lower and higher frequency define the sound.
//     300, 1500 : noise
//     340, 345   : computer noise
//     600, 14500 : rain drops noise

#define FREQUENCY_LOWER   300
#define FREQUENCY_HIGHER   1500
 
int i, frequency, volume;

for( i=0; i<10000; i++)
{
  volume = random(6, 11);
  frequency = random( FREQUENCY_LOWER, FREQUENCY_HIGHER);
  toneAC( frequency, volume, 0, true);
  delay(1);
}
noToneAC();
 
delay(2000);
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: countofangels on Jan 24, 2013, 09:20 pm
First of all this library is awesome, and I'm very pleased that I found it. Registered just for this.

Secondly though, I'm running into trouble because of the 9 & 10 pin requirements. (Arduino Uno)

Is there a way someone could point in the right direction to modify the library to use pins 5 & 6? (or other PWM pins in general?)  Or perhaps I misunderstand and the relevant timer is ONLY accessible on 9 & 10.

Any reason we couldn't use Timer 0 or Timer 2, per: http://playground.arduino.cc/Main/TimerPWMCheatsheet


Alternately, I think it'd be an excellent addition to the library to be able to set options to switch between all possible PWM pins, just to give a little bit more flexibility.
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 24, 2013, 10:20 pm

First of all this library is awesome, and I'm very pleased that I found it. Registered just for this.

Secondly though, I'm running into trouble because of the 9 & 10 pin requirements. (Arduino Uno)

Is there a way someone could point in the right direction to modify the library to use pins 5 & 6? (or other PWM pins in general?)  Or perhaps I misunderstand and the relevant timer is ONLY accessible on 9 & 10.

Any reason we couldn't use Timer 0 or Timer 2, per: http://playground.arduino.cc/Main/TimerPWMCheatsheet

Alternately, I think it'd be an excellent addition to the library to be able to set options to switch between all possible PWM pins, just to give a little bit more flexibility.


The library uses timer 1, which are hard-coded to the PWM pins 9 & 10 on the Arduino Uno.  It's not that my library hard-codes this, this is how the ATmega microcontroller is designed.  While it's possible to have the timer interrupt run a small routine that would allow you to use different pins, the speed and accuracy would suffer.  This isn't a big deal if you're doing human-audible frequencies as the Arduino would be plenty fast to do this.  But, toneAC is designed to do frequencies well beyond even typically ultrasonic range (like 1 MHz) and do so with precise accuracy.

If it was just about flexibility, I would have written the library that way from the beginning (I basically already did when I wrote the NewTone library, which is based on toneAC but allows you to specify a pin).  There's no way to keep the speed and accuracy while allowing you to select the pins.

Further, typically the only reason why you wouldn't want to use the timer 1 PWM pins is because you have a conflict with timer 1, not because you can't just move pins around.  So, the real issue isn't that you use other pins, it's that you need it to use a different timer.  The problem with doing that is that you'll get just as many people complain about using a different timer as it conflicts with a different set of libraries.  Timer 0 is basically off-limits because that would mess with the ATmega's internal timers (millis, micros).  Timer 2 would be possible, but more complicated as not all ATmega's have a timer 2 (Leonardo, Teensy 2.0) and they would use timer 4 instead.

So, switching over to use timer 2&4 instead of timer 1 would solve a problem for 10%, but create a problem for 10%, in other words a wash.  Adding both timer 1 and timer 2/4 support would make the library more than twice the size, which would cause problems for some as it's small enough to be used on microcontrollers like the ATmega8 while the tone library won't fit.

In other words, we wouldn't really be solving anything by adding timer 2/4 support.  We would for some, but we'd be creating problems for others.

I would think the only real option would be to rework toneAC and create a new library, say toneAC2 for example.  It would simply be a timer 2/4 version of toneAC that would be fixed to the timer 2/4 PWM pins.

Now that I say this, and think about it for a minute, maybe it's not possible.  Timer 2 doesn't have a Phase and Frequency Corrected PWM mode, so I don't think you can do it exactly like toneAC.  It would need to be a slower and less accurate way.

It's not really that big of a project to do, but I don't have the need for it, therefore not the desire either.  If someone is versed in timer interrupts, it would be really easy to take my toneAC and NewTone libraries and make a toneAC2 library that would use timer 2/4 as well as allow you to specify the pins.  If I get bored one night maybe I'll do it (probably a 2 hour job).  I guess as a bonus I wouldn't need to create a new development page for it.  I could just piggy-back it on the toneAC site as an alternative version that uses timer 2/4 and has flexible pin assignments.  Ah crap, maybe I will just do it.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: countofangels on Jan 24, 2013, 10:32 pm

Ah crap, maybe I will just do it.

Tim


Ah my name is Tim as well.  :P

So from one Tim to another: Thanks for the detailed information involved as to the concerns with the timers. It's helpful for me to learn more about this as a beginner to the Arduino world.

At the moment, I'm mostly trying to figure out how to use your library without conflicting with the SD library's use of the 10 pin as a selector (per: http://arduino.cc/en/Reference/SDCardNotes)  Based on what I've read there, though it looks like I may be able to just use SD.begin() to select a different pin for card initiation, and as long as 10 remains an Output that shouldn't actually cause problems.

So actually, with a little reading, I think the library will work for my particular application as it is.


Though I still think it would be awesome to have versions of the library for each of the available timers, just for that extra flexibility. From the pretty robust response you've received on the library in only a couple weeks, I think it's clear that people are finding it useful.

Anyway! Thanks for your efforts.
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 24, 2013, 11:26 pm


Ah crap, maybe I will just do it.

Tim


Ah my name is Tim as well.  :P

So from one Tim to another: Thanks for the detailed information involved as to the concerns with the timers. It's helpful for me to learn more about this as a beginner to the Arduino world.

At the moment, I'm mostly trying to figure out how to use your library without conflicting with the SD library's use of the 10 pin as a selector (per: http://arduino.cc/en/Reference/SDCardNotes)  Based on what I've read there, though it looks like I may be able to just use SD.begin() to select a different pin for card initiation, and as long as 10 remains an Output that shouldn't actually cause problems.

So actually, with a little reading, I think the library will work for my particular application as it is.


Though I still think it would be awesome to have versions of the library for each of the available timers, just for that extra flexibility. From the pretty robust response you've received on the library in only a couple weeks, I think it's clear that people are finding it useful.

Anyway! Thanks for your efforts.


If the conflict is with the SD library, it's easy to get around it as it doesn't need to use pin 10.  toneAC sets pins 9 and 10 (on the Uno) to output the first time you run it.  It also never changes them back to input either.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 26, 2013, 08:31 am

Though I still think it would be awesome to have versions of the library for each of the available timers, just for that extra flexibility. From the pretty robust response you've received on the library in only a couple weeks, I think it's clear that people are finding it useful.


I had some extra time so I spent an hour and built the toneAC2 library that uses timer 2 and allows you to use any two pins.  It doesn't have the level of accuracy as toneAC nor the range.  Also, we lose the volume control because timer 2 doesn't have all the features of timer 1.  You're basically trading accuracy, range, and volume for flexible pin assignments.

What's kind of funny is that I wrote toneAC2 at work and I didn't have any Arduino's with me to test.  So, I couldn't test it at all, didn't even compile it as I was just using note++ to edit the library.  When I got home it had one little bug and then it compiled (needed to declare a variable outside a "for" loop).  It compiled the second time and worked perfectly.  I guess I've been doing low level port registers and timers too long.

I need to add Teensy and Leonardo support (ATmega32U4 needs to use timer 4 instead of timer 2) and test before I release it.  But, that's simple so it should be uploaded this weekend.  I'll post when it's available.

Tim
Title: toneAC2 v1.0
Post by: teckel on Jan 27, 2013, 06:19 am
As promised, the pin flexible and timer 2 version of toneAC was released.  You can download it from the toneAC development page here:

toneAC2 - v1.0 (http://code.google.com/p/arduino-tone-ac/downloads/list)

This is an alternate version of toneAC that uses timer 2 instead of timer 1 and allows for any two pins to be used.  You should still try to use toneAC first, as it's more accurate, higher quality, allows for higher frequencies, and creates smaller code.  However, if you're having a conflict with timer 1, or just can't use the PWM pins for timer 1, then toneAC2 may be your answer.

toneAC2 is a replacement to the standard tone library with the advantage of nearly twice the volume, 800 bytes smaller compiled code size, and less stress on the speaker. This alternate version uses timer 2 and allows for flexible pin assignment. The primary version (toneAC) allows for higher frequencies, higher quality, and even smaller code size. However, toneAC is fixed to using the PWM timer 1 pins unlike toneAC2 which can use any two pins. Both exclusively use port registers for the fast and smallest code possible.

Let me know if there's any problem.  Oh, I didn't add Leonardo and Teensy 2.0 support.  I forgot how different timer 4 was on those compared to timer 2.  It seemed too much like work to make it compatible so I released it as-is.

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 27, 2013, 10:47 am
I'm waiting for toneAC version 1.2.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 27, 2013, 09:58 pm

I'm waiting for toneAC version 1.2.


Sorry about that, kind of forgot about releasing it.  It's been packaged for distribution for 7 days but I was working with someone via PM to confirm compatibility. In any case, v1.2 is now online and ready to download.

Download:
toneAC v1.2 (http://code.google.com/p/arduino-tone-ac/downloads/list)

New in v1.2:
Fixed a counter error which went "over the top" and caused periods of silence (thanks Krodal). For advanced users needing tight code, the TONEAC_TINY switch in toneAC.h activates a version of toneAC() that saves 110 bytes. With TONEAC_TINY, the syntax is toneAC(frequency, length) while playing the note at full volume forever in the background. Added support for the ATmega 640, 644, 1281, 1284P and 2561 microcontrollers.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: Krodal on Jan 30, 2013, 02:14 pm
Library toneAC version 1.2 tested with Uno, Leonardo, Mega 2560, ATmega8 16MHz. Everything is okay.
Library toneAC version 1.2 with option TONEAC_TINY tested with ATmega8 16MHz. Also okay, 140 bytes smaller.

The TONEAC_TINY version has implications for the source code.
If I would use toneAC(1000,5); and switch to TONEAC_TINY, I must change that line. That is not obvious, since it is the same function "toneAC".
The second parameter changes from volume to duration.
Adding a second parameter (an unused volume byte) changes the size saving from 140 to 106.
I don't know what to think of it.

What about a ToneAC page in the Playground section ?

Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: robtillaart on Jan 30, 2013, 08:36 pm
Quote
What about a ToneAC page in the Playground section ?

Good idea!
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 30, 2013, 11:57 pm

Library toneAC version 1.2 tested with Uno, Leonardo, Mega 2560, ATmega8 16MHz. Everything is okay.
Library toneAC version 1.2 with option TONEAC_TINY tested with ATmega8 16MHz. Also okay, 140 bytes smaller.

The TONEAC_TINY version has implications for the source code.
If I would use toneAC(1000,5); and switch to TONEAC_TINY, I must change that line. That is not obvious, since it is the same function "toneAC".
The second parameter changes from volume to duration.
Adding a second parameter (an unused volume byte) changes the size saving from 140 to 106.
I don't know what to think of it.


It was an oversight not changing the function name for TONEAC_TINY.  I now changed the function name to toneAC_tiny() when using the TINY code.

Adding the volume in for TINY code makes the TINY savings only 52 bytes on my 1.0.3 compile on Uno.  If it's only 52 bytes of savings I should probably just remove the TINY code totally.


What about a ToneAC page in the Playground section ?


That's the plan, just haven't got to it yet.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: xxryan1234 on Jan 31, 2013, 03:49 pm
Hi. Can you add ADSR with your library sir? :)

http://en.flossmanuals.net/pure-data/audio-tutorials/envelope-generator/
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jan 31, 2013, 07:07 pm

Hi. Can you add ADSR with your library sir? :)

http://en.flossmanuals.net/pure-data/audio-tutorials/envelope-generator/


Can't be done with toneAC as the ATmega controls all the switching.  In order to do ADSR (Attack-Decay-Sustain-Release) we should first create a sine wave instead of a square wave.  To do a sine wave, we need to interrupt the ATmega's PWM switching and adjust the duty, this takes valuable CPU cycles.  Further, to do ADSR we would need to also adjust the amplitude while the note is being played, further using limited CPU cycles.

All of this "could" be done on the ATmega.  But, I'm not sure what the frequency range would be.  It would also be well outside the scope of the toneAC library as it would be quite large, slow (CPU intense), and limit the frequency range by a huge amount.

Further, to really do ADSR correctly, it would need to be able to output the release phase of the previous note as the current note was starting the attack phase.  This really disqualifies the ATmega as an option.

You'd probably need a more powerful processor and one designed to output audio to really do what you're looking for effectively with any amount of fidelity.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Feb 15, 2013, 09:22 pm

What about a ToneAC page in the Playground section ?


toneAC in the playground:

http://playground.arduino.cc/Code/ToneAC

Tim
Title: Re: toneAC v1.1 - Twice the volume, higher quality, higher frequency, etc.
Post by: allenhuffman on May 06, 2013, 06:48 pm

I don't have the code handy - but waaaay back when I was kid, I remember playing around on my TRS-80 Color Computer with the PLAY command; there was a way, via using certain values (I think random notes played with very, very short durations) with a rapidly decreasing volume level (the CoCo had a 6 bit DAC - so there were 64 volume levels) - you could make an "explosion" or "gun" sound of sort...


Nice to see a CoCo reference here... I recently ported a 1983 Extended Color BASIC program I wrote on the CoCo over to Arduino C (line by line, as literally as possible) and I put in a placeholder for the CoCo's SOUND command. It only took tone and duration, though. There was no built in provision to do noise or volume.

But the Extended Basic PLAY command did allow volume and some great tricks could be done with it. I have been working on a PLAY command, and finding this thread is helpful as it sounds like it would be better to use than what I was working on.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: duldul123 on Aug 22, 2013, 02:14 pm
Hi ,
I was trying to use the toneAC library to produce ultrasound in the 20kHz range. Firstly, the library works brilliantly and thank you for that :) .
The only issue that i have been having is that sound isin't loud enough. I was using a standard 4 ohm buzzer and the sound output coming from it dosnt seem to be loud enough.

I tried using an Amp LM386 circuit to amplify the output .. described here http://web.mit.edu/6.s28/www/schematics/lm386.htm
But i then had to resort to use one of the 2 pins(9 or 10) which brought the clicking soung back. I have an Atmeg168.

Any you help me figure out how can i raise the output volume. I want t be able to detect the sound in a range of abt 10 m.

Lastly, Im fairly new to this :D
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 22, 2013, 05:26 pm

Hi ,
I was trying to use the toneAC library to produce ultrasound in the 20kHz range. Firstly, the library works brilliantly and thank you for that :) .
The only issue that i have been having is that sound isin't loud enough. I was using a standard 4 ohm buzzer and the sound output coming from it dosnt seem to be loud enough.

I tried using an Amp LM386 circuit to amplify the output .. described here http://web.mit.edu/6.s28/www/schematics/lm386.htm
But i then had to resort to use one of the 2 pins(9 or 10) which brought the clicking soung back. I have an Atmeg168.

Any you help me figure out how can i raise the output volume. I want t be able to detect the sound in a range of abt 10 m.

Lastly, Im fairly new to this :D



Humans can't hear well in the 20kHz range.  Also, many transducers don't produce much at that frequency either.  You would need an ultrasonic transducer designed for that range as well as a SPL meter to actually measure the sound output in that frequency range.  Basically, you need a different transducer and a different way to measure the volume (not your ears).

As far as the transducer, something like the PROWAVE - 250ST180 (http://www.newark.com/prowave/250st180/transducer-ultrasonic-tx-25khz/dp/98K8461) would work well, that's what I use.  Keep in mind, when you're creating a 20-25kHz sound, humans can't hear it at all.  So, while it may be able to output 105dB you won't be able to hear it at all.

To measure the volume at ultrasonic frequencies, you'll need a SPL meter.  Depending on your age and how many concerts you've gone to, the max you may be able to hear is probably in the 15kHz to 17kHz range.  Here's a Digital Sound Level Meter (http://www.radioshack.com/product/index.jsp?productId=12680845).  But, you can get older models on eBay for cheaper.

Hope that helps!

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: duldul123 on Aug 23, 2013, 10:27 am
Hey Thanks for that... im using ultrasound to transfer a code to a phone... So i actually do want to make sue humans cant here it.... 20k is used because the phone microphone has a die out beyond 22k... i been recording the ultrasound and using a fourier transform library on the phone that give be a power output. So i can measure if the sound is being generated. I will try using the transducer you'v mentioned.

Coming back to the amplifier question, how do i connect it to an amplifier. For the time being i am using an 8w 8 ohm buzzer that i got from a set of altec lansing speakers..

Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 23, 2013, 06:22 pm

Hey Thanks for that... im using ultrasound to transfer a code to a phone... So i actually do want to make sue humans cant here it.... 20k is used because the phone microphone has a die out beyond 22k... i been recording the ultrasound and using a fourier transform library on the phone that give be a power output. So i can measure if the sound is being generated. I will try using the transducer you'v mentioned.

Coming back to the amplifier question, how do i connect it to an amplifier. For the time being i am using an 8w 8 ohm buzzer that i got from a set of altec lansing speakers..


You can't make it 20kHz and expect humans to hear it.  We can't hear sounds generated at that frequency, it's at the very outer edge of what even a baby can hear, and even then it would be EXTREMELY soft.  Adults max out more in the 15kHz range.  Here's a website for you to test the maximum frequency you can hear (http://www.noiseaddicts.com/2009/03/can-you-hear-this-hearing-test/).

Therefore, it doesn't matter how big the amplifier is, you're not going to hear a 20kHz signal.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: duldul123 on Aug 28, 2013, 03:59 pm
Thanks tim.

Also.. I do not want to hear the sound. Infact i want to make sure that it cant be head hence i am using this frequency. The only reason i need the amplifier is so that i can increase the volume up to a point that the phone can read it . do a fourier transform and then try and distinguish a particular frequency from another and noise... I can presently do that with a standard audio amplifier circuit but the "Volume" or db value of those frequencies is not high to distinguish them from noise enough beyond a certain distance(1 Meter in the present case) i want to extend it till about 5 M.

So can you suggest how can i connect the two outputs from the Arduino to an amplifier circuit?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 28, 2013, 06:33 pm

Thanks tim.

Also.. I do not want to hear the sound. Infact i want to make sure that it cant be head hence i am using this frequency. The only reason i need the amplifier is so that i can increase the volume up to a point that the phone can read it . do a fourier transform and then try and distinguish a particular frequency from another and noise... I can presently do that with a standard audio amplifier circuit but the "Volume" or db value of those frequencies is not high to distinguish them from noise enough beyond a certain distance(1 Meter in the present case) i want to extend it till about 5 M.

So can you suggest how can i connect the two outputs from the Arduino to an amplifier circuit?


I think it would be easier and cheaper to use a transducer that's designed to output ultrasonic frequencies like the  PROWAVE - 250ST180.  Also, you would need mic that's also tailored for ultrasonic frequencies.  The fall-off from most standard transducers and mics are both quite high beyond 17kHz.  In other words, if you want to transmit and receive at ultrasonic frequencies you should be using drivers and mics that are designed for those frequencies.

Also, making an amp for an alternating signal like with toneAC would be a challenge.  You can't just use two 2N2222 transistors as you also need to alternate the ground as well, which flips between the two.  Not that it's impossible, just much more complex than a typical simple transistor circuit.  Keep in mind that toneAC is designed to be like a voltage amplifier without needing an actual circuit. In essence, it doubles the voltage, which increases the volume.

It would be much easier to just use a single transistor as an amp and keep the polarity always the same by using toneAC to drive just one pin instead of both.  In other words, just use half of the output of toneAC.  The frequency will be the same, and you'll get no volume benefit as it's not doubling the voltage.  But, you don't care about that if you're going to connect the output to a transistor tied to a larger voltage.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: MasterTom on Dec 02, 2013, 05:20 pm
Hello Tim,

thank you very much for toneAC. It is a big step from tone(). I want to use it not for making sound, but producing periodical pulses with different frequencies (5...500Hz). The frequency band is working fine, but when reducing the volume to less than 10 I can see that the pulse width is changing depending of the frequency. I think you did this to bring more power to frequencies that are below the resonance of the piezo? For my project it should be opposite: At lower frequencies I need shorter pulses.

I found the following line in your code "uint8_t _tAC_volume[] = { 200, 100, 67, 50, 40, 33, 29, 22, 11, 2 }; // Duty for linear volume control.". What is the meaning of this? Can I adapt this to realize my task?

Maybe it is possible to change it to something like: toneAC(freq, pulse_length,...) ?

Regards
Thomas

(Sorry for my english but I come from Germany)
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Dec 02, 2013, 06:06 pm

I found the following line in your code "uint8_t _tAC_volume[] = { 200, 100, 67, 50, 40, 33, 29, 22, 11, 2 }; // Duty for linear volume control.". What is the meaning of this? Can I adapt this to realize my task?

Maybe it is possible to change it to something like: toneAC(freq, pulse_length,...) ?


The _tAC_volume array modifies the duty cycle depending on the volume you set.  It's not linear because linear doesn't provide an accurate sound output level.  It needs to be more logarithmic to make it sound correct.

If you want more linear steps, you could simply modify the _tAC_volume array to something linear that works for your task.  Not sure how well this would work, as toneAC is designed for audio output.  I would say when using toneAC for other tasks you should always use full volume as the volume is a hack that just happens to work for speakers.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: MasterTom on Dec 03, 2013, 03:00 pm
Hello Tim,

I found a solution without changing your code. I just send a "volume" that is related to the frequency (5...10Hz -> Vol=1; 10...15Hz -> Vol=2 and so on). Over all, I have pulses with ~1ms width in the frequency range from 5 to 100 Hz. Frequencies less than 5Hz are forbidden, because the pulses are getting longer than 1ms. At frequencies higher than 100Hz the pulse length is getting smaller. But this is acceptable.

This was my goal  :-)

Thank you very much for your help.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: mwahahaha on Sep 01, 2014, 02:49 pm
Hi,

I've read that piezzo buzzers (magnetic ones too) can generate a "back emf" when they are heavily shocked (Arduino box falling on the ground for instance) which induces enough voltage and current to destroy the microcontroller output. One should add a diode in parallel to the buzzer to prevent this.

What do you think about this aspect?

Thanks in advance ^_^
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 02, 2014, 03:57 pm

Hi,

I've read that piezzo buzzers (magnetic ones too) can generate a "back emf" when they are heavily shocked (Arduino box falling on the ground for instance) which induces enough voltage and current to destroy the microcontroller output. One should add a diode in parallel to the buzzer to prevent this.

What do you think about this aspect?

Thanks in advance ^_^


A piezo can work just about as well as a microphone and a speaker.  So, a shock like dropping or tapping it can generate a large voltage pulse that will back-feed to the microprocessor.  While the voltage is high, the current is probably very low.  So even then, it's not very likely.  However, it's always good to provide some level of protection.

But, installing a diode is not the solution to this.  It's better to install a resistor to limit the back voltage.  With toneAC I suggest using a 100 Ohm resistor, which will limit the voltage and prevent a problem.  It's even more important NOT to use a diode with toneAC as it uses an alternating current and therefore the piezo will only ever "push" and never "pull", nullifying most of the advantages that toneAC has.

In any case, use about a 100 Ohm resistor inline with one of the pins when using a piezo buzzer.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: mwahahaha on Sep 02, 2014, 04:00 pm
Thanks a lot for this very accurate answer :)
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: polymorph on Sep 05, 2014, 07:36 pm
First off, thank you for writing this.

I have a few questions, if you don't mind.

What is the maximum reliable frequency this can output? I'm hoping that you'll say it can go up to 150kHz for RFID and some other projects I've got in mind.

Will it work on a Nano V3.0? I'm guessing that it can because both it and the Uno use the 328p.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 05, 2014, 10:18 pm

First off, thank you for writing this.

I have a few questions, if you don't mind.

What is the maximum reliable frequency this can output? I'm hoping that you'll say it can go up to 150kHz for RFID and some other projects I've got in mind.

Will it work on a Nano V3.0? I'm guessing that it can because both it and the Uno use the 328p.


The maximum frequency is VERY high, but depends on the speed you're clocked at.  Here's a link to the maximum frequency based on microcontroller clock speed:

https://code.google.com/p/arduino-tone-ac/wiki/toneAC_Frequency_Limits

So yes, toneAC will work at EXTREMELY high frequencies, even when running at lower clock speeds.  A Nano running at 16 Mhz can produce up to 2.66 MHz output with toneAC.  Even at 1 Mhz, you can generate a 166.66 kHz output.

And yes, Nano v3.0 will work just fine with toneAC, it works with all ATmega chips.  The Nano uses a ATmega328 so it's exactly like the Uno (uses pins 9 & 10).

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: polymorph on Sep 06, 2014, 12:36 am
Thanks!

Pardon my ignorance, but... what is the resolution? Specifically at the >100kHz range?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 10, 2014, 12:14 am

Thanks!

Pardon my ignorance, but... what is the resolution? Specifically at the >100kHz range?


The resolution is always 1 bit, it's a square wave.  That's all that toneAC or just about any other audio library will do on the Arduino, a square wave.

I assume you're trying to output a sound sample?  That would require an analog waveform, which the Arduino is not good at all at doing (nor could it ever hope to output anything of any quality at a 100kHz range).

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: polymorph on Sep 10, 2014, 04:51 am
My apologies, I was not clear.

I meant the frequency resolution. A quick look at the files I downloaded would indicate that the resolution at lower frequencies the frequency resolution is better than at some point where the prescaler must change, and there are larger steps in the frequency.

Kind of like how millis() is milliseconds and has an actual resolution of 1ms, but micros(), although it is microseconds and can be given any number, has an actual resolution of 4us.

Actually I'm looking to use this for an RFID card reader in the 125kHz to 134kHz range. I thought I might try some frequency hunting to look for the tag's actual resonant frequency.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 11, 2014, 07:07 pm

My apologies, I was not clear.

I meant the frequency resolution. A quick look at the files I downloaded would indicate that the resolution at lower frequencies the frequency resolution is better than at some point where the prescaler must change, and there are larger steps in the frequency.

Kind of like how millis() is milliseconds and has an actual resolution of 1ms, but micros(), although it is microseconds and can be given any number, has an actual resolution of 4us.

Actually I'm looking to use this for an RFID card reader in the 125kHz to 134kHz range. I thought I might try some frequency hunting to look for the tag's actual resonant frequency.


That's correct, the steps between frequencies gets larger as the frequency increases.  In about the 125 kHz to 134 kHz range, there will be these frequencies: 123,077, 125,000, 126,984, 129,032, 131,148, 133,333 & 135,593 Hz (basically about a 2 kHz step).  As these are based on the clock frequency of the microcontroller, they will also be off depending on your oscillator and ambient temperature (which is why I gave one below and one above the range you're looking for).

Basically, toneAC can generate frequencies in that range, but if accuracy is important, the ATmega is not an ideal platform as it won't be very granular in frequency and it will vary from board to board based on the microcontroller timer.

Also, I would suggest using the frequencies listed above as they will calculate exactly to a different frequency.  For example, if you told toneAC to generate a 127,000 Hz frequency, it would generate a 129,032 Hz frequency instead.  So, you probably won't get the results you're looking for.  In other words, you should use the above frequencies with toneAC and not any in-between.

I hope this answers your question better.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: polymorph on Sep 12, 2014, 12:49 am
Yes, that answers my questions. Those are exactly the sorts of details I was looking for. Thank you!
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: Peter_n on Dec 26, 2014, 10:49 am
toneAC with Dickson charge pump

I wanted to set my 433MHz TX module to 5V or 12V, to be able to use it at maximum and reduced power.
The Dickson charge pump seems a good solution for that, but it needs two pins with alternating signals.
That is why I decided to use the toneAC, and it works very well. Without load the output is 14V.

The capacitor at the end is 47uF and it is too small. The TX module empties it in 10ms.
The extra bypass diode is to have a voltage close to 5V when the charge pump is not used.
The 470 ohm resistors are to reduce the peak currents, they can be 120 ohm as well. I need to reduce the peak current, because I have a sensitive 433MHz receiver on the same board as well.

The name of the circuit can be "voltage multiplier" or "voltage tripler" or "charge pump" or something like that. This specific circuit is a "Dickson charge pump".

Update: The output is very weak. I changed the resistors from 470 ohm into 220 ohm.
Test with a load of 10k (about 1mA load):
1 kHz : 4.97 V
2 kHz : 7.07 V
5 kHz : 9.42 V
10 kHz : 10.36 V
20 kHz : 10.71 V
50 kHz : 10.83 V
100 kHz : 10.84 V
200 kHz : 10.84 V
500 kHz : 10.81 V
1 MHz : 10.74 V
2 MHz : 10.41 V
A 1000uF capacitor is charged to 13V in 10 seconds. That is enough for the TX module for 300 ms (50% duty cycle) and during that, the voltage is lowered to 10V. That is enough to switch a light on an off, but not for an alarm. I could have used two or three 5V TX modules instead, with different TX power levels.
Title: 8bit OC0A/B & TCNT0 - possible?
Post by: protoc0l on Mar 06, 2015, 08:18 pm
Great library!  I'm driving a piezo from a 3v cell, so this really helps!

On an Attiny44a, the OC1A/B pins are shared with MOSI/MISO, which works (and piezo chirps when uploading :) ) with the changes I made to the original code.

I need to use the OC0A/B & TCNT0 instead, which is only 8bit, but I need to drive @ ~4000hz, is it possible?  

Can I chain or loop the timer or interrupt to get ~4000hz? Is there an example of this somewhere?

thx!
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Mar 06, 2015, 08:58 pm
Great library!  I'm driving a piezo from a 3v cell, so this really helps!

On an Attiny44a, the OC1A/B pins are shared with MOSI/MISO, which works (and piezo chirps when uploading :) ) with the changes I made to the original code.

I need to use the OC0A/B & TCNT0 instead, which is only 8bit, but I need to drive @ ~4000hz, is it possible? 

Can I chain or loop the timer or interrupt to get ~4000hz? Is there an example of this somewhere?

thx!
toneAC uses timer 1 (OC1A/B) because that timer has the ability to do the automatic alternating push/pull.  Other timers won't allow this.  However, I also have a toneAC2 library which should work quite nicely for your needs.  That is, if you're using a ATmega and not an ATtiny.  Why use a ATtiny anyway?  The price is about the same, the ATmega has lower power modes, and the ATmega is available in a smaller footprint.  I really find no reason for the ATtiny.

Anyway, if it must be an ATtiny for whatever reason, just create your own loop at whatever frequency you want that flips two pins from on to off and vise versa.  That would be very simple and easily run at 4kHz.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: protoc0l on Mar 06, 2015, 10:10 pm
... Why use a ATtiny anyway?  The price is about the same, the ATmega has lower power modes, and the ATmega is available in a smaller footprint.  I really find no reason for the ATtiny.
Thx for reply, not really married to the attiny, but I do need something that can run @ ~2v, and I can get the t44a for 80 cents (@10). I did see some atmega8's around the same price, but I think the vcc was higher. Will take another look.

Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: Peter_n on Mar 06, 2015, 10:19 pm
2V is low. The ATmega8L starts at 2.7V.

I did see a trick once ( perhaps on Hackaday ) that an ATtiny or ATmega starts at a low voltage and increased its own voltage with a voltage doubler to run normal.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Mar 06, 2015, 11:16 pm
Thx for reply, not really married to the attiny, but I do need something that can run @ ~2v, and I can get the t44a for 80 cents (@10). I did see some atmega8's around the same price, but I think the vcc was higher. Will take another look.


The ATmega328P can run at 1.8volts and when in low power mode use only 1μA (microamp).  I have a couple projects that I've been running for 3 years from a single set of batteries, and the batteries still have a lot left in them.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: GizmoGarden on Sep 14, 2015, 09:05 pm
Question about race conditions in toneAC2: I was seeing some odd behavior in the standard tone() function that I suspect is due to a race condition between the interrupt handler and tone() inself. The doc says you can call tone() while a previous tone is playing and it will just update the frequency, but tone() can be interrupted at any point by its own interrupt, hence the potential race. In searching the web to see if others had observed this I came across toneAC and toneAC2, and intend to use your library. I don't think I can use toneAC because I need the servo library which uses timer1 on my Uno, but toneAC2 should be just the ticket. So my question: Is there any potential race condition if toneAC2 is called while a previous tone is playing? What is the intended behavior?

The main reason I want to use toneAC2 is to take advantage of "twice the volume". I'm currently doing that with tone() using the following push-pull inverter, but software is preferable to hardware:
(http://www.tidewater.net/~bsilver/GizmoGarden/PiezoAmp.png)
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 14, 2015, 10:06 pm
Question about race conditions in toneAC2: I was seeing some odd behavior in the standard tone() function that I suspect is due to a race condition between the interrupt handler and tone() inself. The doc says you can call tone() while a previous tone is playing and it will just update the frequency, but tone() can be interrupted at any point by its own interrupt, hence the potential race. In searching the web to see if others had observed this I came across toneAC and toneAC2, and intend to use your library. I don't think I can use toneAC because I need the servo library which uses timer1 on my Uno, but toneAC2 should be just the ticket. So my question: Is there any potential race condition if toneAC2 is called while a previous tone is playing? What is the intended behavior?

The main reason I want to use toneAC2 is to take advantage of "twice the volume". I'm currently doing that with tone() using the following push-pull inverter, but software is preferable to hardware:
(http://www.tidewater.net/~bsilver/GizmoGarden/PiezoAmp.png)
You will need to use toneAC2 as toneAC will conflict with the servo library.  That's unfortunate as toneAC is faster, more accurate, etc.

Anyway, I don't think toneAC or toneAC2 will create a race condition because I set the new tone end before setting the new timer settings and monitor the state as well. The intended behavior if you call toneAC/toneAC2 while a current tone is playing is that the tone will simply change.  toneAC/toneAC2 resets the counter top in an overflow situation which the tone library does not do.  Also, if you specify a length, toneAC2 will run in blocking mode so it would be impossible to call toneAC2 again (although, blocking mode probably won't work with your project).

The toneAC2 library is small, fairly straight-forward, and commented in detail.  You should be able to review toneAC2.cpp to see if there's any potential issues.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: GizmoGarden on Sep 15, 2015, 04:01 am
I think I do see a race condition in toneAC2 (easy to fix), but tell me what you think. The interrupt handler can call noToneAC2 and thereby change TCCR2A, TCCR2B, and _pinMask1. Suppose that a tone is just ending when toneAC2 is called to start a new one. If the tone-ending interrupt occurs between the lines in toneAC2 that set OCR2A and that disable the interrupt (TIMSK2), then some or all of _pinMask1, TCCR2A, and TCCR2B will be placed into an invalid state. If you simply move the interrupt disable somewhere before the "if (_pinMask1 == 0), the race condition is impossible.

Of course this race bug is rather unlikely to occur, but that is what makes race conditions so nasty and difficult to debug.

And of course I could be wrong here--you know both the code and the timers better than I do.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: GizmoGarden on Sep 15, 2015, 04:57 am
Now that I look at the code again, I think there is no race condition, but the analysis is subtle. Near the beginning of toneAC you set _tAC2_time. If this unsigned long is set correctly, it will prevent the race condition about which I was concerned in my previous post, since the interrupt handler would then not call noToneAC2. But an unsigned long is four bytes, and setting it on an 8-bit processor is not an atomic operation and can therefore be interrupted. If it is interrupted partway through setting all four bytes, the interrupt handler will run with an invalid value in _tAC2_time, and may or may not call noToneAc2. But I think either case is harmless because nothing that the interrupt handler can change has been read yet by the rest of tomeAC2. Still, I'd move the interrupt disable eariler in toneAC2.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 15, 2015, 02:46 pm
Now that I look at the code again, I think there is no race condition, but the analysis is subtle. Near the beginning of toneAC you set _tAC2_time. If this unsigned long is set correctly, it will prevent the race condition about which I was concerned in my previous post, since the interrupt handler would then not call noToneAC2. But an unsigned long is four bytes, and setting it on an 8-bit processor is not an atomic operation and can therefore be interrupted. If it is interrupted partway through setting all four bytes, the interrupt handler will run with an invalid value in _tAC2_time, and may or may not call noToneAc2. But I think either case is harmless because nothing that the interrupt handler can change has been read yet by the rest of tomeAC2. Still, I'd move the interrupt disable eariler in toneAC2.
I set _tAC2_time early to avoid a race condition.  Also, stopping the timer earlier if tones are playing quickly can cause a "crackle" sound as we're terminating the tone before starting a new tone with too much computation between (that's why the timer stop and start are so close to each other with only a single if/else statement between them.

I don't believe having _tAC2_time as a long int could also create a race condition.  I do, however see two other cases where a race condition could happen.  One I corrected in my development code already.  The other has to do with the millis() rolling over at 0xFFFFFFFF.  It's programmed to deal with the rollover.  But, there could be a very rare case where _tAC2_time is set to a very high value and the interrupt misses it before millis() rolls over.  Say that _tAC2_time is set to 0xFFFFFFFE and the tone frequency is set to 100Hz.  ISR(TIMER2_COMPA_vect) would only be called once every 10ms and it would be very possible that millis() could wrap to 0x0 and never be greater than _tAC2_time to cause the tone to stop.  This would be highly rare and the solution would add bulk inside the ISR(TIMER2_COMPA_vect) which isn't a good idea either.

In any case.  All of what we're talking about is when we're using toneAC2 to control the length of the tone.  Another way of doing it is to not specify the duration which makes toneAC2 just play the tone forever.  Then, you could use your sketch to decide when to stop the tone.  Depending on your sketch, this may be a good way of avoiding any possible problem.

Tim
Title: Re: toneAC with regular 8Om speaker + volume question
Post by: piif on Dec 20, 2015, 05:41 pm
Hello,
 I work on a "home made" sound player project, using a regular 8ohms solenoid speaker and want to generate "ping" notes.
I found your library and your AC trick was exactly what I wanted to make louder sound.

But I've a problem with volume control : on full volume (50% duty cycle) the sound is ok, but when I decrease it, it becames twanging like a duck and thus "ping" effect sounds really ugly.

Is this a known problem ? I don't understand why of shorter duty cycle distorts sound so much ?

I tried another solution, by connecting speaker to a timer for frequency and other speaker end to another timer (with higher frequency) onto which I change duty cycle to simulate a variable low voltage.
Result is fine, but in this way, i can't use your AC trick thus volume is less loud

By the way, I've another question :
With a 50% duty cycle sound, the signal is like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruWTJwVWplQzNCdzg)
(yes, my oscilloscope comes from another century ...)
Top line shows one output pin, bottom line shows other pin inverted, thus speaker receives 0 -> +5 at beginning then +5 -> 0. That's ok.


With lower volume, the signal becames like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruYXFyeVZGaVNxT1k)
thus, +5 -> 0 90% of time, then 0 -> +5 during remaining 10%

Shouldn't it be better to have something like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruZGM3MHE3Q0kySDg)
thus 0 -> 0 90% of time, then 5 -> 0 during 5%, and then 0 -> 5 during remaining 5%

I achieved this by setting OCRxA to (top / volume) and OCRxB to (top - (top / volume)), and compare flags to "normal"
Thus, A is high during the beginning of timer count, then low, then B is set to high during last steps and returns low at end.
The result sounds not exactly the same, but is still twanging, thus it doesn't solve my problem, but I'd like to have your opinion in this signal generation method ?

Thanks in advance for any help ...
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Dec 21, 2015, 06:11 pm
Hello,
 I work on a "home made" sound player project, using a regular 8ohms solenoid speaker and want to generate "ping" notes.
I found your library and your AC trick was exactly what I wanted to make louder sound.

But I've a problem with volume control : on full volume (50% duty cycle) the sound is ok, but when I decrease it, it becames twanging like a duck and thus "ping" effect sounds really ugly.

Is this a known problem ? I don't understand why of shorter duty cycle distorts sound so much ?

I tried another solution, by connecting speaker to a timer for frequency and other speaker end to another timer (with higher frequency) onto which I change duty cycle to simulate a variable low voltage.
Result is fine, but in this way, i can't use your AC trick thus volume is less loud

By the way, I've another question :
With a 50% duty cycle sound, the signal is like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruWTJwVWplQzNCdzg)
(yes, my oscilloscope comes from another century ...)
Top line shows one output pin, bottom line shows other pin inverted, thus speaker receives 0 -> +5 at beginning then +5 -> 0. That's ok.


With lower volume, the signal becames like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruYXFyeVZGaVNxT1k)
thus, +5 -> 0 90% of time, then 0 -> +5 during remaining 10%

Shouldn't it be better to have something like this :
(https://drive.google.com/uc?export=download&id=0B0YxeBdRV-ruZGM3MHE3Q0kySDg)
thus 0 -> 0 90% of time, then 5 -> 0 during 5%, and then 0 -> 5 during remaining 5%

I achieved this by setting OCRxA to (top / volume) and OCRxB to (top - (top / volume)), and compare flags to "normal"
Thus, A is high during the beginning of timer count, then low, then B is set to high during last steps and returns low at end.
The result sounds not exactly the same, but is still twanging, thus it doesn't solve my problem, but I'd like to have your opinion in this signal generation method ?

Thanks in advance for any help ...
The "volume" is a bit of a hack for sure.  It changes the duty cycle, but it's not ideal.  Basically, the goal of toneAC was to create a "push/pull" for the speakers using the built-in timers of the ATmega which would make it high accuracy and very fast.  The duty cycle allowed me to adjust the volume so I added it to the library.

I don't have an oscilloscope to test what the output of toneAC is.  But for me, it does change the volume and doesn't sound like a duck.  I'm using only piezo transducers, so maybe that's the difference?  I would be concerned about your modification if the pins are ever both high.

Honestly, I wouldn't use the volume option in toneAC.  It "works" but not well.  It's a bonus only.  toneAC was really designed to be driven at 100% to produce a higher sound output, high accuracy, and the ability to do high frequencies.

The reason it still doesn't sound right with your modification is probably because the pins are out of sync.  Maybe if I had an oscilloscope I could mess around with this.  But I'm kind of out of luck until such time.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: piif on Dec 21, 2015, 10:53 pm
Thanks for your answer.
I've to find a piezo speaker to do the test, but i fear sound will not be loud enough.
My goal is to make a door bell, thus it have to be eared from everywhere in my house ...
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Dec 22, 2015, 04:47 pm
Thanks for your answer.
I've to find a piezo speaker to do the test, but i fear sound will not be loud enough.
My goal is to make a door bell, thus it have to be eared from everywhere in my house ...

The best solution to this is using a simple amp (a transistor will do).  The output of the ATmega just isn't enough to drive a cone speaker at type of a loud volume.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: piif on Dec 29, 2015, 10:12 pm
The best solution to this is using a simple amp (a transistor will do).  The output of the ATmega just isn't enough to drive a cone speaker at type of a loud volume.

Tim
Hi,
  that's what i did, but to drive the speaker with toneAC, I needed to amplify signal both ways, thus i have to use a H-bridge.

As my volume troubles were not solved, I finally used my "second timer" idea, and connected it to the "enable" pin of a H-bridge component. I tried to build my own with Darlingto transistors, but never achieve something working (i think i will never understand how to deal with those weird components !) thus i took a 754410

The final result is working and installed on my door since today !
I will post detail soon (in french, sorry, but source code is english commented)
Thanks for your help
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Dec 29, 2015, 10:16 pm
Hi,
  that's what i did, but to drive the speaker with toneAC, I needed to amplify signal both ways, thus i have to use a H-bridge.

As my volume troubles were not solved, I finally used my "second timer" idea, and connected it to the "enable" pin of a H-bridge component. I tried to build my own with Darlingto transistors, but never achieve something working (i think i will never understand how to deal with those weird components !) thus i took a 754410

The final result is working and installed on my door since today !
I will post detail soon (in french, sorry, but source code is english commented)
Thanks for your help
If using an amp you don't need to use toneAC.  The standard tone or one of my other tone libraries will work (like NewTone (https://bitbucket.org/teckel12/arduino-new-tone/wiki/Home)).

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: piif on Dec 29, 2015, 11:17 pm
I will post detail soon (in french, sorry, but source code is english commented)
the story (https://docs.google.com/document/d/1IuG2oHFJ5zJzwFW_nQGuirxd6ZcFn5cequqiLHnNeQE/edit?usp=sharing)
the source code (https://github.com/piif/ArduinoTests/blob/master/bell.ino)
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: freakolowsky on Feb 16, 2016, 03:28 pm
Hey, not sure if i'm doing something wrong or what ...

i'm using a Micro (ATMega32U4) and have a buzzer connected on pins 9&10. Positive pin on the speaker has a 100 Ohm resistor on it ...

first of all volume (at 10) is equal if not even lower than when using default tone. If i switch pins the volume gets even lower.

As i said ... not sure what i'm doing wrong.

PS: i also have a switch on D12(pullup) and LCD 16x2 on D2-D8

any ideas.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: mariemarolleflyvop on Apr 26, 2016, 11:04 am
Hey, I was wondering, is there a way to make ToneAC work with a sensor and one LED?
Fx. you activate the sensor, the LED will turn on and a sound from ToneAC will play. I already did this with the normal Arduino settings and a speaker but to be honest am I not quiet so skilled at Arduino.
I want to use ToneAC because of the improved volume.
Thanks a lot :-)
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: alberio on Jul 07, 2016, 04:32 am
Use the tone function and it works perfectly fine! It's a great library, I use only one of the pins in ATmega328P and works well. I would like to release one of the pins for me to wear with something else in my code?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jul 07, 2016, 03:15 pm
Use the tone function and it works perfectly fine! It's a great library, I use only one of the pins in ATmega328P and works well. I would like to release one of the pins for me to wear with something else in my code?
toneAC needs to use 2 pins or it's really worthless using ToneAC at all.  If you're using toneAC because it uses timer 1, it's better to use my Arduino New Tone library (https://bitbucket.org/teckel12/arduino-new-tone/wiki/Home) instead, as it only uses one pin.  But, maybe I don't understand the question.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jul 07, 2016, 03:15 pm
Hey, I was wondering, is there a way to make ToneAC work with a sensor and one LED?
Fx. you activate the sensor, the LED will turn on and a sound from ToneAC will play. I already did this with the normal Arduino settings and a speaker but to be honest am I not quiet so skilled at Arduino.
I want to use ToneAC because of the improved volume.
Thanks a lot :-)
Yes, you can do that with toneAC.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Jul 07, 2016, 03:17 pm
Hey, not sure if i'm doing something wrong or what ...

i'm using a Micro (ATMega32U4) and have a buzzer connected on pins 9&10. Positive pin on the speaker has a 100 Ohm resistor on it ...

first of all volume (at 10) is equal if not even lower than when using default tone. If i switch pins the volume gets even lower.

As i said ... not sure what i'm doing wrong.

PS: i also have a switch on D12(pullup) and LCD 16x2 on D2-D8

any ideas.
It's probably the buzzer being used.  Some buzzers are a fixed frequency and you just supply voltage to them to buzz.  Those would not be compatible with toneAC (nor with any other sound library) as they don't need a library, they just buzz when voltage goes to them.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: sid1202 on Aug 19, 2016, 03:16 am
Hi there,

I'm using a Adafruit Feather32U4 with a ATMega32U4 and I get compiling errors when I try to use toneAC2 Pin 9 floats at around 2v so we can measure battery voltage, so I can't use toneAC. If I change the board to the Uno it compiles fine. Any suggestions ?

Sid
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 20, 2016, 12:03 am
Hi there,

I'm using a Adafruit Feather32U4 with a ATMega32U4 and I get compiling errors when I try to use toneAC2 Pin 9 floats at around 2v so we can measure battery voltage, so I can't use toneAC. If I change the board to the Uno it compiles fine. Any suggestions ?

Sid
First off, it's impossible to use toneAC2 on a ATMega32U4 microcontroller as the ATMega32U4 doesn't have timer 2 and that's exactly what the "2" in toneAC2 stands for.  Basically, you're trying to use a feature that doesn't exist on the ATMega32U4 so it's impossible.

However, there's still hope for using toneAC on your platform.  It's very possible that toneAC doesn't use pins 9 and 10 on your platform.  9 & 10 is just what Arduino uses.  For example, on the Teensy 2.0 (which is  ATMega32U4 based) it has pins 14 & 15 mapped to the timer 1 pins.  I suggest you investigate this first as to which pins are mapped to what timers on your platform as they could be totally different.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: sid1202 on Aug 21, 2016, 07:06 pm
Thank you. I think I miss understood the Timers on the Atmega processors. It's starting to make sense but it is still foggy.

Trying to learn everything at once is hard lol...

Regards,

Sidney
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 22, 2016, 11:26 pm
Thank you. I think I miss understood the Timers on the Atmega processors. It's starting to make sense but it is still foggy.

Trying to learn everything at once is hard lol...

Regards,

Sidney
I looked at the Feather pinouts and it appears that toneAC would use pins 9 & 10.  Not sure why there would be a problem using pin 9 on the Feather, it shouldn't have anything on it unless you have a sketch that's doing something else with the pin.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: q2dg on Sep 07, 2016, 04:38 pm
One stupid question...Are ToneAC, ToneAC2, New-Tone... libraries compatible with Arduino Zero/MKR1000? And with Genuino 101? I've searched in bitbucket's wiki but I haven't found anything. Thanks a lot.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 07, 2016, 06:31 pm
One stupid question...Are ToneAC, ToneAC2, New-Tone... libraries compatible with Arduino Zero/MKR1000? And with Genuino 101? I've searched in bitbucket's wiki but I haven't found anything. Thanks a lot.
ToneAC, ToneAC2 and NewTone are absolutely NOT compatible as all libraries use ATmega AVR timers which Arduino hasn't implemented compatibility for their ARM based processors.  As there's no standard with Arduino ARM based processors, a custom library would need to be developed for each ARM platform (which is out of scope for the ToneAC project).

Further, ARM based platforms may times have better methods to generate sound (like sine waves).  So in reality, ToneAC/ToneAC2/NewTone is probably not the best thing to use with ARM anyway as there's probably a better solution.

The only "tone" library of mine that would work with an ARM processor is TimerFreeTone as it doesn't use timers and therefore can easily implement compatibility for non-AVR processors.  But again, TimerFreeTone probably isn't the best library to use for an ARM processor as the advantages of TimerFreeTone are really not important to an ARM based project.

Basically, EVERY Arduino library that uses times won't work with ANY non-AVR (for example ARM) based microcontroller.  There's no need to look for a note about this, consider no libraries to work on your platform as most libraries use timers.  This isn't specific to ToneAC or my libraries, it's how it works.  Also, most of my libraries were started before there was ARM based platforms, so concern with non-AVR compatibility was never part of the scope of the project.  Nor do I have these Arduino non-AVR platforms to care about making a custom version for each.

In a nutshell, don't count on ANY libraries working with non-AVR microcontrollers.  That's why I stay away from non-AVR microcontrollers (the Teensy 3.x is the exception because Paul Stoffregen gets it).

Tim
Title: Can the SPI pin conflict on pro mini be avoided?
Post by: franck102 on Mar 28, 2017, 07:36 pm
Hi,

Great library, unfortunately it uses pin 10 which is one of the SPI pins I need to communicate with an RFM69 module.

If I go inside the source code can I patch the code to use another PWM pin (seems like 1 & 9 would work for me for example)?

Thanks!
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: TryBit on Mar 29, 2017, 12:18 am
I am getting the below errors when compiling a simple the simple code.



Here's the code

#include <toneAC.h>


void setup() {
 pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
 pinMode(5, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
 pinMode(0, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
 digitalWrite(LED_BUILTIN, LOW);
 digitalWrite(5, LOW);
 digitalWrite(0, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                   // but actually the LED is on; this is because
                                   // it is acive low on the ESP-01)
 delay(1000);                      // Wait for a second

 digitalWrite(LED_BUILTIN, HIGH);
 digitalWrite(5, HIGH);
 digitalWrite(0, HIGH);  // Turn the LED off by making the voltage HIGH
 delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}



Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: franck102 on Mar 29, 2017, 12:33 pm
Hi,

Great library, unfortunately it uses pin 10 which is one of the SPI pins I need to communicate with an RFM69 module.

If I go inside the source code can I patch the code to use another PWM pin (seems like 1 & 9 would work for me for example)?

Thanks!
I just found the toneAC2 which addresses this exact problem... sorry :)
Franck
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Mar 29, 2017, 06:17 pm
Hi,

Great library, unfortunately it uses pin 10 which is one of the SPI pins I need to communicate with an RFM69 module.

If I go inside the source code can I patch the code to use another PWM pin (seems like 1 & 9 would work for me for example)?

Thanks!
No, toneAC uses certain pins because that's the pins the timer uses. If you need different pins, that's what toneAC2 is for.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Mar 29, 2017, 06:34 pm
I am getting the below errors when compiling a simple the simple code.



Here's the code

#include <toneAC.h>


void setup() {
 pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
 pinMode(5, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
 pinMode(0, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
 digitalWrite(LED_BUILTIN, LOW);
 digitalWrite(5, LOW);
 digitalWrite(0, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                   // but actually the LED is on; this is because
                                   // it is acive low on the ESP-01)
 delay(1000);                      // Wait for a second

 digitalWrite(LED_BUILTIN, HIGH);
 digitalWrite(5, HIGH);
 digitalWrite(0, HIGH);  // Turn the LED off by making the voltage HIGH
 delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}




It would probably be beneficial if you included in your message that you're running a non-Arduino non-AVR platform "Adafruit HUZZAH ESP8266".  You can expect many compatibility issues trying to use Arduino libraries with non-AVR microcontrollers. 

Anyway, see the toneAC compatibility section for a list of what microcontrollers work with toneAC:

toneAC compatibility (https://bitbucket.org/teckel12/arduino-toneac/wiki/Home#!compatibility)

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: mureytasroc on Apr 20, 2017, 04:58 am
Also, making an amp for an alternating signal like with toneAC would be a challenge.  You can't just use two 2N2222 transistors as you also need to alternate the ground as well, which flips between the two.  Not that it's impossible, just much more complex than a typical simple transistor circuit.  Keep in mind that toneAC is designed to be like a voltage amplifier without needing an actual circuit. In essence, it doubles the voltage, which increases the volume.

Tim
If you are using toneAC for the sound quality and still want an amplifier for it a simple solution will be two NPN transistors - on both connect the emitter to ground, the collectors to the two poles of the speaker (choose a "positive rail" transistor and a "negative" one and connect each's base to its respective pole of the speaker), and the base through a current limiting resistor (see below for value) to D9 (for the transistor on the "negative" side of the speaker) and through a current limiting resistor (see below for value) to D10 (for the "positive" side transistor).  





The final touch is to add two pullup resistors on the collectors of both the transistors (the resistance values of these will limit the current sufficiently by the way so you don't need that 100ohm recommended resistor on the positive speaker pole).   To determine these pullup values take 1/2 the vcc (the "+" voltage) of the circuit (should be the same as the high voltage of the digital pins - 3.3 on some arduinos, 5v on most) (5*1/2=2.5 volts).   The current through each resistor can be determined with:

v=ir (ohm's law)
(v/2)=i*r
i=v/(2r)

r is resistance of the pullup (ohms), i is current through the pullup (amps), v is vcc (volts)

So the current through each resistor is v/(2r) r being the resistance of the pullup.   Multiply this by two because you have 2 resistors (one on each collector) supplying current to the speaker - now we get v/r for the current passing through the speaker (r being the resistance of each individual pullup - they should be the same (the math gets more complicated if they aren't)

We can then plug this watt's law to determine the power output of this amp:

p=iv (watt's law)
p=v*v/r

p being power (watts)

now if you want to pass 1.5 watts through a speaker (say if its rated for 2 watts) you plug 1.5 in (and lets use 5v as vcc - we'll pretend we are using an arduino uno)

p=v*v/r
1.5=5*5/r
r=25/1.5
r=16.67 ohms

So you should have each resistor be 16.67 ohms - remember the resistors should have an adequate power rating ( at least 1/2 the speaker wattage (>(v*v)/(2*r) each so >0.75 watts each if the speaker wattage is 1.5 watts - you should have some buffer room though)

**IF YOU COULDN'T FOLLOW THAT, USE THIS EQUATION: resistance=positive voltage*positive voltage/desired power through the speaker (for an uno: r=25/desired power)




Now for the value of the resistor between the digital pins on the bases of the transistors (they should both be the same as you might have guessed) referred to as base res in the schematic below.   We will first start with the desired "collector current" flowing through the transistor (the current that the transistor is giving to our speaker in plain english); we want:

("collector current" rating of the transistor (Ic max))>i>v/(2r)
i being the most "collector current" that the transistor will let through (Ic) and r being the PULLUP RESISTOR ON THE COLLECTOR (we want the current flowing through the transistors to be able to match that of the pullup resistors (v/(2r); calculated above) so it should be designed to handle more current than the resistors will draw - this current must also be below the specified collector current rating for the transistor - choose your transistor wisely)

when choosing a transistor consider: Ic max (see above) and Max power rating (above v*v/(2r), r  being the pullup resistor value)

So now look at your chosen transistor datasheet and find a chart or a graph that specifies "current gain" for a given collector current (current going through the transistor) - the collector current will be the "i" value you chose above (greater than v/(2r) and less than the Ic max rating) and find the "current gain" at that given value.   Now plug the current gain and  the i value (collector current; Ic) into this equation:

Base current= Ic/current gain

Now find the Emitter-base voltage (Vebo) specified in the datasheet and the required voltage drop across the resistor will be: vcc ("+" voltage of the system; 5v if using an uno) - Vebo

So take that voltage drop and plug it into ohms law to find the resistor value:
v=i*r
(vcc-Vebo)=(Ic/(current gain))*(r)
r=Ic/((vcc-Vebo)*(current gain))

Ic was chosen by you above (the "i" value), the current gain was found in the datasheet with Icm vcc was determined at the beginning of this tutorial, and Vebo was found in your transistor dtasheet as well.   Now you have an r value for teh resistors on the bases of your transistors.   Power rating of these resistors are equal to:

power = Ic*(vcc-Vebo)/(current gain) - this will usually be negligible though so a 1/4 watt resistor should be fine in general

**IF YOU COULDN'T FOLLOW THAT, A 1/4 watt resistor with a VALUE OF 2.2k ohms on each transistor base should be fine***




Enjoy unlimited volume - REMEMBER SPEAKER POWER RATING, RESISTOR POWER RATING (On bases and on pullups), AND TRANSISTOR POWER RATING AND CURRENT RATING to not break stuff

Here is a schematic of the circuit:

                                    v *NPN bjt transistors (EBC = emitter, base, collector)*

                                  <E>----GND
D9--<base res>--<B>
                                  <C>---|------<Resistance value chosen with above math>----VCC
                                             |
                                             ------ negative pole of the speaker (-)
                             GND                                                                   >>>> LOUD SOUND
                              ^--<E>   |------positive pole of the speaker (+)
D10--<base res>--<B>     |
                                  <C>---|------<Resistance value chosen with above math>----VCC
                                           

Please correct me if I have made any mistakes in my explanation but I have tested this circuit and it works.
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: AdnanSamra on Aug 24, 2017, 11:20 am
hi every one

can i use toneAC to get three cut identical frequencies and then stop like this

toneAC(3000);
delay(1000); toneAC(3000); delay(1000); toneAC(3000);
 }
 toneAC(0); // Turn off toneAC, can also use noToneAC().

 while(1); // Stop (so it doesn't repeat forever driving you crazy--you're welcome).
     
   
    }
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: robtillaart on Aug 24, 2017, 03:32 pm
Yes, such a sketch could be tested within a minute.

What makes you think it cannot be done?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: AdnanSamra on Aug 25, 2017, 02:58 am
well, I thought it could be done, but never the less i wanted to make sure because i have not got any Arduino board yet , I am very new to this domain in fact,
thank you very much for your help

another question please is suppose that I have a code that would light a led through the digitalWrite (pin#, High) & after it there is the tone code as mentioned in my post earlier, Led will stay on even when micro controller is carrying on the tone code? because I was surfing through the forum I noticed that every one is mentioning that the micro controller does not perform tasks in parallel but rather in high speed that the user would not notice the difference in many applications , so if the LED will stay on even during the Tone process is it because of this or because the fact that I told it to switch on the led by digitalWrite order and the pin stayed on the high state ?

thank you all for all the help,
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 25, 2017, 05:40 am
well, I thought it could be done, but never the less i wanted to make sure because i have not got any Arduino board yet , I am very new to this domain in fact,
thank you very much for your help

another question please is suppose that I have a code that would light a led through the digitalWrite (pin#, High) & after it there is the tone code as mentioned in my post earlier, Led will stay on even when micro controller is carrying on the tone code? because I was surfing through the forum I noticed that every one is mentioning that the micro controller does not perform tasks in parallel but rather in high speed that the user would not notice the difference in many applications , so if the LED will stay on even during the Tone process is it because of this or because the fact that I told it to switch on the led by digitalWrite order and the pin stayed on the high state ?

thank you all for all the help,
Not even your phone, laptop or desktop PC can technically do multiple things at the same time, it just seems that it can. Same goes for the Arduino. But just like other computers, you can seemingly do multiple things at the same time. Because toneAC uses timers it kinda works in the background, so it's like multitasking.

Basically, you shouldn't have these concerns. You need an Arduino and use it, it will all make more sense.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: AdnanSamra on Aug 25, 2017, 11:44 pm
thank you Tim,

to tell you the truth I am not a bit concerned about this as long as tasks that I assign the controller to do do not interfere or interrupt each other , so that is my only concern actually . i am working on a code were i need to initiate a relay while certain readings are obtained by an ultrasound sensor and start a sound for a certain period of time at the same time and then stopping it without interrupting the relay function at any time because the relay function could last for 1:30 hour or more,

so do you think that i can just use the readDigital function to read the pin I assigned as writeDigital (pin, High)
to activate the relay and link it in an If function to do the cut tones without affecting the relay function?

thanks,
 

   
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Aug 28, 2017, 04:03 pm
thank you Tim,

to tell you the truth I am not a bit concerned about this as long as tasks that I assign the controller to do do not interfere or interrupt each other , so that is my only concern actually . i am working on a code were i need to initiate a relay while certain readings are obtained by an ultrasound sensor and start a sound for a certain period of time at the same time and then stopping it without interrupting the relay function at any time because the relay function could last for 1:30 hour or more,

so do you think that i can just use the readDigital function to read the pin I assigned as writeDigital (pin, High)
to activate the relay and link it in an If function to do the cut tones without affecting the relay function?

thanks,
Simple answer, "Yup!".  Once you change the state of a pin (from LOW to HIGH or whatever) it stays in that state till you change it (or you power the microcontroller down).  The microcontroller doesn't need to multitask to keep the state of the pin the same, it's stuck in that state till you change it.

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: MarkT on Aug 29, 2017, 12:20 pm
I believe a piezo only acts like a capacitor when "charged" in one direction (for example, with the tone library).  The deflection of the disc is what generates the current.  However, with toneAC it can't charge in this way as an alternating current is being sent.  Therefore, the piezo is never charged and never acts like a capacitor.  From my understanding of how a charge on a piezo works, supplying an alternating current eliminates the need for a resistor.  But, maybe I'm mistaken.
Yes, completely mistaken.  The very same materials used in high value ceramic capacitors are used in
piezo elements because of their very high dielectric constant is due to the ferroelectric effect, where
charge movement is caused by atomic displacements within the crystal lattice.  Piezo elements are all
capacitive.

And like all capacitors the impedance goes down as the frequency goes up, so the current will be higher at
high frequencies.  And being mechanical devices they can also resonate, leading to the possibility of
higher voltages being generated than are fed in...
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: AdnanSamra on Sep 23, 2017, 09:34 pm
hi every one i need to know something please , since we are using pin 11, & 12 for arduino Mega 2560 to out put the sound using tone(AC) and there is no GND connection how can i use a push pull transistor output B class amplifier stage to an 8 ohm speaker? how can i connect this out put to the common bases of the npn & pnp transistors?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Sep 25, 2017, 04:35 pm
hi every one i need to know something please , since we are using pin 11, & 12 for arduino Mega 2560 to out put the sound using tone(AC) and there is no GND connection how can i use a push pull transistor output B class amplifier stage to an 8 ohm speaker? how can i connect this out put to the common bases of the npn & pnp transistors?
Ground alternates with toneAC, so you can't use a transistor.  But, you wouldn't need to use toneAC if you're going through a amplifier as you don't need to use toneAC to increase the volume.

Maybe I should ask, why are you wanting to use toneAC with an amplifier?

Tim
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: Darkstar_Traceur on Oct 18, 2017, 09:02 am
Hello, I absolutely love toneAC and have been using it on pretty much all of my projects.

Recently however, im trying to expand my project to the internet of things and picked up a Wemos D1 based on the ESP8266. (With inbuilt wifi)

And unfortunately, im getting errors. :( I know its this library is built for the ATmega but I had to try ;)

My question is do you have any support for the ESP8266 or even the new and powerful ESP32?

If not do you or anyone else have any suggestions for a tone library for the ESP boards?
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Oct 20, 2017, 07:42 pm
Hello, I absolutely love toneAC and have been using it on pretty much all of my projects.

Recently however, im trying to expand my project to the internet of things and picked up a Wemos D1 based on the ESP8266. (With inbuilt wifi)

And unfortunately, im getting errors. :( I know its this library is built for the ATmega but I had to try ;)

My question is do you have any support for the ESP8266 or even the new and powerful ESP32?

If not do you or anyone else have any suggestions for a tone library for the ESP boards?
The non-timer based methods will work (like ping() and ping_cm() for example). But the time-based methods would never work on ESP boards as every microcontroller uses different timers and logic.

You shouldn't get errors if your using ping() for example.

Tim
Title: How to connect 2 speakers
Post by: TryBit on Nov 18, 2017, 07:41 pm
Hi

I want to connect two speakers (left speaker & right speaker), I know the specs says connect pin9 & 10 to speaker wires. The speakers will not play at the same time, only one or the other.  I am using UNO, how to achieve 2 speakers connection? 

FYI, I know I can make a control switch circuit to switch between left and right speakers.  But I'd rather not do that if there is a way to connect two separate speakers. Again only one speaker will be active at one time.

Thanks in advance
Title: Re: toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.
Post by: teckel on Nov 19, 2017, 04:44 pm
Hi

I want to connect two speakers (left speaker & right speaker), I know the specs says connect pin9 & 10 to speaker wires. The speakers will not play at the same time, only one or the other.  I am using UNO, how to achieve 2 speakers connection? 

FYI, I know I can make a control switch circuit to switch between left and right speakers.  But I'd rather not do that if there is a way to connect two separate speakers. Again only one speaker will be active at one time.

Thanks in advance
toneAC must use the pins assigned to the timer.  The pin 9 & 10 requirement is a limitation of the microcontroller, not the library.  However, I do have a toneAC2 library which uses timer 2 and you can assign it to any other 2 pins.  So, you need to use both toneAC for one speaker (pins 9 & 10) and toneAC2 for the other speaker, which you can assign to any other two pins.

toneAC2:  https://bitbucket.org/teckel12/arduino-toneac2/wiki/Home

Tim