Arduino Forum

Using Arduino => Audio => Topic started by: Tuttut on Jul 03, 2012, 09:24 pm

Title: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 03, 2012, 09:24 pm
Hello,
I like to promote my new library which makes playback of audio from SD cards very simple. The audio quality is 8-bit, but a PWM frequency of 62.5 kHz is used which gives decent sound quality at very low effort. The library is completely free, fully documented and includes some example projects for quick start. Enjoy, feedback here if you like it.

Edit/New: I updated the library (ported the core output part to hand-optimized ASM) and now also 16 Bit audio output (even in stereo) is possible (combining two PWM outputs using 2 resistors, known as 256R-R-network).

Edit/New: I updated the library again and now you don't have to call the .worker() function anymore if you provide a flag at init. Also added more examples like a doorbell with ding-dong sound as well as an example that shows file access from SD card using this library.

Regards,
Lutz
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 03, 2012, 09:25 pm
Forgot the link: http://hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio (http://hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 05, 2012, 05:27 pm
cant wait to play with it!..


Audio & Arduino is a hard thing for noobies (like myself) to achieve...

havent read it yet.. does it play .wav files? or do you have to convert to a specific format first to play off SD?


update: read link.. yep I saw you have to convert the files to another format..

thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 08, 2012, 05:40 pm
Yes, you have to convert the files, but for Windows users the conversion is a simple drag'n'drop operation of the wav-file to a batch-file. I also show a very simple and cheap approach to build an SD-card adapter just from two standard pin-headers.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 09, 2012, 03:24 am
nice!..

would be better if it played straight .wav files though  ;)


Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 09, 2012, 08:23 pm
I also thought about that, but the thing is that it is hard to get a high quality playback if PWM runs not at an integer multiple of the sample rate. That is the magic behind my library and that is why I can get such good quality. With high-speed PWM as available in ATtiny85 then it makes more sense to use the original playback rate (as Elm-Chan does).
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 09, 2012, 08:51 pm
cool!

I'm still wanting to play with it!

anything that helps do audio is a bonus!  Im sure others will appreciate it too!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: funkyguy4000 on Jul 10, 2012, 01:26 am
bump
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 13, 2012, 03:48 pm
Thank you so much for this, will try out ASAP!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 13, 2012, 05:39 pm
I love this, thank you, sounds pretty good, a bit of hiss, so I have to see how to clean it up.

Questions:

1) could you add an option for 20Mhz too? I got some 20Mhz crystals and ATmega328 chips lying around, wondering if at 20Mhz I could play stereo files better?

2) I did a PWM output that was nearly 10 bits, with a better audio. Check this out:
https://github.com/Beat707/BeatVox
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 13, 2012, 09:05 pm
Hello,

1)
it would work with 20 MHz, but not better regarding stereo playback at full rate, because this is just a matter of free cycles. But with 20 MHz fullrate will be 78kHz, so just a little better. I think the next improvement I will make is to use a 256R-R network to go from 8 bit to 16 bit with just another port and 3 resistors.

2)
I don't find the circuit for the audio output. Increasing bit resolution is always about decreasing PWM frequency, the only way around is to use either a AVR with high-speed PWM (like Elm-Chan did with ATtiny85) or combining two PWM outputs.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 13, 2012, 11:15 pm
Quote
I think the next improvement I will make is to use a 256R-R network to go from 8 bit to 16 bit with just another port and 3 resistors.


Niiice, I wonder about that.

Plus, I wonder about the ATtiny85 too.

Thanks!  8)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 13, 2012, 11:27 pm
Question about the ATtiny85, as I also use those and have a few to test out, what kind of bit-depth are we talking with those? I'm not talking about SD card playback, just internal flash playback, as I'm doing another project, and all I need is to be able to play a single drum sound from the ATtiny85, but I need better quality, as better possible. ;-)

Thanks again!  :smiley-mr-green:
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 15, 2012, 04:45 pm
Maybe this could help you getting 16-bit using 2 PWM outputs?

http://embeddednewbie.blogspot.com.br/2011/02/review-of-arduino-dac-solutions.html

Resistor/PWM hybrid DAC

This is a good explanation on how to combine two PWM outputs in order to double the bit resolution. So combining two 8-bit arduino PWM outputs you can get a 16-bit PWM output! Remember Arduino's limits if you plan on going down this road. I mean, the Atmega chip is just 8-bit...

(http://4.bp.blogspot.com/_wij7mZKxW4Y/TU7DQ35G6XI/AAAAAAAAAQU/W6KfcI6EEXU/s1600/pwmhybrid.png)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 16, 2012, 11:47 pm
Hi,
now I tried the 16-bit thing with the R256-R DAC and it gives a big advantage. It is not as good as you would expect from 16-Bit because it is hard to get rid of all those digital noise in such a circuit. The problem with all those circuits is to keep away the digital noise from supply from audio output. As long as a digital output pin that is supplied from uC is used, you also hear all the uC noise. Maybe it gets better if you decouple the uC better or use something like a buffer. But simply said, using just those two additional resistors you get rid of those hiss noise. After playing a little bit around it seems that most noise comes from the USB port - maybe you get acceptable results by using battery power.

What I did is the following: I set the following mode in software:
Code: [Select]
SdPlay.init(SSDA_MODE_HALFRATE | SSDA_MODE_STEREO)

Then I prepared my file with the following modified batch-file:
Code: [Select]

@echo off
cd %~dp0
mkdir converted
FOR %%A IN (%*) DO sox %%A --norm=-1 -e unsigned-integer -b 16 -r 31250 -c 1 -t raw "converted\%%~nA.ahd"  
pause


Connections I made:
Code: [Select]

Pin 9  ----[220k]------+
                      |  100nF
Pin 10 -[1k trimmer]---+---||----[10k]--AudioOut--[1k]--GND


With trimmer the sound can adjusted for minimum hiss, I prepared also a special audio-file for easier trimming.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 16, 2012, 11:57 pm
Ohhh, very nice! I need to download a library update, right? Thanks again for such hard work!  8)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 17, 2012, 12:02 am
No, I have not changed the library yet. Maybe I will do it later after documenting it better - you only need the new batch file. We should try level-shifters or buffers (anything that is very cheap and easy available) to improve the sound (should be placed between Arduino outputs 9/10 and resistor stuff. 
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 17, 2012, 12:03 am
I haven't messed out with the library source yet, but do you think it would be possible to get a more instant playback and re-play by setting an initial file, and just have it play, and re-play when requested? This way I could use this to playback long drum sounds. (crashes and cymbals) I need this for a small project I'm doing. ;-) Maybe an option to open the file and have it used until said to open a new one? Also, an option to re-start the file, even if its not done yet, for when you play a drum sound, you are in the middle, but needs to re-trigger the sound.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 18, 2012, 04:54 pm
I wonder one thing, would it be possible to handle 16-bit stereo files? Using 4 x pwm outputs for 2 x 16-bit hybrid dacs? What's the limitation them? I see that a 5Mb SD Card can handle it without problems, is the bottle-neck the SPI or the ATmega itself? Maybe running at 20Mhz would help? Just wondering, as it would be KILLER to be able to play 16-bit stereo files.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 03:50 pm
In any event, it should be possible to handle mono 16-bit 31khz .WAV files now, right? I know how to handle WAV files, so I will see if I can be of any help on this...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 07:34 pm
With this I got a perfect loop:

Code: [Select]
while (1)
  {
    // Start playback
    SdPlay.play();
 
    // Let the worker work until playback is finished
    while(!SdPlay.isStopped()) {
      SdPlay.worker();
    }
  }
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 07:47 pm
I just tested the 16-bit hybrid dac with your code, as explained, and I love it, great quality!  8) I hear a strange buzz on the background, is that the PWM? I'm using an external power-adapter and running the ATmega328 at 3.3V, to keep the SD Card connections simpler.

I haven't done your full 16-bit dac specs, I used a 256k and just one 1k resistor, so now I will try the way you did, to see if the buzz goes away. ;-)

Thank you so much for the hard work on this lib!!  :smiley-mr-green:
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 07:48 pm
The project I'm working requires 4 loops to be played, not at the same time, but with the option to go from one to another. So I wonder if I could do some sort of pre-buffering for all 4 files, in a way I could just go from one to another with min. gaps?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 08:59 pm
Ok, I found the buzz sound problem. It was the 3.3 V thingy. Now I'm running at 5V and using a proper SD Card adapter for Arduino (it has all the voltage converters) and it sounds GREAT! Thanks again!  8) 8)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 09:01 pm
Darn, the buzzing sound is still there, its from the PWM output. But its much lower now, compared to before.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 09:41 pm
Ok, assuming you can also hear the buzzing sound there, how about using 2 timers? One for the DAC and another one for the sample-rate. For instance, Timer1, which you already use now for both sample-out and sample-buffering, you could leave just for the DAC and setup for 9 bits, so the frequency of PWM is much faster. Then another timer for the rest, lets say, Timer2.

I will check the code when possible to see if I could just hack it and hear the result.

At least on my 6-voice sampler I did it with a higher frequency PWM using Timer1 and there's no buzzing sound. Unless my chip is faulty. I will test my 6-voice sampler on this same setup, just in case. ;-) Here's the link: https://github.com/Beat707/BeatVox

Again, thanks for doing this lib, I'm really loving it!  8)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 09:59 pm
Darn, I can't figure out this buzzing sound, no idea where its coming from, maybe the SPI interface? (doubt that) What I see you did different from my 6-voice thingy, is that you take a bit to update the PWM outputs, I do it first-thing, from a 2-byte buffer, maybe that could help? I will try that. ;-)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 10:36 pm
Darn thing, it does sound like the SPI. Here's a simple test.

Code: [Select]
uint8_t bufferL = 80, bufferR = 80;

void SdPlayClass::interrupt(void)
{
//SSDA_OC1L = bufferL;
//SSDA_OC2L = bufferR;

SSDA_OC1L = 255;
SSDA_OC2L = 255;

  uint8_t  flags = _flags;  // local copy for faster access

...


Code: [Select]
void setup()
{
  SdPlay.init(SSDA_MODE_HALFRATE | SSDA_MODE_STEREO);
  SdPlay.setFile("Loop5.a16"); // 16-bit mono file - half rate
   
   while (1)
   {
     SdPlay.play(); while(!SdPlay.isStopped()) { SdPlay.worker(); }
   
     pinMode(SCK, INPUT);
     digitalWrite(SCK, HIGH);
     delay(1000);
     pinMode(SCK, OUTPUT);   
   }
...


I can hear the buzzing sound, once the loop is done, it will pause for 1 second without the buzz sound.

Unless I'm doing this test wrong. ;-)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 19, 2012, 11:11 pm
Well, it does seem to be the SPI clock leaking somewhere, not sure what to do... any ideas?  :smiley-red:
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 20, 2012, 05:07 pm
Hi,

the buzzing sound can come from anything on the Arduino or stuff connected to it. I don't think that you can get rid of it just by optimizing the software - increasing sample rate will not change things. The quality out of the PWM is already superior, but get's damaged by the noise on the supply lines.
Therefore as I proposed before try to use something that "isolates" the digital PWM lines from power source. Use a buffer or a level shifter. Then filter the supply for that level shifter very thouroughly  using an own linear regulator or at least a serial resistor with a capacitor to gnd between VCC-digital and VCC-analog.

Regarding 4channel mode: If I translate the interrupt function to assembler then it should be possible to have enough computing power for stereo 16 bit playback...

Regarding pre-load: The function setFile stores internally something about the file in a small structure. By using that struct it should be possible to playback any file with very little latency. Maybe I will add this feature later to the library.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 20, 2012, 06:29 pm
the buzzing sound can come from anything on the Arduino or stuff connected to it. I don't think that you can get rid of it just by optimizing the software - increasing sample rate will not change things. The quality out of the PWM is already superior, but get's damaged by the noise on the supply lines.
Therefore as I proposed before try to use something that "isolates" the digital PWM lines from power source. Use a buffer or a level shifter. Then filter the supply for that level shifter very thouroughly  using an own linear regulator or at least a serial resistor with a capacitor to gnd between VCC-digital and VCC-analog.


For now I will ignore the buzz sound, I deal with that later on. ;-) Txs bud.

Regarding 4channel mode: If I translate the interrupt function to assembler then it should be possible to have enough computing power for stereo 16 bit playback...


Oh! oh! oh! That would rock!!!!!!!

Regarding pre-load: The function setFile stores internally something about the file in a small structure. By using that struct it should be possible to playback any file with very little latency. Maybe I will add this feature later to the library.


Indeed, shouldn't be too hard for me to just hack the thing out if I really need. So far I'm just using the setFile and it still works great!

Thanks again!

Cheers, WilliamK
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 25, 2012, 05:50 pm
Just wanted to thank you again for such great library.  8)

I managed to find the buzzing sound, it was my wiring, a friend told me to not use too long wires to connect to the SD Card, that was the reason of why the SPI Clock was leaking to the PWM outputs. Its solved now.

I still wonder if it would be possible to handle WAV files (saved at the right sample-rate) but its not a big deal to convert things up, just wondering. (one less step for newbies)

The 16-bit mono support is great, but yes, stereo support would put this lib in a new position.

I plan on using 4 loopers running side-by-side, already got extra ATmega328 + Crystals here to do so. ;-) Just need some extra time, prob next week...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 25, 2012, 07:11 pm
hey guys...

I dusted off my 2009 board.. and want to give this library a try and compare it to the output Im getting using dedicated hardware and the WaveHC library (.wav files)

what is the wiring set-up you guys have going?

I have an SD card (made a little break out board for it).. and plugs into my Arduino 2009 board..  with the correct resistors for level shifting..etc..

reads/writes fine using SDFat libraries to test..

what else is there?  what pins are you using for the speaker output?  what other components are needed?

off to download library now..

thanks!

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 26, 2012, 08:49 pm
The wiring is described on the website. If you are using a shield already for SD card connection, all you need is a capacitor (take anything you get between 100nF and 100uF), connect positive end of capacitor to Arduino-Audio-Outputpin (as described in library documentation) and connect the other to your active speaker/line in. Then also connect GNDs of active speaker/line in and Arduino and you are done. That way you can play back the example file or any other files converted to MONO and FULLRATE or HALFRATE.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 27, 2012, 06:09 am
HI I just downloaded your lib to finally play with it..

I (finally) noticed everything is .ino  or for Arduino 1.0 only?

I tried to put your lib in my libraries folder..but it never showed up (Im still using IDE v.23)

is there a version for older IDEs?



update:

installed IDE v1.0 justto try this..

did minimal (10uF cap, speaker approach)..


sounds great!.. awesome job on using minimal components..with default Arduino!!!

this adds so much more ability/options for projects..


question (since Im a noobie)..

are we free to do whatever we want during the audio playing?  any restrictions?

what about having other components on the SPI bus?

thanks..  =)



thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 27, 2012, 05:42 pm
Hello,

>is there a version for older IDEs?
No, currently you need at least Arduino 1.0 IDE.

> are we free to do whatever we want during the audio playing?  any restrictions?
It depends... You have to call the worker()-function frequently enough to avoid buffer underruns. This function reads the next sector from SD card into a ringbuffer to keep audio playing running.

The library uses timer1 on most Arduinos (timer5 on mega arduino). This should be no issues for standard libraries, but libraries which uses those timers may not work correctly. analogWrite() functions should work even with that modified timer. The timer's interrupt is used to for audio playback, disabling interrupts for more than 10 micro seconds could result in playback distortions. In general, very much of the available computing power of the Arduino is used during playback...

> what about having other components on the SPI bus?
The lib could work with other stuff on the SPI bus as long as it has its own chip-select and does not need to change the spi transfer parameters (SD lib uses full speed). It seems to work with the Ethernet-Shield - also an example to start playback via webbrowser is included in the examples. For other SPI stuff it depends - just try it...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 28, 2012, 06:37 pm
Hehe, I now got stereo at fullrate working - I've rewritten the audio output interrupt routine completely in ASM. Next step is heading to 4-channel audio output at 8-bit or stereo-16-bit-output...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jul 28, 2012, 06:38 pm
That's impressive, congratulations! Thanks for this!  8)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 28, 2012, 07:57 pm
I think this is VERY awesome!!..


thanks!..

I had a (now defunct) PIC project that played audio through PWM output as well.. was very easy/low components too..  missed it!

Now we have this!!!

I read about thew buzz/hiss on the output a little bit.. what was the verdict?

dirty power lines?  or something with the SPI bus/lines?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jul 31, 2012, 05:42 am
can you easily change the speaker out pin used on the Arduino?

I tried to change this:

uint8_t const SSDA_PWM1_PIN =  9; // OC1A PB1

to

uint8_t const SSDA_PWM1_PIN =  5;

but didnt seem to work on getting output on PWM pin 5

thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Aug 01, 2012, 06:25 pm
Hi,
no, you can not change the speaker output because it need very special PWM pins. It it would be that easy I'd already implemented it in the library. May I ask why you need the output pins to be changed?

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Aug 01, 2012, 06:37 pm
I figured..  I was hoping another PWM pin could be substituted.  :)

I was just trying to test it out on a specific (custom) board I had... to see if this lent even more flexibility to it..

I have one more (custom) board I want to try this with..

my 'goal' on my board/project was to have a very small footprint/sized board (which I need for the things I like to do..and full sized dev boards dont cut it).... that had several on-board things that we buy/use shields for.. (SD card.. .wav playback.etc..etc..)

but still be generic enough to apply to many different projects.

(here it is: http://dmstudios.net/misc/scab_assembly/flash_board.jpg)
using the WaveHC library.. it plays .wav files off the SD card..
can also just be used as a data logger or to access stuff on the SD card is audio playback is NOT the focus for the board..etc

here it compared to an Arduino & WaveShield.. (which this was based off...sorta merged together)

http://dmstudios.net/misc/WaveShield_assembly/compare0_small.jpg

http://dmstudios.net/misc/WaveShield_assembly/compare2_small.jpg


I had a failed version of this project I wanted ot test your lib with.. (but no D9 available on that)

the one above.. (current project) does have it (D9) available, so will be testing on that as well..
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Oct 14, 2012, 01:52 am
I've been playing with this library today and have to say it's awesome for what I need, being able to play simple sound effects from game props.

I've just been using a single pin today for 8 Bit Full Rate Mono, but the quality seems really good for what we need. Unfortunately I was using an Ethernet shield for the SD cardso couldn't use D10 to try 16 Bit. That's the only downside I can see, the pin conflict with Ethernet and some LCD Shields (pin 10 is used for backlight brightness control).

Just thought I'd say a big thanks for the time put into this. It's a great piece of work to show what can be done direct from the MCU, without additional hardware.

I connected up to a set of PC amplified speakers and it sounds great with both voice, item and vehicle sounds.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: gateway on Oct 14, 2012, 12:14 pm

Hehe, I now got stereo at fullrate working - I've rewritten the audio output interrupt routine completely in ASM. Next step is heading to 4-channel audio output at 8-bit or stereo-16-bit-output...


Hi there,

just stumbled upon your library, it's great!
Many thanks!!

The last version on your website (v1.01) seems to date previous to this rewrite.
Any chance of posting this new version?
I would like to do 16-bit mono @8mhz, so I could use the extra resources...

Thanks again for sharing this!!

Regards Dennis
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Oct 17, 2012, 10:09 pm
Hello,

This looks like a great library. Any chance that it could be ported over to include support for the chipkit Uno32? How difficult do you think it would be to do so? It appears that PWM would be relatively simple to port over, but I am not sure about the SD card interface. Any ideas?

With the 80MHz 32bit processor on chipkit, you could have faster SD card read times and high sample rates that would enable more processor free time and better sound. The chipkit is also natively 3.3V, so no level shifters are necessary.


-Thomas
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Oct 19, 2012, 06:02 pm
Well, I am starting to port the code over to the chipkit Uno32. First I had to port the library back to Arduino 0023, since that is what the chipkit software--MPIDE--is based on. This was mostly just changing

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

to

Code: [Select]
#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif


as well as converting the examples from .ino back to .pde files. After this massaging, I got it to compile in 0023.

The code is not pretty at the moment since I am using a lot of "#if defined (__PIC32MX__)" to switch between AVR and PIC specific code. I have the SD card library working on the Uno32, so now I need to port over the PWM.

I am running the SD card at 400kHz during initialization and then at 20MHz for everything after that. It is looking like the PWM will be sampled at 78125Hz for full rate and 39062.5Hz for half rate. These values were chosen to give perfect 8bit resolution on the PWM and still be close to the original 62500 and 31250Hz values.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Oct 19, 2012, 06:07 pm
cant wait to see some examples (video) of how it sounds....

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Oct 19, 2012, 06:29 pm
For anyone interested in further details regarding my chipkit port, follow the progress at http://chipkit.org/forum/viewtopic.php?f=7&t=1652&p=7026#p7026 (http://chipkit.org/forum/viewtopic.php?f=7&t=1652&p=7026#p7026).


-Thomas
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: PWBarrett on Oct 21, 2012, 06:43 pm
Might I make a request?...

that SdPlay.deInit(); would release whatever SPI timers etc that were grabbed by calling init().

I'm trying to use this in the same project with the Servo.h library, but there's apparently a conflict.
Once I call SdPlay.init(), I can no longer position servos where I want, even if I'm not playing a sound.

Not really a problem since I don't need to do both simultaneously.
I could init(), setFile, play etc., then deInit before returning, but deInit isn't putting things back the way they were...

Any suggestions?
-- thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 23, 2012, 10:04 pm
Hi,
I released a new version of the library. The core audio output function is now written in assembler and thus allowing playback of either STEREO and FULLRATE or HALFRATE with four channels. Two channels can be combined to get 16-bit resolution using only a resistor and a trimmer. But in this case the faint noise of the controller can be heard, so I recommend using cheap Schmitt-Trigger buffers (like 74HC14 or else) to get rid of the noise that is on top of the digital signals of the Arduino. With HALFRATE and QUADRO mode and those Schmitt-Trigger circuit you can get a quality that is very good also for music or sound with big dynamics. I is still not full CD quality but quite near to it.

Also I did a patch that you can apply to Arduino that frees the timer0 from all the core functions and makes it available for audio output (timer2 is then used instead of timer0 for core functions like millis and so on). This way audio can be output on pins 6 and 5 instead of pins 9 and 10 on ATmega328 based platforms like Uno, Duemillanove and Ethernet or on all 4 pins together allowing also the Uno to do 16-bit stereo output...  :smiley-mr-green:

Further, for Windows user I included the SOX binaries in the library so you can convert WAV-files using the drag'n'drop targets.

Have fun!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: gateway on Oct 23, 2012, 10:31 pm
Hi Tuttut,

Great work, many thanks for this!!!

As for audio filtering, I've tested with a "Passive, first order low-pass RC filter", which seems to clean out most of the noise with just a resistor and a capacitor, see http://en.wikipedia.org/wiki/Low-pass_filter (http://en.wikipedia.org/wiki/Low-pass_filter).
I found a  1kohm resistor and a 2.2qf capacitor work out for me, but to be honest, I used a trial and error approach...
Not sure if this even comes in the neighborhood of your buffer approach, but I found the improvement more than adequate for my project.

Once again, many thanks!!!

Regards Dennis
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 25, 2012, 11:31 pm
@cobra18t: I like your attempt of porting my library. I included your header-file-stuff for earlier Arduino versions but I never tried the lib on older Arduino IDEs. For SD access you can use my reduced SD library - you have to adapt the sd_l0-files, but the other layers should work quickly on any architecture after that.

@PWBarret: The servo-library (re)initializes the servos after detaching and re-attaching all servos. So try this order: 1. SimpleSDAudio: init -> Play... -> deInit, then Servo: Attach -> control -> detach, then continue with SimpleSDAudio. Both libraries can not work the same time because they share the same timers.

@gateway: You are right, a RC filter might often be an easy way to improve the sound quality on PWM outputs. It works better the higher the PWM frequency is -> SimpleSDAudio uses the highest possible frequency and therefore a RC filter should work pretty well.

Tuttut. 
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Oct 27, 2012, 01:15 am
@Tuttut: I saw my changes in the newest version, I will have to try it out in 0023. Thank you for abstracting the SD card library so that I only had to change the "0" level. That made it much easier.

I have a video of a basic 8-bit 78.125kHz stereo sample running on my ChipKit Uno32 using a minimal setup. Check it out:
http://cobrainnovations.blogspot.com/2012/10/basicsdaudio-chipkit-library.html (http://cobrainnovations.blogspot.com/2012/10/basicsdaudio-chipkit-library.html)


-Thomas
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: PWBarrett on Nov 06, 2012, 02:46 am
Thanks for the suggestion...
Maybe it's the servo library that's not properly honoring the detach method then...
If I never attach the servos at all, the sound is good.
But if in my PlaySD function, if I detach both servos upon entry, then init, play, deinit, the sound is garbled.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Dec 14, 2012, 10:55 pm
Hi Tuttut-

I havent kept up with things since you first posted the initial library.. (I see its come very far)..  great job!.. and a HUGE benefit to the community IMHO! (thanks)

I am going to re-read the posts.. and go to your site and download the latest..etc..

1.) Does the Arduino board/version matter to use this library? Can the board be a 3.3v @8Mhz board and still be able to utilize this lib?

2.) how much space/resources do we have to 'do' other things WHILE playing audio back?

3.) I saw mention of it being able to be used with IDE v23?  IS this added/supported now? or must I use the 1.x+ IDE's?

I have a project in mind that I intend to use this lib for...  but the board/pcb is a 'VERY' minimal Arduino circuit running at 3.3v and internal clock @ 8Mhz and SD socket...

(actually.. Im trying to run it off a coin cell.. think thre will be enough voltage (3.0v I believe most coin cells).. if there is enough current for the SD card?


I remember there needs to be a cap in-line with the speaker out line...  so I'll probably look at adding that 'on-board' to the pcb itself.....so end result is just solder speaker wires to pcb pads.  (or reading up on the low pass filter to put on board)

off to look over the public methods available to us.. and check for any examples on how to utilize each one.

thanks!!



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Dec 17, 2012, 12:15 am
Hi xl97,

1) The lib is tested on Arduinos using mega328 or mega2560 Arduino based plattforms. I don't know if it will work on things like Leonardo or those USB-supporting-AVR-Devices.
If you want to use a 8 MHz Arduino you need to convert the samples using the batch-files for 8 MHz, this will half the sampling rate but is often still good enough. If you use a 3.3V Arduino you can attach the SD card without those resistor-divider-stuff directly to the Arduino.

2) Audio-Lib takes about 1.3KB of RAM, which is a lot especially on mega328 devices. The timer that belongs to the audio-output-pin is fully utilized by the lib and therefore not available anymore. The processor time amount needed is also very high, I guess at nearly 80-90% for highest quality audio stereo. But often that is enough for applications that does not need much power.

3) I've added some stuff to allow for work in versions prior 1.x, but I never tested that. I think I have heard other people got it to work with v23.

The cap is by the way only to block DC currents from the speaker. It does not act as a low-pass so far as the PWM frequency is out of the hearing range for 16 MHz Arduinos. For 8 MHz you should use the highest rate, then it should be ok as well.

tuttut
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Dec 19, 2012, 11:18 pm
@Tuttut

Any suggestions for changing the code so multiple files could be played at once/asynchronous from each other. Would I just keep track of a "_fileinfo" object and a buffer for each file playing? Then the worker routine would service each buffer as necessary and the PWM output would be some sort of summation of the individual outputs?

Note that this is for my port of your library to the faster ChipKit compatible microcontrollers. My ideal scenario would be to create a library capable of 4-8 channels of audio. You could designate 1 or more of those channels to be protected, by which I mean they would not stop playing if the user requests another file to be played. Instead, the next file would go to the next available unprotected channel, where "next" is determined by a ring buffer.

As an example, Super Mario Brothers sounds. Assuming 4 channel audio. You would want the background music to be protected, because you don't want it to stop when the sound effects play, so maybe it plays through channel 0. If you jump, then the jump sound effect would play in channel 1. Then you shoot two fireballs while you are in the air, whose sounds play in channels 2 and 3. If the first fireball hits a bad guy, then the jump sound would be stopped and the hit sound would play back in channel 1.


-Thomas
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Dec 20, 2012, 02:51 pm
Hi,
I also thought about extending the library to multi-playback, even on AVR based plattforms. On AVR, the interrupt itself creates big overhead due the many PUSH and POP stuff (I think ARM has a somewhat nicer architecture there), so doing things in interrupt is not the best way. On Arduino, if sample buffer is not changed, I works a little like a ping-pong buffer, because a whole sector of samples is read before the buffer is released for playback. If multi-playback of different sounds starts sector aligned, two different sectors can be read and added together in playback buffer and the buffer can be released as one block. This become more complex when not sector aligned.

For your approach I like your idea of buffering the sounds in different memory locations and maybe adding them in interrupt (maybe also scale the values for volume control). SD cards tend to be damn slow if sectors are not read in order, to overcome this your approach could lead to read n sectors from file 1 and then n sectors from file 2. With n being a number bigger than 1, you can trade more possible simultaneos channels at the cost of a bigger starting delay.

BTW: But decide and try yourself, getting the best compromise involved a huge efford of research even for that simple "SimpleSDLibrary" on AVRs. It was a long way to find out that simply using a high PWM rate even at low sampling rates is the most important factor on the way to get nicer audio output. On that way I also tried things like storing 1 bit delta-sigma-coded audio on a SD card and playing that back at high rates through SPI output. It worked good, but involved heavy conversion on PC side and adding sounds or even modifying the volume is not possible anymore. In the end I considered it not simple enough for Arduino world...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: hart on Dec 23, 2012, 05:03 am
I got this working on an Arduino Uno (R3) in under 30 minutes this morning, very happy to hear the audio coming out of my speaker - however, when I tried connecting an LM386N-3 based 1W amplifier (http://ebookbrowse.com/n48fl-pdf-d393297795 (http://ebookbrowse.com/n48fl-pdf-d393297795)) with a set gain of 50 (adjustable input attentuation via POT) to the output pin (using the recommendations in the docs for powered speakers), all I got was beeping noises rather than audio?

Any advice appreciated!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: hart on Dec 27, 2012, 02:05 pm
sorted - was a dry joint on a cap. 
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: TroyO on Dec 27, 2012, 08:39 pm
Opps, i think I dumped my first post... appologies if this ends up being a duplicate.

I am having some unexpected behavior with some SimpleSDAudio code. I am basically working on a lightsaber and I want the code to play a HUM.AFM file whenever something else isn't playing.

Simple enough. The issue I am running in to is that SdPlay.isStopped() returns false (0) when the code goes in to the first "loop(void)" even though nothing is playing. While that is easy enough to code around it seems it should in fact return true (1). Once kicked over through one loop it seems to work fine.

Code: [Select]

void loop(void)
{
Serial.println(F("Loopy"));
Serial.println(SdPlay.isStopped());
  if (SdPlay.isStopped()) {
    SdPlay.setFile("Hum.afm");
    SdPlay.play();
}
while(!SdPlay.isStopped()) {
    SdPlay.worker();
   }
}


Anyway.... not a huge deal, it just seemed odd.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: TroyO on Dec 27, 2012, 10:40 pm
Further details..... my "fix" was just calling to

    SdPlay.setFile("");

In the void setup() section. That seems to get the ball rolling too.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: craiglindley on Dec 30, 2012, 06:36 am
Pin 44 on my mega 2560 is committed to another function that I cannot change. So is it possible to use a different timer (like timer4) for PWM output with this code?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Dec 30, 2012, 04:47 pm
Hi,
for performance reasons, audio pins are fixed in the library. But the library is written in a way, that all that must be defined to use a certain timer is placed in the file SimpleSDAudioDefs.h, so take a look in that file, maybe you can patch it for your purposes. All defines there are used from assembly as well as c-files, so there should no need to touch any other files.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Dec 30, 2012, 05:10 pm
@TroyO
Hi, I've analysed your stop-issue, I think you are right, there is a little bug in the library that clears the stop-flag in the init-function. Calling SdPlay.stop(); after .init should also solve the issue.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Dec 30, 2012, 05:32 pm
good to know tuttut-


@TroyO-

I saw the 'double press' in the video..

glad it can all be 'fixed' with a line of code.  :)

I'll be using this heavily in a project over the next 3-4 weeks..

I have high hopes for this lib. :)


(will be starting next week hopefully!)  :)

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: timberwolf9 on Jan 03, 2013, 01:37 am
This is a really good lib. Been playing with it all morning, really should be doing work on my other project, and I've had no problem playing files converted with:
Code: [Select]

$ sox inputfile -b 8 -r 64000 -c 1 -t raw outputfile


Good work on getting all this together, I bought an arduino with a few projects in mind, but never thought
I'd be playing music off of the thing. Keep up the awesome progress!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: bratan on Jan 03, 2013, 01:59 am
Fantastic library, got it working within few minutes!  :)
Is it possible to play Audio in parallel while Arduino does other things?  I wasn't able to figure out how. I wanted to see if I can dump WaveShield in favor of this library. WaveShield allows me to play Audio regardless of other things I'm doing, which is essential for my Alarm clock (shows time, blinking dots while playing alarm audio file).
I did some testing with SimpleSDAudio and it looks like if delay between calling SdPlay.worker() greater than 5 milliseconds, playback slows down and becomes choppy... Even calling Serial.println ("test") slows down playback noticeably. Here's example of code from loop:
Code: [Select]
void loop(void) {
 Serial.println ("running");
 //delay (5);
  if (!SdPlay.isPlaying() ) SdPlay.play();
 // Let the worker work until playback is finished
 SdPlay.worker();
}

Let me know if there's a trick to it :)
Maybe buffer can be auto-filled by Interrupt?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: timberwolf9 on Jan 03, 2013, 03:00 am

Fantastic library, got it working within few minutes!  :)
Is it possible to play Audio in parallel while Arduino does other things?  I wasn't able to figure out how. I wanted to see if I can dump WaveShield in favor of this library. WaveShield allows me to play Audio regardless of other things I'm doing, which is essential for my Alarm clock (shows time, blinking dots while playing alarm audio file).
I did some testing with SimpleSDAudio and it looks like if delay between calling SdPlay.worker() greater than 5 milliseconds, playback slows down and becomes choppy... Even calling Serial.println ("test") slows down playback noticeably. Here's example of code from loop:
Code: [Select]
void loop(void) {
 Serial.println ("running");
 //delay (5);
  if (!SdPlay.isPlaying() ) SdPlay.play();
 // Let the worker work until playback is finished
 SdPlay.worker();
}

Let me know if there's a trick to it :)
Maybe buffer can be auto-filled by Interrupt?



Don't quote me on this, but from looking at the code, I think you could do such given that you make a call to the SdPlay.worker() function often enough to keep the buffer filled. I'm not sure how much of the processor is left once playing audio, but it seems you could squeeze in a few other non time dependent things. (Like adding up time or checking for a button and updating its state...simple things)

From what I have gathered, the SdPlay.worker() function reads the next sector of the sdcard into a buffer. So if you call it often enough, you should be okay, just don't ask for anything that needs a ton of resources while playing audio.

Feel free to correct me if I'm wrong, but this is what I have gathered so far.

Edit: Just from playing with the serial I can see what you are saying, but I haven't come up with a solution.
Edit2: If you hear the skip when using serial at 9600, move it to a higher speed. I'm running at 115200 just to see, and there isn't a noticeable skip when using the serial commands in the demo.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: AllanB on Jan 03, 2013, 08:40 pm
Hi

I'm exited about this library. I might have a troublesome SD Card module.
I keep getting an error code: 49. I cant find out what code 49 is.
If I use Arduino's standard SD example listfiles, I get a correct list of files on the SD card. The SdFat library from http://code.google.com/p/sdfatlib/ also read the SD Card with the same wiring. So the wiring must be correct. And I use SdPlay.setSDCSPin(10); as pin 10 is my CS pin.
Then I commented the line: SPSR |= (1 << SPI2X);
Same result.

My sd module is this one http://www.lipoly.de/index.php?main_page=product_info&products_id=213383

I really hope someone can with this problem.

EDIT ----
It was not the SD Card Module but the SD Card itself. I tried with another one. Now it works.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: bratan on Jan 03, 2013, 08:56 pm


Don't quote me on this, but from looking at the code, I think you could do such given that you make a call to the SdPlay.worker() function often enough to keep the buffer filled. I'm not sure how much of the processor is left once playing audio, but it seems you could squeeze in a few other non time dependent things. (Like adding up time or checking for a button and updating its state...simple things)

From what I have gathered, the SdPlay.worker() function reads the next sector of the sdcard into a buffer. So if you call it often enough, you should be okay, just don't ask for anything that needs a ton of resources while playing audio.

Feel free to correct me if I'm wrong, but this is what I have gathered so far.

Edit: Just from playing with the serial I can see what you are saying, but I haven't come up with a solution.
Edit2: If you hear the skip when using serial at 9600, move it to a higher speed. I'm running at 115200 just to see, and there isn't a noticeable skip when using the serial commands in the demo.

No you are right, my thoughts exactly (about buffer). I also guessed that increasing baud rate will improve things, but never tested it so you just proved it :) It makes sense. However I'm just wondering how did they pull off the trick with WaveShield? I can do lots of heavy things with microprocessor while wave is playing, it never skips a beat... Can same be accomplished with this library? :)  Or because there's no DAC it's impossible to do?  I'm curious to hear what author thinks.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: timberwolf9 on Jan 04, 2013, 01:48 am

Hi

I'm exited about this library. I might have a troublesome SD Card module.
I keep getting an error code: 49. I cant find out what code 49 is.
If I use Arduino's standard SD example listfiles, I get a correct list of files on the SD card. The SdFat library from http://code.google.com/p/sdfatlib/ also read the SD Card with the same wiring. So the wiring must be correct. And I use SdPlay.setSDCSPin(10); as pin 10 is my CS pin.
Then I commented the line: SPSR |= (1 << SPI2X);
Same result.

My sd module is this one http://www.lipoly.de/index.php?main_page=product_info&products_id=213383

I really hope someone can with this problem.

EDIT ----
It was not the SD Card Module but the SD Card itself. I tried with another one. Now it works.


Just my two cents, I had this same error and was to fix it by reformatting the sd as FAT. You may be able to do the same with your sd, but don't use the quick format or the card will give the same error.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 04, 2013, 01:49 am
Hi, I will try answer some of your questions:

@timberwolf9:
Why the argument -r 64000? If you use a 16 MHz Arduino, it should be 16 MHz / 256 = 62500. But anyway, the sound is just a little bit to slow then...

@bratan & timberwolf9:
I will tell you some internal details about my library: The library uses a ring buffer of 1024 bytes when no work buffer is set manually. As the buffer is filled in one sector blocks of 512 bytes each, the buffer became a ping-pong buffer in most cases. With 512 bytes, at 8-Bit/Mono/62.5kHz that is about 8ms time, because the data reading from sd-card also takes some time, your observation of 5ms max delay between worker()-calls is very realistic.

On mega-arduinos is still a lot of RAM availible, so you can try to increase the audiobuffer by calling setWorkBuffer(...) before calling init(). With an increased buffer you will get more time between worker-calls.

By using the function isUnderrunOccured() you can detect if you even had a slight buffer underrun. But beware, I think this function returns true on every first call after calling play().

I also thought about calling the worker-function automatically in a timer interrupt. This should be possible, but only if that interrupt is set to non-blocking to guarantee the main audio interrupt the maximum priority. Maybe I will try to implement such in a next version of my lib, so that calling worker() is not necessary then anymore.

@AllanB:
Error code 49, which is 0x31, indicates that something is wrong with the bootsector on that cards. Maybe there is more than one partition on the card or something else is wrong. That explains why other cards work for you.

@bratan:
Yes, rising the baud-rate should solve issues with print-functions, as then the worker-calls are called more often.

To your question about other Audio-Playback-Shields: As far as I have seen it, all other audio-shields contain a dedicated processor that reads the audio-data from storage and feed it to an audio-DAC. For a good sound the DAC must be feed with low jitter at the audio rate of the audio material, otherwise you may recognize audio distortions like slowdowns or stuttering. With a dedicated processor it doesn't matter what your Arduino does while audio is playing, but my library is for all those who don't want to spend extra money to such a thing. SimpleSDAudio get the most out of the AVR's by pushing the Arduino processor strongly to its limits - that's the price you have to pay if you want nice audio from that little thing.

And one detail on top: The magic trick of getting a good sound out of the AVR's PWM is that mainly PWM-frequency matters more than anything else. It is the sampling rate of >32kHz that make the big difference between this lib and the well known bad telephone-like audio-playbacks often sampled at only 8 kHz of other approaches. With PWM frequency as high as 31/62kHz a low-pass is often not necessary. And you only need more than 8-bit if you want to listen to something that has not been as fucking dynamic compressed as most of the actual radio stuff nowadays is.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: timberwolf9 on Jan 04, 2013, 03:07 am

Hi, I will try answer some of your questions:

@timberwolf9:
Why the argument -r 64000? If you use a 16 MHz Arduino, it should be 16 MHz / 256 = 62500. But anyway, the sound is just a little bit to slow then...

@bratan & timberwolf9:
I will tell you some internal details about my library: The library uses a ring buffer of 1024 bytes when no work buffer is set manually. As the buffer is filled in one sector blocks of 512 bytes each, the buffer became a ping-pong buffer in most cases. With 512 bytes, at 8-Bit/Mono/62.5kHz that is about 8ms time, because the data reading from sd-card also takes some time, your observation of 5ms max delay between worker()-calls is very realistic.



@Tuttut
"-r 64000" gives reasonably good audio on my arduino uno, it may be my setup that has gone wonk, but when converting using the rate you gave, the audio was always really high pitched and fast moving. So I played around with the terminal options for sox and found that to be a sweet spot where the audio tone and play speed are warm and spot on.

If I read the internals correctly, we could get away with performing micro task once the audio is playing. 704 is not a lot of RAM to play with, but for listening to the network and flashing a light, it may be enough. (704 is more than enough for flashing a light...I would think)

Also, Tuttut, I ran into the 49 error code on my card until I did a FAT format. Once that was done, everything else went smooth as butter.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: bratan on Jan 04, 2013, 04:58 am

I also thought about calling the worker-function automatically in a timer interrupt. This should be possible, but only if that interrupt is set to non-blocking to guarantee the main audio interrupt the maximum priority. Maybe I will try to implement such in a next version of my lib, so that calling worker() is not necessary then anymore.


That would be awesome! :)


To your question about other Audio-Playback-Shields: As far as I have seen it, all other audio-shields contain a dedicated processor that reads the audio-data from storage and feed it to an audio-DAC. For a good sound the DAC must be feed with low jitter at the audio rate of the audio material, otherwise you may recognize audio distortions like slowdowns or stuttering. With a dedicated processor it doesn't matter what your Arduino does while audio is playing, but my library is for all those who don't want to spend extra money to such a thing. SimpleSDAudio get the most out of the AVR's by pushing the Arduino processor strongly to its limits - that's the price you have to pay if you want nice audio from that little thing.


Thanks for the info!
I think MP3 decoder shield might have such processor, but not WaveShield. From description  (http://www.ladyada.net/make/waveshield/design.html)they only have DAC with some basic low pass filters.
BTW, I'm just trying to understand how things work, not in any way implying anything bad about your library. In fact I think it's brilliant work, nobody else did anything like this with no external hardware (other than SD card)!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 04, 2013, 07:58 pm
You are right, WaveShield doesn't have an additonal processor so the AVR has to cope with every sample. In the end, the external DAC mainly give the convenience that you don`t have to convert the sample rate of the audio file. I think WaveShield perfektly fits the hole between my radical simple hardware library and shields that came with additional controller.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: AllanB on Jan 06, 2013, 10:38 pm
Thanks for this library. It works like a dream.
For the fun of it, are there any way to speed up or slow down the speed. You know, making Schwarzenegger sound like Mickey mouse?
/Allan
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: UnaClocker on Jan 07, 2013, 04:08 am
I saw a video on YouTube where it appears someone has this working on the Due. Has anyone tried it on the Teensy 3.0 yet? I'd imagine the Due and Teensy3 could decode an actual WAV file..
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 10, 2013, 06:31 am








update:
Sorry to mislead.. after some more tests.. I see this is really just an IDE 1.0 thing..

I tried to load another sketch (blink).. to my +3.3v/8MHz internal clock board.. and it gave same errors..

I opened IDE v.23 and the blink program loaded just fine... without error..


(the only problem now is.. SimpleSDAudio doesnt work with any IDE under 1.0....right?)



thanks!


Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: AllanB on Jan 13, 2013, 02:01 pm
Hi Tuttut
I would love to be able to read a text-file from the SD-Card to read some default settings to initialize my music-box. Would that be possible to add to the library without too much effort?
/Allan
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 13, 2013, 11:44 pm
Hi,

@xl97: I don't know if my lib works under Version below 1.00, but I think other people tried it as well and got it running, but I am not sure. Maybe you can try, within the last version of my lib I included at least something that picks other Arduino-default libs for versions below 1.0, but I never tested it.

@AllanB: My lib uses a own SD card implementation, but you could use this also to access other files on card. It is based on 3 layers: l0 does the hardware access to sd-card - you only have to change this if you want to use this lib on a different architecture. l1 gives access to sectors (sector read/write), whereas l2 gives access to filesystem. Using SD_L2_SearchFile you can find the first cluster of a file on card. Use then SD_L2_Cluster2Sector to get the appropriate sector that belongs to the file and finally read the sector using  SD_L1_ReadBlock. Analyse the SimpleSDAudio.cpp to see how it works. It's not hard, but very low level...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 14, 2013, 12:09 am
hi Tuttut-

dont mind me!..

although it would be great if it did work with IDE v23  (and someone posted a 'how to')....

my realy problem is with IDE 1.0 (and not your lib at all)..

I made a minimal/breadboard hardware set-up (+3.3v @ 8MHz internal clock)... purpose built to use your lib for the project.

However.. my '3.3v/8MHz breadboard bootloader chip does NOT work with IDE 1.0 out of the box..

so Im reading up on how to make it 'compliant'..  (something to with boards.txt edits... and maybe another step as well?)

When I couldnt get the BLINK sketch to upload either.. I knew it was board/IDE problem.


thanks!

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 14, 2013, 12:57 am
Hi xl97,

even it's off-topic, one of my next project I am working on is an special Arduino board with library for very low power applications. I already got my own bootloader for mega328 with 8 MHz internal clock (but 32kHz crystal-calibration) to work - I placed a boards.txt in a folder under <MySketches>/hardware/<my_arduino_board_name>. Compared to your file, it contains two lines that seems to be important for compilation:
Code: [Select]
gcduino168.build.core=arduino:arduino
gcduino168.build.variant=arduino:standard
 
Maybe that info will help you...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 14, 2013, 01:12 am
cool!

cant wait to see it..

Im using a TQFP 3.3v/8MHz minimal design (no regulator).. running off coin cell..

whole pcb is round and smaller than 1"..  (plus has SD socket on bottom!)..  has no room! lol

I just fired up IDE 1.0

and added this line to my breadboard board.txt file:  (at the end)

atmega328bb.build.variant=arduino:standard


that seemed to be all I needed..   compiled and uploaded sketches.. works fine now.


I have a question about your diagrams for filters out the audio feed..

in some/many demos..  you say just use a 100Ohm resistor from D9 output.. before the speaker?..
and in some diagrams..  you have a 100uF cap ( - side to D9) between D9 and speaker..


My D10 is already fixed for the SD CS pin...   so I cant use both D9 and D10 for better output..

but would like to learn more/better understanding about low-pass filters..etc  and what can be done to (sorta) reduce the static/noise on the single D9 output approach..

I know a proper filter and amp would be best.. but there wont be any of that on this 'current' project


thanks!!


Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Jan 14, 2013, 01:45 am
Since I've decided to use the 1284P and 644P for the benefit of the extra RAM, FLASH and EEPROM, I've been testing various things to see if everything will work. Obviously the 1284P isn't an official Arduino MCU so it requires some customisation to set everything up.

One thing I was worried about was SimpleSDAudio due to the use of the specific PWM pins and Timers. This turned out to be well founded and so I spent this evening investigating and trying to work a solution.

The other issue is that there are a few variants of pin mapping in use. I'm using the Bobuino variant that puts SPI across pins 10,11,12,13 and RX0/TX0 on D0/D1, to keep some consistency with Uno. There is also a 'standard' mapping that is the same as the Sanguino for the 644P

I managed to get it working in 1.01 and then moved to 1.02 and tried the same fix. So...

I have edited SimpleSDAudioDefs.h and added a new MCU entry for the 1284P and 1284, with both Bobuino and standard pin mappings. I also edited the 644P/644 entry to provide Bobuino pin mapping option, as I will use this with any 644 I use.

I also noticed that only the 168/328 entry has been updated to the Stereo 16 bit usage at the moment. Although I added the additional pins for PWM3 and PWM4. I've left them commented out as my knowledge doesn't extend to confirming if the register entries below it are correct for the 1284.

On the 1284 the OC0A and OC0B are on PB3 and PB4, rather than PD6 and PD5, as per the 168/328. The PWM1 and PWM2 are the same as 168/328 and certainly my 1284 works fine in 8 bit fullrate mono and 8 bit fullrate stereo now. The PWM4 conflicts with SPI SS again, as per the 328.

I wonder if it would be possible to incorporate this into the library direct to save it having to be applied by hand on updates? Maybe you could check if the 'QUAD' options are correct or need some amendement before possibly enabling.

I added the 1284 entry above the 644/Sanguino entry. Remove any comments by me as you see fit. They are just there to highlight what I've actually altered.

Code: [Select]
// ADDDED FOR ATMEGA1284P and 1284 COMPATIBILITY - M BEEBY
#elif defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__)
// Mighty1284P & Bobuino

    // Standard pinmap, same as Sanguino
    //#define SSDA_PWM1_PIN 13 // OC1A
    //#define SSDA_PWM2_PIN 12 // OC1B
    //#define SSDA_PWM3_PIN 3 // OC0A PB3 - NOTE 328 IS DIFFERENT, ON PD6
    //#define SSDA_PWM4_PIN 4 // OC0B PB4 (collision with SPI SS!) - NOTE 328 IS DIFFERENT, ON PD5

    // Bobuino pinmap
    #define SSDA_PWM1_PIN 8 // OC1A
    #define SSDA_PWM2_PIN 30 // OC1B
    //#define SSDA_PWM3_PIN 7 // OC0A PB3 - NOTE 328 IS DIFFERENT, ON PD6
    //#define SSDA_PWM4_PIN 10 // OC0B PB4 (collision with SPI SS!) - NOTE 328 IS DIFFERENT, ON PD5

   
    // Output-compare settings
    #define SSDA_OC1L    OCR1AL
    #define SSDA_OC2L    OCR1BL
//#define SSDA_OC3L    OCR0A
    //#define SSDA_OC4L    OCR0B
    #define SSDA_OC1H    OCR1AH
    #define SSDA_OC2H    OCR1BH
   
    // Register to backup and restore
    #define SSDA_OC_CR1_REG             TCCR1A
    #define SSDA_OC_CR2_REG             TCCR1B
//#define SSDA_OC_CR3_REG             TCCR0A
    //#define SSDA_OC_CR4_REG             TCCR0B
   
    // Always: Prescaler = 1, Fast-PWM-Mode with 8-Bit
    #define SSDA_SINGLE_OC_ENABLE()     { TCCR1A = _BV(WGM10) | _BV(COM1A1); TCCR1B = _BV(WGM12) | _BV(CS10);}
    #define SSDA_DUAL_OC_ENABLE()       { TCCR1A = _BV(WGM10) | _BV(COM1A1) | _BV(COM1B1); TCCR1B = _BV(WGM12) | _BV(CS10);}
    #define SSDA_DUAL_OC_BRIDGING()     { TCCR1A |= _BV(COM1B0); }
//#define SSDA_QUAD_OC_ENABLE()       { TCCR0A = _BV(WGM00) | _BV(WGM01) | _BV(COM0A1) | _BV(COM0B1); TCCR0B = _BV(WGM02) | _BV(CS00);}
    //#define SSDA_QUAD_SYNC() { TCNT1 = 0; TCNT0 = 0; }
    #define SSDA_OC_INT_DISABLE()       { TIMSK1 &= ~_BV(TOIE1); TIFR1 |= _BV(TOV1); }
    #define SSDA_OC_INT_ENABLE()        { TIMSK1 |=  _BV(TOIE1); TIFR1 |= _BV(TOV1); }

    #define SSDA_OC_INTERRUPT           TIMER1_OVF_vect

//------------------------------------------------------------------------------
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
// Sanguino

//Original standard pin mapping
    #define SSDA_PWM1_PIN 13 // OC1A
    #define SSDA_PWM2_PIN 12 // OC1B

// Bobuino pinmap - Added by M BEEBY
//#define SSDA_PWM1_PIN 8 // OC1A
    //#define SSDA_PWM2_PIN 30 // OC1B
   
    // Output-compare settings
    #define SSDA_OC1L    OCR1AL
    #define SSDA_OC2L    OCR1BL
    #define SSDA_OC1H    OCR1AH
    #define SSDA_OC2H    OCR1BH
   
    // Register to backup and restore
    #define SSDA_OC_CR1_REG             TCCR1A
    #define SSDA_OC_CR2_REG             TCCR1B
   
    // Always: Prescaler = 1, Fast-PWM-Mode with 8-Bit
    #define SSDA_SINGLE_OC_ENABLE()     { TCCR1A = _BV(WGM10) | _BV(COM1A1); TCCR1B = _BV(WGM12) | _BV(CS10);}
    #define SSDA_DUAL_OC_ENABLE()       { TCCR1A = _BV(WGM10) | _BV(COM1A1) | _BV(COM1B1); TCCR1B = _BV(WGM12) | _BV(CS10);}
    #define SSDA_DUAL_OC_BRIDGING()     { TCCR1A |= _BV(COM1B0); }

    #define SSDA_OC_INT_DISABLE()       { TIMSK1 &= ~_BV(TOIE1); TIFR1 |= _BV(TOV1); }
    #define SSDA_OC_INT_ENABLE()        { TIMSK1 |=  _BV(TOIE1); TIFR1 |= _BV(TOV1); }

    #define SSDA_OC_INTERRUPT           TIMER1_OVF_vect

//------------------------------------------------------------------------------
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 19, 2013, 04:24 am
@allenb -  *or anyone*

have you made any head way getting the SD lib to have some file reading capabilities yet?

I too would like to be able to use same lib to grab a few params/vars from a text file to be used in a sketch that also uses the SimpleSDAudio lib for audio playback


I read the brief comment left by Tuttut about looking at the lib ..and I havent got that far into it yet..(and dont really have high hopes or figuring it out by myself anyways!)  lol..

figured Id ask before I dive in next week



thanks!!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 19, 2013, 08:57 pm
Hi,

here an example how to read a file with the very low-level SD-sector-access commands from SimpleSDAudio-Library:

Code: [Select]

/*
Simple SD Audio example, prints content of TEST.TXT from SD card.

This example shows how to use the SimpleSDAudio library embedded low-level file access.
You need:
- An Arduino with ATmega368 or better
- An SD-Card connected to Arduinos SPI port (many shields will do)
   -> copy TEST.TXT on freshly formated SD card into root folder

See SimpleSDAudio.h or our website for more information:
http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

created  19 Jan 2013 by Lutz Lisseck
*/
#include <SimpleSDAudio.h>
#include <sd_l2.h>
#include <sd_l1.h>

// Create static buffer (shared for all file access, because mega328 are quite low on RAM!)
#define BIGBUFSIZE (2*512)      // bigger than 2*512 is often only possible on Arduino megas!
uint8_t bigbuf[BIGBUFSIZE];

SD_L2_File_t TxtFileInfo; 

// helper function to determine free ram at runtime
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void setup()
{
  uint8_t retval;
 
  // Open serial communications and wait for port to open:
  Serial.begin(9600); while (!Serial) {}

  // Setting the buffer manually for more flexibility
  SdPlay.setWorkBuffer(bigbuf, BIGBUFSIZE);

  // Using F("...") to avoid wasting RAM 
  Serial.print(F("\nInitializing SD card...")); 
 
  // If your SD card CS-Pin is not at Pin 4, enable and adapt the following line:
  // SdPlay.setSDCSPin(10);
 
  if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO)) {
    Serial.println(F("Initialization failed. Error code:"));
    Serial.println(SdPlay.getLastError());
    while(1);
  }

  Serial.print(F("Free Ram: "));
  Serial.println(freeRam());

  Serial.print(F("Looking for TEST.TXT... "));
  // Search for file TEST.TXT in Rootdir (=cluster 0), search shortname files only (0x00,0x18)
  retval = SD_L2_SearchFile((uint8_t *)"TEST.TXT", 0UL, 0x00, 0x18, &TxtFileInfo);
  if(retval) {
    Serial.println(F(" not found on card! Error code: "));
    Serial.println(retval);
    while(1);
  } else {
   Serial.println(F("found."));
   Serial.print(F("First sector: "));
   Serial.print(TxtFileInfo.ActSector);
   Serial.print(F(" Size: "));
   Serial.println(TxtFileInfo.Size);
  }   

  while(TxtFileInfo.ActBytePos < TxtFileInfo.Size) {
    // read one sector
    retval = SD_L1_ReadBlock(TxtFileInfo.ActSector++, &bigbuf[0]);
    if(!retval) {
      uint16_t cnt = 0;
      // print sector content until 512 bytes or file length is reached
      while((cnt < 512) && (TxtFileInfo.ActBytePos < TxtFileInfo.Size)) {
        cnt++;
        TxtFileInfo.ActBytePos++;
        Serial.write(bigbuf[cnt]);
      }
    } else {
      Serial.println(F("Err read sector. Error code: "));
      Serial.println(retval);             
      while(1);
    }
  }
  Serial.println("done.");
}

void loop(void) {
}


I will include this example in later versions of the lib...
I had to edit this code in a way that the Audio-Lib shares the same buffer as that is used for sector-read because only that way it should fit to ATmega328 that is quite low on RAM.

Tuttut
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: miriel90 on Jan 21, 2013, 10:38 pm
Hi! We're trying to run the library with an Arduino Duemilanove and the Breakout Board for SD-MMC Cards. We´re having troubles when we try to run the Bare Minimun with debug and at the serial output we get an error code: 1

We've checked that our SD card is correctly wired and with the  free RAM method we've got a 708...

So what does this mean? Sorry, English is not my native language...

We don't know why the code isn't running, if is the RAM or another point that we cannot see at this time

Can you help us?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 21, 2013, 11:06 pm
Hi, error code 1 is a sign that there is something wrong with the SD-Card connection, RAM is no problem. Have you used level-shifters to ensure that the SD-card only get 3.3V? Otherwise you can damage the card. Are you using any kind of shield for the SD-card? You find also info about wiring the SD-card in the file SimpleSDAudio.h, this also explains how to build the level shifters.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 21, 2013, 11:14 pm

Hi! We're trying to run the library with an Arduino Duemilanove and the Breakout Board for SD-MMC Cards. We´re having troubles when we try to run the Bare Minimun with debug and at the serial output we get an error code: 1

We've checked that our SD card is correctly wired and with the  free RAM method we've got a 708...

So what does this mean? Sorry, English is not my native language...

We don't know why the code isn't running, if is the RAM or another point that we cannot see at this time

Can you help us?


sounds like problem with SD card set-up...


how is it set-up?

what breakout board are you using?  Do you have any pics of the wiring/set-up?

I have used this with the following with 'success':

1.) Arduino Duemilanove 2009 board with  a SeeedStudio SD shield  (has bot SD and micro SD)  http://www.seeedstudio.com/depot/sd-card-shield-p-492.html

2.) have created a custom 'Arduino' board, all SMD, with on-board microSD socket, this runs at +5v/16MHz.. with a lever shifter for the SD card (and +3.3v regulator)

3.) a BARE minimum 'Arduino' circuit... running at +3.3v native logic.. and INTERNAL 8MHz clock.. with on-board micro SD card..  (running direct connect, no lever shifter needed or any voltage divider)

and after working through some of MY mistakes.. all have worked great and as described.



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: miriel90 on Jan 21, 2013, 11:37 pm

Hi, error code 1 is a sign that there is something wrong with the SD-Card connection, RAM is no problem. Have you used level-shifters to ensure that the SD-card only get 3.3V? Otherwise you can damage the card. Are you using any kind of shield for the SD-card? You find also info about wiring the SD-card in the file SimpleSDAudio.h, this also explains how to build the level shifters.


Yes we used level-shifters but we used a wiring configuration different from the wiring of the SimpleSDAudio.h... so we're going to change our wiring. We're using this shield https://www.sparkfun.com/products/11403? for the SD-card and the configuration we've used previously is  this:

D2 nothing
D3 Chip Select line (CS) needs pull down resistors
CMD pin 11, no pull down resistors
CD nothing
CLK clock connect to pin 13, needs pull down resistors
VCC 3.3V
GND ground
D0 pin 12, needs pull down resistors
D1 nothing
WP nothing

I found it in the same page of Sparkfun...

So, the D2 pin of the Breakout Board is the CS?

Thanks for your answers! :D
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: DavidFMarks on Jan 22, 2013, 05:06 pm
I have set up my sd card and successfully played the example program (although for some reason it doesn't work with the two resistors)
My problem is how to produce my own files as I cannot understand exactly what I am supposed to convert my wav file to. I have downloaded the SOX program as suggested and haven't a clue how to use it. I downloaded a guide but find it totally incomprehensible. Please, is there a simple explanation for ancients like me with a shortage of grey cells !
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 22, 2013, 05:27 pm
hi-

in the library .zip file .. there is a directory called 'tools'..
(http://hackerspace-ffm.de/wiki/index.php?title=Datei:SimpleSDAudio_V1.02.zip)   <-- latest version posted is v1.02



SimpleSDAudio\tools


Inside that you had three more directories:

Arduino with 8 MHz
Arduino with 16 MHz
sox_win
&
ReadmeSimpleSDAudio.txt


(the readme explains all of this)

so you take your /wav file of choice, that you want to convert..(the file format accepted/used by SimpleSDAudio is .afm)

if you need are using an 8MHz board/clock.. then you would open/go into the Arduino with 8MHz folder.. and drag your .wav file over the conversion you want done/format you want to end up with.

which is either FULL or HALF rate.. and either MONO or STEREO

if your board is running a 16MHz clock.. then you do the same in the Arduino with 16MHz directory...

after you drop the file on the correct .bat file you want.. you will be prompted to press any key from a command prompt (CMD) window.. 

this will created a folder called 'converted' in the directory you just dropped the .wav in.. and inside will be your new, ready to use .afm file.




Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: DavidFMarks on Jan 22, 2013, 06:03 pm
That's brilliant - thanks very much - works a treat and with good sound. There will now be a period of silence whilst I figure out how to select and play specific files from a list. I presume that this is possible if not perhaps someone could tip me off to save me from hurting my brain !!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 22, 2013, 06:15 pm
there is a demo provided whre it lists out all .files on the SD card..

and you can enter it in by name (in the serial monitor)..

and you can then P = play S= stop...etc..etc  (its outlines the commands)

I bet if you tear that demo apart you'll be able to cut out those snippets you want
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: DavidFMarks on Jan 22, 2013, 11:42 pm
That's great, many thanks.. I'll have a crack at it
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: DavidFMarks on Jan 23, 2013, 01:05 am
Been studying the demo sketch and can see roughly what bit is doing. I am trying to find out how to issue a serial command from within the program (rather than via the serial monitorto select and play a file. I'm afraid I am very new to Arduino and am perhaps taking on too much here but I just cant see how to do it.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 23, 2013, 01:31 am
Hi folks, good news from me:  8)
I've updated the library and now you don't need to call worker() anymore if you provide the SSDA_MODE_AUTOWORKER flag at initialization. I've also added a doorbell (with ding-dong-sound) example, the SD card file access example and edited the examples for autoworker-function. Also there is the fancy AbsoluteMinimum-Example to play the example-audio-file from card that contains just this:
Code: [Select]

/*
SimpleSDAudio absolute minimum example, plays file EXAMPLE.AFM from root folder of SD card (CS on pin 4)
through speaker/amplifier at pin 9 for ATmega328 / pin 44 for ATmega1280/2560.
*/
#include <SimpleSDAudio.h>
void setup()
{
  // SdPlay.setSDCSPin(10); // Enable if your SD card CS-Pin is not at Pin 4...
  SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER);
  SdPlay.setFile("EXAMPLE.AFM");
  SdPlay.play();
}

void loop(void) {
}


Enjoy!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Jan 23, 2013, 04:21 am
nice job..

(for those lazy.. here is the link to the lib:  http://hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio#Download)

  So using what you've posted.. all you need to do in the MAIN loop..

for a button 'check/press' is:


(dummy code:)

Code: [Select]
if(digitalread(button1) == LOW){
     SdPlay.setFile("EXAMPLE2.AFM");
     SdPlay.play();
}else if(digitalread(button2) == LOW){
     SdPlay.setFile("EXAMPLE3.AFM");
     SdPlay.play();
}


etc..etc..

no need to init or de-init anything?

the more demos showing all the functions and features make for popular usage!!..

I still have gotten to the 2/4 channel stuff I saw mention.. or how all that works!  lol..

(side question and really more a general hardware questions.. is there any other things we can add to the single output on D9 to make it sound a bit better?..  I only have a 100uF cap right now.. no resistors any thing)..

I dont/wont have enough room to have a pot/wiper and a ton of extra components.. but if adding another cap or resistor or two will help improve..  Id like to try!).. I saw some examples use a resistor.. and some use only a cap..etc.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Jan 23, 2013, 11:19 am
@Tuttut, did you see my post at #84 about use on the 1284P? Thanks.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: DavidFMarks on Jan 23, 2013, 12:34 pm
Thanks once again .. I'll get to work on that. It's amazing how I can spend several hours getting nowhere and then you guys come up with a nice straightforward solution that leaves me wondering why I didn't think of that ! GRRRR. Anyway many thanks for the help, its greatly appreciated.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 23, 2013, 01:14 pm
Hi,
@tack: have you looked inside the new version? I think I've put your stuff in, but it would be nice if you can try if also autoworker works on your platform as it needs additional stuff in those hardware-settings.

@xl97: You still need the init function that does a lot internally like setting up the file-system and configuring the audio ports. For Button example see the doorbell example that is also new in my library.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: g_u_e_s_t on Jan 26, 2013, 11:21 am
hello Tuttut

i just finished an analysis of pwm distortion, and then thought it would be cool to make a good and cheap wav player.  and it turns out it is cool, and you have already done it.  thanks for the work, i always enjoy finding projects like this.  if you are open to suggestions, here are some things that my research has shown to make improvements in the audio quality.

1. use 14b, phase correct pwm, at 62khz clock rate.  you never really get the full 16b anyways, even with perfect resistors, due to distortions building up in the noise floor.  also, perfect resistors are difficult to come by, even with trimming, due to the variability of the internal resistance of the arduino.

2. use 3.9k / 499k resistors for the mixing.  the output resistance is around 40ohms, so this keeps its error component low in comparison to the 3.9k.

3. dont bother with the external logic chips, they have a lot of jitter in comparison to the arduino itself, and introduce phase modulation and associated distortions.  also, the noise floor on the arduino i tested was -110dB, which was below the pwm noise floor for frequencies above 1kHz.  with the usb disconnected, the arduino isnt that bad.

4. you can try changing the depth / location of pwm to get further gains, but its probably not too significant for audio (as compared to pure tones), as the maximum amplitude is usually low anyways.

here are the writeups if youre interested:

distortion analysis:
http://www.openmusiclabs.com/learning/digital/pwm-dac/pwm-distortion-analysis/

dual pwms:
http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/

again, great work, im looking forward to trying it out.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: WilliamK Govinda on Jan 26, 2013, 11:40 am
I'm loving this, already using it in a solar-powered project.

Now, maybe I'm daydreaming, but I would love to be able to output AM Radio Modulation instead of audio.  ]:D

http://dangerousprototypes.com/2011/10/05/am-sofware-radio-using-arduino/

Code:
http://dangerousprototypes.com/forum/download/file.php?id=5107&sid=9ed56f436c83604b287f75ec73f11146

(http://dangerousprototypes.com/forum/download/file.php?id=5105&t=1&sid=9ed56f436c83604b287f75ec73f11146)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 28, 2013, 12:47 am
Hi g_u_e_s_t,
a warm welcome on the journey of pushing the audio quality from 1-bit (and 2-bit) outputs to new frontiers! Raising audio quality from such limited systems is a challenging task but I am amazed how far we get. Some years ago I also shared the opinion that without an additional DAC it would be hard to get audio out of an AVR that sound far better than telephone.   
 
I read your writeups about PWM distortion and - at least - tried to understand them. I think you did a very good theoretical work, even I didn't understand everything yet. But I think you did a really great work toward raising audio quality out of such constrained systems and breaking actual known limits. Some time ago I started my journey by coding a high-order delta-sigma-modulator that converts audio-files to pulse-dense-modulated single bit-streams that I played back through the SPI port of the AVR at rates of up to 2 MBit/s. That way I moved most of the quantization noise out of the audible band, but for whatever reason, the quality on real-world hardware was worse than expected and because it is not possible to do mixing easily with pulse-width-modulated data I stopped my efforts. I wanted then to make something that makes good audio quality playback as easy as possible to use and with minimum hardware effort and started SimpleSDAudio.

With your research results I think we should try to get a step further in quality, but it's time to leave theoretic and try it at the real thing. Let's try if and when phase-correct PWM really sound better than fast PWM. Does it make sense for 2-bit systems to go from 16-bit to 14-bit (or even less) for better results? How about pre-filtering the input audio files to something like PWM-Freq/4? We will loose some high-frequency audio-information but maybe reduce perceived noise also.

You measured -110dB noise floor, I can't believe this really. When SimpleSDAudio stopped at a fixed PWM value, there is really no audible noise, but how about when it is accessing SD card and the AVR has to work harder? I thought the noise is much higher than but maybe I am wrong and that noise is really only from those artifacts you described - I have to try again...

Also interesting that Ti-paper about logic outputs. I wondered why it is so hard to drive speakers at reasonable volume, but with a 74AC14 it should be again worth a try  to drive a speaker as this thing cost only a quarter Euro.

Keep on your good work! I look forward to see what happens if you apply your thoughts to real hardware...

@WilliamK: Interesting thing that AM modulation. BTW: hook up a laser-pointer or a focused LED to the digital audio output pin and receive it over quite a distance using a small solar-panel from garden-light connected to an amplifier - it works great.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: g_u_e_s_t on Jan 28, 2013, 01:02 pm
hello Tuttut,

one more thing.  you can pre-distort a wav file so that it plays back identical to the source material.  the pwm transform is a known function, and although not invertible, it can be compensated for perfectly.  i have yet to implement this, but i have read research papers on it, which prove it mathematically.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Jan 29, 2013, 12:22 pm

Hi,
@tack: have you looked inside the new version? I think I've put your stuff in, but it would be nice if you can try if also autoworker works on your platform as it needs additional stuff in those hardware-settings.


OK, I've now had time to test it and I can report that it works perfectly 'out of the box'. Many thanks for adding those mods to the definitions as it will save re-applying them in future.

I've also tested the Autoworker mode and that also works fine on the 1284P. It has been tested with a 3 minute music file of 27Mb size and it played perfectly in 8 bit stereo full rate, sounding good through a set of hacked active PC speakers.

At the moment this is just running with a 100R in series with each channel. I want to use this now with a little 3W stereo amplifier as an onboard solution. - http://www.technobase.jp/eclib/OTHER/DATASHEET/pam8403.pdf

Any thoughts on input filtering/control prior to the amp? At the moment I'm thinking of a .1uF capacitor in series and a 10k trimmer to control the input level, as per attached schematic. I don't need to be able to adjust volume by the user, just set it and leave it.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jan 29, 2013, 12:37 pm
The amplifier's datasheet uses an 0.47uF input capacitor, if this is already there you don't need the additional 100nF one in series. The trimmer is ok, you want it otherwise it will be to loud. If audio output is to noisy try adding a capacitor after the trimmer to GND to do a little low-pass filtering. I don't know a value but experiment in range of 100nF to several uF for best results.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 08, 2013, 12:46 am
I've added the additional cap pads to my design but I can always jumper them out for testing on the prototype boards.

One thing I am doing is setting a 28 pin DIL socket inside my 40 pin one, with some approrpiate 328P pins joined through to 1284pins. This lets me use a 328P on the same board if I don't need all the peripherals or FLASH/SRAM of the 1284P/644P.

On the 1284P the 2 pins used for Channel 1 & 2 (8 Bit Stereo Full Rate) don't clash with anything else. On the 328P Channel 2 is Pin 10, clashing with SPI hardware SS.

I saw the wiring.c patch for the timers, saying that pin 6 & 5 can be used to get 16 bit stereo at half rate. What I would like to do, is use 6 & 5 instead of 9 & 10 for the default 8 bit stereo. Is this possible? I tried making a few changes to the defs file but realised it needs some of the hardware timer definitions altering too if it is possible to make it work.

If possible then It would be ideal if there was a setup parameter to use the alternate pins IF the patch is applied. I'm sure this would be useful for 328 users who want 8 bit stereo but use Ethernet shields or other SPI devices.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 09, 2013, 05:20 pm
First, hardware SS is often only an issue when SPI is used as slave, which is often not the case. Second, to use the pins 6 & 5 on mega328 Arduinos, you have to apply the wiring.c patch as you already figured out and then you have to patch the file SimpleSDAudioDefs.h. Scroll to the end and you find the last big #else part that sets up all the stuff for mega328 Arduino. Below that, there is the same part again but this time for use pin 6 & 5, but it is commented out. Rework the comments that the old #else-part for pins 9 & 10 will become commented out and activate the part below instead. Then audio will use pin 6 & 5, but it requires the wiring.c patch. Beware, I have not tested that thoroughly so please leave a note if it works for you.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 09, 2013, 06:54 pm
Hi,

Does this also work with Arduino with ATMEGA168 only?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 09, 2013, 08:12 pm
Hi, I am sorry, I think the minimum requirement is ATmega368 ATmega328P. The ATmega168 is to low on RAM.7
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 09, 2013, 08:37 pm
How about ATMEGA 328.
Sorry. I don't know which is which.

Additional: I tried converting a .wav file but no file appears on the "converted" folder I created.
Is there any requirement for the format of the wav file?
How do I choose the appropriate batch file?
A real newbie in here, hope you understand.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 09, 2013, 08:56 pm
@Tuttut - sorry, I didn't realise that section was there. I'll give that alternativ section a try and report back on whether it works ok. Many thanks again, it's very much appreciated.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 09, 2013, 09:01 pm

How about ATMEGA 328.
Sorry. I don't know which is which.

Additional: I tried converting a .wav file but no file appears on the "converted" folder I created.
Is there any requirement for the format of the wav file?
How do I choose the appropriate batch file?
A real newbie in here, hope you understand.


It works fine in both the 328 and the 328P.

You need to choose the batch file for the playback rate and type you want. I have used 8 bit Mono Fullrate and 8 bit Stereo Fullrate and find the quality very good with a set of PC 2.1 active speakers.

If you are struggling for cycles (a processor intensive sketch) then you may want to try the Halfrate variants.

I've not found any problems with any Wav files at all. I've used downloaded movie/TV sound effects and also used freeware converters to convert a music track MP3 to Wav and then drop on a batch file to convert to 8 bit Stereo Fullrate .asm file, that then played very nicely in SimpleSDAudio
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 09, 2013, 09:31 pm
Hi,

What free converter did you use?
What are the settings like encoding etc?
This is killing me for quite a while now  :P

I have a .wav file.
attributes: 64000 Hz, 8-bits, mono.
format: PCM uncompressed

On the command prompt, it says:
A subdirectory or file converted already exists.
Press any key to continue . . .
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 10, 2013, 12:06 am
Hi,
maybe you have a Wav-File that contains something that sox is not aware of, try converting it using commandline and verbose mode of sox. Or try a program like Audacity to import and export the file to a proper PCM Wav-file.
Maybe you even look at the wrong path of the converted folder...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 10, 2013, 02:57 pm
I'm not at home to check what file converter I used.

The command line message you got, about a subdiretory or file already converted, is normal. Once you already have a 'converted' folder then that message always appears, but you should find your newly converted file inside that folder.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 10, 2013, 04:39 pm
I'm ok now.
I redownloaded the zip file.
Maybe an error on the first zip file downloaded was the cause.

Question:
What pins are to be connected to the SD card.
This is my arduino: http://www.e-gizmo.com/KIT/Gizduino.html
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 10, 2013, 10:44 pm

Question:
What pins are to be connected to the SD card.


D4 - SS or CS
D11 - MOSI
D12 - MISO
D13 - SCK


First, hardware SS is often only an issue when SPI is used as slave, which is often not the case.


Yes, on the 328P it was working OK on 9 & 10 with SD Card used on SPI and with D4 as SS. On my new PCB's I could also be using radio and ethernet modules on SPI (I know they work together), as well as SimpleSDAudio, although any sounds would only be played when those devices aren't being used. I thought it would be cleaner if I could use 6 & 5 instead.


Second, to use the pins 6 & 5 on mega328 Arduinos, you have to apply the wiring.c patch as you already figured out and then you have to patch the file SimpleSDAudioDefs.h. Scroll to the end and you find the last big #else part that sets up all the stuff for mega328 Arduino. Below that, there is the same part again but this time for use pin 6 & 5, but it is commented out. Rework the comments that the old #else-part for pins 9 & 10 will become commented out and activate the part below instead. Then audio will use pin 6 & 5, but it requires the wiring.c patch. Beware, I have not tested that thoroughly so please leave a note if it works for you.


Patches all made and audio works perfectly now switched to Pins 6 & 5. Tested in 8 bit Stereo Fullrate. Many thanks again. :-)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: purgedsoul on Feb 13, 2013, 12:23 pm
Forgive me for asking this, I'm just recently learning about SPI and I2C. But can I use an I2C device (specifically an accelerometer e.g. ADXL345) together with this library? My plan is to play a sound based on the accelerometer's inputs.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 13, 2013, 06:09 pm
The audio lib uses a timer and the hardware SPI. I2C is often a different hardware in uC, so I2C should still work beside the audio lib. For additional SPI devices also software-SPI might be an option and that way it should be possible to run SPI devices on pins not already used by the audio lib as well. So just give it a try.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 16, 2013, 06:22 am
Hi,

I used arduino with atmega324.
Connected sck of sd card to sck of arduino.
miso of sdcard to miso of arduino.
mosi of sd card to mosi of arduino.

I connected cs of sd card at pin4 of arduino.
and tried to get audio output at pin 9 and then at pin 10 but no luck.
I tried the examples at simplesdaudio.

My speaker is 8 ohms 1 watt.
What could be the problem?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 16, 2013, 02:33 pm
1: I don't know if the lib work with ATmega324 and I don't know Arduinos with that processor. The typical processor is ATmega328.

2: Have you use level-shifters or does your Arduino run with 3.3V only? If the Arduino is 5V you need level-shifters or you could broke your SD card. The simplest way to build a level-shifter is using two resistors for every of the four input pins at the SD card. A description can be found in file SimpleSDAudio.h.

3: You have to power the SD card as well - connect GND to pin 3 and 6 of SD-card and connect pin 4 to the 3.3V output of the Arduino.

4: If there is no sound try the example BareMinimumWithDebug first and look at the output from the serial port. This can give you an indication if your wiring is still wrong or if there is something wrong with the filesystem on card or the file. You can post this output here in the forum to get more help.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 06:24 pm
Quote
1: I don't know if the lib work with ATmega324 and I don't know Arduinos with that processor. The typical processor is ATmega328.

It is sold here. http://www.e-gizmo.com/KIT/gizduino+%20164,324,644.html
Quote
2: Have you use level-shifters or does your Arduino run with 3.3V only? If the Arduino is 5V you need level-shifters or you could broke your SD card. The simplest way to build a level-shifter is using two resistors for every of the four input pins at the SD card. A description can be found in file SimpleSDAudio.h.

It has 3.3V.  No need for level shifters.
Quote
3: You have to power the SD card as well - connect GND to pin 3 and 6 of SD-card and connect pin 4 to the 3.3V output of the Arduino.

Did that already.
Quote
4: If there is no sound try the example BareMinimumWithDebug first and look at the output from the serial port. This can give you an indication if your wiring is still wrong or if there is something wrong with the filesystem on card or the file. You can post this output here in the forum to get more help.
It failed the first test. And I am not certain where to connect the cs pin. Digging the datasheet of 328 and 324 does not help. I am having a hard time understanding both.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 06:29 pm
Do you think this board will work for this library?

http://www.e-gizmo.com/KIT/Gizduino.html
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 06:40 pm
I think the library has the CS pin default to pin 4 (D4)

but there is a line in sketch that allows you to set it to whatever pin you want..

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 07:52 pm
After connecting the SPI pins on corresponding pins, CS to pin 4, 100 ohm resistor to pin 10 and then the speaker, I tried measuring the 3.3 volt supply from the board and it went up to 4.3 volt. I think it's not normal. What might be the cause?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 08:09 pm
I thought the default out put was from pin 9?

and the bonus/extra pin that could be used was pin 10?

I also have never used a resistor... but instead a 100uF cap...

No clue on the voltage spike.. where your measuring?..with what?..etc..etc..

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 08:15 pm
My board has a 5V and 3.3 V.

I directly connected the MOSI, MISO, and SCK of the SD card to the MOSI, MISO, and SCK of my arduino.
I also directly connected the VCC pin of my SD card to the 3.3V of the arduino.
After connecting everything, I checked the voltage at the 3.3V pin of my arduino.
I used a fluke to measure the voltage. I got a reading of 4.3 volts.

I'll try the 100uF. It might work.
Also, I'll try connecting the audio out to pin 9.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 22, 2013, 08:16 pm
Hi, I looked over the Gizdino+ schematic: It runs on 5V, so you need level-shifters and you should test the 3v3 pin before with a multimeter to ensure that at least there is 3.3v. Second, the gizdino+-thing has sanguino pinmap, but datasheet says that there is a mapping for arduino-compatibility. Whatever, in the end you must ensure that the hardware spi pins are connected correctly to the card, so mosi to mosi, miso to miso, clk to clk and cs to pin 4 - but i dont know if in arduino or sanguino or gizdino numbering. Even if that is all correct i dont know if it will work because that clone is not very compatible to arduino. better go for the real one - at least take one with the correct cpu. the gizdino-non-plus version may work, but beware - the statement that it is 3.3v seems to be a bad typo to me...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 08:34 pm

My board has a 5V and 3.3 V.

I directly connected the MOSI, MISO, and SCK of the SD card to the MOSI, MISO, and SCK of my arduino.
I also directly connected the VCC pin of my SD card to the 3.3V of the arduino.
After connecting everything, I checked the voltage at the 3.3V pin of my arduino.
I used a fluke to measure the voltage. I got a reading of 4.3 volts.

I'll try the 100uF. It might work.
Also, I'll try connecting the audio out to pin 9.


I believe you are referring to the outputs/pins....

but this does NOT mean your board runs on +3.3v logic level..

example the Arduino UNO has +5v & +3.3v output pins....

however the boards runs on +5v logic...  (even though there is a regulator outputting +3.3v on a pin or two)



I have tested/used this library on custom boards, Uno/Duemilanove (+5v)..  and even minimal Arduino circuits running on +3v, 8Mhz internal clock  (ie: no crystal no caps..etc)


First thing is to get an SD shield that properly works with your set-up..



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 08:55 pm
Hi,

Thanks for the replies.
I had a little experiment that may help you help me.
I measured SCK of SD car to gnd: 0V
MOSI = 4.4V
MISO = 5V
CS = 5V

Added later: I guess this already shows the error on interfacing.
Do you think this http://www.sparkfun.com/tutorials/65 can already correct the error?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 22, 2013, 09:16 pm
Hi,
is it so hard to believe that your board is running on 5V and not on 3.3V even that #*&! website says something different? That you measured the 3.3V line at 4.2V is a sign that your SD card is fighting a deathly battle against the 5V. What happens is the following: The SD card is connected to 3.3V at VCC, but at 5V at one of the other pins. An internal protection diode in the card tries to clamp the excess voltage at the pin with 5V to the 3.3V supply, but that supply is also weak because the crapduino uses some 3.3V from the USB-seriell-converter chip instead of a powerful extra regulator. This way the 3.3V regulator looses the battle and its output voltage rises to 5V minus the typical diode foreward-voltage of 0.7-0.8V = 4.2V. This is not how it should be done! You can destroy your AVR, the USB-Seriell-Converter or the SD card. I don't know how long this battle can take place and who will win, but you might have already broken something. Hint: Try if your SD card still works within a PC before spending more time frying stuff...

Believe it: YOU NEED LEVEL-SHIFTERS or a SD-shield that has those!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 09:26 pm
The SD card is still working.
It still contains the DING, DONG, and EXAMPLE.

I will then construct the "DIODE" from this site.
http://www.sparkfun.com/tutorials/65
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 22, 2013, 09:31 pm
Another thing: I don't like the solutions from sparkfun levelshifter site because most of them are pretty slow. Better use a voltage divider with two resistors per line as described in SimpleSDAudio.h. This is proven to work even at fast SPI speeds as required for my lib.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 09:37 pm
if you really want to test this..

I suggest grabbing a few resistors.. and making a voltage divider, so that your LOGIC level will work correctly..

I have read about the voltage dividers being 'slow' (or too slow even).. but I have tried and tested this myself.. and it works fine for me & initial testing.

IMHO (again Im a noob!  <--- disclaimer!) .. you have +5v Arduino/board..  (period)

In order for the SD card to 'work'.. you need an Arduino that RUNS @ +3.3v logic...
or
A voltage divider between Arduino & SD card.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 09:43 pm
+5V------4.7k-----(x)-----10k------gnd

this will be for mosi, sck, and cs

MISO does not need a level shifter.

is this already correct?

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 09:51 pm
Follow this diagram (worked for me)

(http://2.bp.blogspot.com/-Py69MLr_7vs/TwWwhxXJcWI/AAAAAAAAC78/gRRKFXHgsOE/s1600/schematicuo7.jpg)

not sure the 4.7k / 10k will work..but other diagrams seem to elude to it works fine:

(http://farm7.staticflickr.com/6239/6323290363_951471d9cb_z.jpg)


make 100% sure that your +3.3v output pin on the Arduino is REALLY outputting only +3.3v
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 22, 2013, 10:09 pm
Hi,
I think both voltage dividers will work, if you don't have those 1.8k and 3.3k resistors also the 10k/4k7 solution should do it. BUT: Do you really have a CrApDuInO+gizDuino+ (the plus version)? In such a case please tell me exactly how the menu item under "Board" inside Arduino-IDE is called that you use. I can help you to get it running even on such strange Arduino board but it will need some "special handling".
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 22, 2013, 10:25 pm
I have the CRAPduino that appears on this site #?!! site.. http://www.e-gizmo.com/KIT/Gizduino.html

Only 4.7k and 10k resistors are available with me now.

The 3.3 volts pin on my crapduino outputs about 3.3 volts so it's correct.

In my voltage divider with 4.7k and 10k, i get a 3.3 to 3.4 volts accross 10k.

I use 1.0.3 IDE. Board: Gizduino (mini) with atmega 328. Programmer: AVR ISPmkII.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 22, 2013, 10:44 pm
Ok, at least this Arduino clone has a ATmega328, better than the one with the plus at the end. If you do your wiring correct and with levelshifters it should work with the lib.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 22, 2013, 10:53 pm
should work now...


voltage divider in place of the level shifter...

+3.3v output ON the +3.3v pin..

Can you run any other SD or sdFat libs to check the SD communication at all?? (be sure to check the CS pin used in the sketch)



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Docedison on Feb 23, 2013, 02:42 am
Level Shifters. One of the more important but rarely addressed subjects. for the record either the 3K9 or 4K7 resistors will work fine. There is a slightly different method that can be used to give true level shifting.  Instead of 2 resistors (Besides the bus pull-ups) a single mosfet is used.  There is truly an added advantage in that the device is fully bi-directional it is described in this app note: AN10441. I have attached it to this post.
basically the Drain connects to the 5 V side (data - I/O), The Source connects to the 3V3 side (data - I/O) and the gate connects to 3V3. I had a bunch of 2N7000's and for the 3 or 4 I've built they've worked well. A BSS138 is recommended for this device and 2 or more? should fit nicely on one of those small SMT prototype boards. I also chose the 2N7000's because I had a bunch of them but I've not found it necessary to "Select" devices to make functional 2 wire translators, all have worked and I also use them in preference to the BSS138 because I breadboard everything and interconnect and a test all of any modules before I have an idea of what the final PCB is going to be.
As a note: Adafruit sells inexpensive level shifters for 2, 4, 8 channels but I've not bothered as it takes a fet/channel and a jumper not the 6 wires that breakout board does for 2 channels.

Bob
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: purgedsoul on Feb 23, 2013, 04:12 pm
That Gizduino+ is a Sanguino clone. The SPI pins are on Digital pins D5, D6, and D7:

D5 - MOSI
D6 - MISO
D7 - SCK

and yes, level shift your pins. A simple resistor divider, as suggested, or you can use a 74HC4050 (CD4050 can be used if you can't get it locally).

connections using CD4050:

SD Card Pin----CD4050 Pin-----Gizduino+
CS--------------15         14-----D4
MOSI-----------12          11----D5
SCK------------10          09----D7
MISO----------------------------D6

the CD4050 connections can also be used with your Gizduino mini:

SD Card Pin----CD4050 Pin-----Gizduino mini
CS--------------15         14-----D4
MOSI-----------12          11----D11
SCK------------10          09----D13
MISO----------------------------D12



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 24, 2013, 08:10 pm
Unfortunately, it still doesn't work
This is my connection.
CS---------D4
MOSI------D11
SCK-------D13
MISO------D12

If I turn on the crapduino and upload absolute minimum, what readings should I get from this pins: D4, D11, D12 and D13 provided that I have not made any connection yet.

Because I am getting:
D4: 0.1 volt
D11: 5volts
D12: 0.1 volt
D13: 0 volt


Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 24, 2013, 09:09 pm
are you using a level shifter?

have you made a resistor based voltage divider??

follow the images/wiring that was posted for you.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 24, 2013, 09:42 pm
yes, I'm using a level shifter.
I followed the second circuit. Resistor values are 4k7 and 10k.
If I supply my level shifter with 5 volts, the drop across 10k with respect to ground is around 3.37 to 3.4 volts.
This means that my level shifter is OK.

If I turn on my crapduino, what voltage should I read from the SPI pins?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: purgedsoul on Feb 25, 2013, 04:00 am
Can you take a picture of your setup and post it here?

Are you using an SD Card or a Micro SD Card in an adaptor?

What's the error code thrown out by the BareMininumWithDebug example, error code: 1 or error code: 08?

if it is error code 1, if your not using a shield, check your connections and contacts with the SD-Card pins. if it is error code 8, try level shifting using 1.8k and 3.3k resistor.

I recently had a problem with my setup above using CD4050. So i ditched that setup and use resistor divider with above values. I am using a micro-sd on an adaptor.

also if no error code and it is saying in the serial monitor "Initialising SD card...Wiring is correct and a card is present....... playing EXAMPLE.AFM.found.playing" lean-in, or put the speaker, closer to your ear, the audio volume is quite low. that it can be unnoticeable when your in a noisy environment.

and my *duino is even more crappier than yours  XD  :D :D  XD and it's from five years ago...

http://arduino.cc/forum/index.php/topic,24039.msg181921.html#msg181921 (http://arduino.cc/forum/index.php/topic,24039.msg181921.html#msg181921)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 25, 2013, 06:39 pm
just saw this today... and it sorta applies here:

https://tindie.com/shops/thinkl33t/sd-level-shifter/

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 26, 2013, 12:49 pm
When I run the BareMinimumWithDebug, the error code is 3.

Can anyone answer post number 145? Thank you.

Kindly check the schematic. I always connect my CS pin on pin 4 which is T0 (PD4) of the ATMEGA328P.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 26, 2013, 06:25 pm
Hi, it seems that is still something wrong, either with wiring or something else.

Regarding post 145: If you build your voltage dividers correctly and assuming that you are not driving MISO as output you should not measure more than 3.3 - 3.6v anywhere on the SD card.

Please also check:
1.  You use a SD or SDHC card, but not SDXC. Old MMC cards may work - not tested.
2.  You use Arduino IDE 1.0 or up to 1.0.3, but not 1.5 (the beta version only for Due)
3.  If you use a ATmega328 based Arduino, even a clone, you should use an unpatched Arduino IDE and program the Arduino using one of the boards-setting that came already with the standard IDE.
4. If all is ok, check if your Arduino is still working on all ports used by the SD card. Set ports to output and high and you should measure 3.3v at appropriate SD pins.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: tack on Feb 27, 2013, 09:01 am
Have you tried with a different SD card?

I have some SD cards that just won't initialise in my card reader. I have two cards exactly the same,  2gb and same make and model, and only one will work with the reader. Both work in the pc. I also have some microSD that won't work either, where others do.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 27, 2013, 09:59 am
Hi again.

I'm almost losing hope.
But before I turn into incredible hulk and destroy everything, I'll try my best to do it. :D

I am attaching an image of my connection to the crapduino and to the sd card.

Question: What brand of SD cards are working for this application?

SD card CS goes to pin 4?
Please check the attached image...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 27, 2013, 10:49 am
Kindly let me know what it means by the error codes so I know what to check.

Thank you.

When I upload, I sometimes get this error:

avrdude: stk500_getsync(): not in sync: resp=0x00

I'm using an Aduino 1.0.3 IDE.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 27, 2013, 02:00 pm
not sure of the error.. seems like it cant communicate..



as for the CS pin.. why do you have it connected to several pins?

seems like it goes to pin D4.. but 'also'.. D10 (SS) pin as well??

just follow the wiring diagrams that have been posted for you.



Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 27, 2013, 04:40 pm
Hi

I think I followed exactly the schematic you posted.
There are 3 voltage dividers connected to MOSI, SCK, and CS.

PLUS: The testing for the BAREMINIMUMWITHDEBUG says that CS pin of SD card goes to digital pin 4 of crapduino.

What part did I not follow sir? I really need the audio ASAP. It's for a school project.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 27, 2013, 05:02 pm
Im saying (to me at least).. it looks like you have the CS pin on the SD card connected to two other places on the Atmega

Is that how the other diagrams posted have it? (two places)

I have tried BOTH (with this library)..

using D4 and D10 and the CS pin...

and of course using D9 as the default audio output pin..

this gives you 'basic' audio output.. unless you build in a filter/amp..etc..

(more advanced/better audio output is use D4 as the CS pin.. and use BOTH D9 & D10 for audio output.   [along with a few other components])






Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 27, 2013, 05:32 pm
I misunderstood the hardware set-up.

Is this correct already? (check image)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 27, 2013, 06:11 pm
If you change the code/sketch it 'could' work...

but if you leave the purple (D4).. and remove the SS (D10)..

it should work out of the box..


you also need to use D9   >>>   electrolytic cap   >>>   speaker   >>>   GND
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Feb 27, 2013, 11:15 pm
Quote
remove the SS (D10)..


Does it mean that the voltage divider: D10-----4k7----.----10k-----gnd    will be removed?

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Feb 28, 2013, 12:14 am
you just use D4 instead of D10.. everything else is the same..

leave D10 not used (for now)

follow these images in this post.. but instead of using D10 anywhere.. use D4

http://arduino.cc/forum/index.php/topic,112745.msg1128459.html#msg1128459

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: manmachine on Mar 04, 2013, 06:08 pm
Hi,
    Great lib.But, Is there any scope of varying the pitch/speed of the file in the SD card ?
Thanks.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Mar 04, 2013, 11:49 pm
Hi,
it is not foreseen yet to change the pitch yet, at least not in fine amounts. You can select between half or full-rate, but that's all. If you want to change the playback speed in finer amounts, it is not possible with that library yet and you wont get usable result just by changing the timer rate because the timer already runs at relatively high speed allowing only massive pitch changes.

The easiest way to do such things might be to prepare multiple files on the card each with a different pitch and play those. You can do this using an audio editor like Audacity to prepare such files.

If you really want to go the hard way it should be possible to modify the library to support different playback rates - at least two options came in mind for me, changing the playback-interrupt function or the worker-function. The worker-function is written in plain C and should be easier to modify but with rate-changing it would not be longer operating at sector boundaries. In the playback function rate changing only have influence over buffer empty speed but it is harder to understand as it is written in Asm. The algorithm I would prefer is a phase-accumulator that decides if and how many samples are skipped or repeated for every target sample...

Tuttut
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: manmachine on Mar 05, 2013, 07:58 am
Thank you tuttut for the reply.
OK, I take the easy way you have mentioned.
One more question. I need to play a 5sec audio as a seamless loop:indefinitely .Though I am able to accomplish that with the "Bare minimum" you have provided,there occurs an audio glitch at the end-to-beginning of the file played. The file  has perfect zero-crossing at the beginning and in the end.Could you please suggest anything to avoid this problem.
(My gadget: Ardiuno Atmega 328+LC studio SDcard breakout board).
Thank you again.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Mar 06, 2013, 01:45 am
Hi,
there is no standard way, but you can try this patch (untested yet!)

Code: [Select]

void SdPlayClass::worker(void) {
  if(!_WorkerRunning && _pBuf && _fileinfo.Size) {
    uint16_t buflencpy;
    _WorkerRunning = 1;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
      buflencpy = _Buflen;
    }     
    if(_fileinfo.ActBytePos < _fileinfo.Size) {
        // At least space for 1 sector?
        if(buflencpy < _BufsizeMinus512) {
            int16_t ret;
            ret = SD_L1_ReadBlock(_fileinfo.ActSector++, _pBuf + _Bufin);
            if(!ret) {
               uint32_t BytesLeft = _fileinfo.Size - _fileinfo.ActBytePos;
               _Bufin += 512;
               _fileinfo.ActBytePos += 512;
               if(_Bufin >= _Bufsize) _Bufin -= _Bufsize;
               if(BytesLeft > 512UL) {
                   ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
                   {
                     _Buflen += 512;
                   }
                } else {
                   ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
                   {
                     _Buflen += BytesLeft;
                   }
                   while(1) {   
                     ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
                     {
                        buflencpy = _Buflen;
                     }
                     if(buflencpy == 0) break;
                   }
                   play();                   
                }
            } else {
              stop();
              _lastError = ret;
            }
        }
    } else {
      // Playback done
      if(buflencpy <= 1) {
        stop();
      }
    }
    _WorkerRunning = 0;
  }
}



Replace the worker-function inside the lib (file SimpleSDAudio.cpp) with the one above. To stop playback you need to use stop() then.


Please try it and tell if it works...

Tuttut
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: manmachine on Mar 06, 2013, 07:52 pm
Hi,
   Sorry, that patch did not work.
  Result : Audio file not played.Instead, there were lot of glitches-only glitches.I have noticed that the glitches came out as a stream (loudest at the start and diminished along the time line and died in few seconds).But that was from "Bare minimum" sketch.
  When I tried the " Bare minimum with Debug", it gave a continuous tone of 125 hz approx.(No audio file content played).
But, sketch examples with worker (bare minimum with worker,bare minimum with worker with debug),worked normally,of course with the glitch.
Could you please explain what exactly the patch modifies.
Anyway, thank you for trying to help me.

manmachine.
 
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Mar 06, 2013, 10:26 pm
Hi,
sorry, I did the patch using a too old local copy of the library on my smartphone on-the-go and got an too old lib file. Now I edited my former post, please try to apply the patch again on SimpleSDAudio-Lib V1.03 (the current one). This time I tested it a little. Unfortunately actually there is no flag that tells you if the file played at least once...
Please try again and tell me if it is working for you.

BTW: The patch catches the moment when the worker function puts the last sector (or part of it) of the audio file in the playback buffer. In this case, it waits endless (and therefore precise) until the buffer is completely empty (_Buflen == 0). In this moment it triggers the play() function, which starts the playback again. This is how the play() function works - if playback is still playing it restarts playing from start again (done by calling internally the stop() function). The stop() function resets all the pointer and the buffer for the playback. 

Tuttut
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: manmachine on Mar 08, 2013, 06:05 am
Hi,

    I'm still getting audio glitch.May be,something wrong (sd card format etc)with my setup.Could you please confirm that the test file I am using (please see attachment)works Ok in your set up?

 
:  Thank you for the explanation about the patch.Now I understand little more about the 'worker' function and I try to understand your libs more deep.

manmachine
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: meowth08 on Mar 08, 2013, 04:40 pm
Hi,

I got it finally working.

But not with that FAKEduino.
I made my own board.

Sadly, outputting an audio is just a part of the project. The whole project isn't working yet.

Question: Are there pins affected when using this library? For example, some digital pins won't work...something like that?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Mar 09, 2013, 12:39 am
Hi
@manmachine: Hm, I thought about my quick solution and it is wrong - the issue is that the buffer is completely empty when issuing play and that play first reads a whole sector of 512 bytes from card before it starts playback again. This should lead to a fast but not gapless start. I think it will need a bigger overwork to get around this. I could think about modifying the lib to read the sectors byte-wise which will make the lib slower but more flexible. Audio processing will then become possible like gapless playback, fine-tuned playback tempo and mixing. But the lib might be then not as simple to use as now.

@meow...: Please provide more info what is working and what not. Error code of lib or just no sound? Or just no sound in bigger software project?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: manmachine on Mar 09, 2013, 08:39 am
Hi,
   @Tuttut:Thank you for your reply.So, its going to be a different approach!Well,Could you post a FLOW CHART of the proposed lib implementation,what might be a possible solution.

manmachine
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Mar 09, 2013, 01:36 pm
hey Tuttut-..

I sent you a PM a couple of days ago.. :)

just curious if you got it?


thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: cobra18t on Mar 26, 2013, 07:38 am
Tuttut, thanks for the great library. I have an alpha release of my ChipKit port, BasicSDAudio, available on GitHub. I am also working on an amplifier board that would work for any PWM audio output.

Check out the release at:
http://github.com/cobra18t/BasicSDAudio

another demo at:
http://cobrainnovations.blogspot.com/2013/03/basicsdaudio-alpha-release-and-demo.html

and info on the amplifier/filter at:
http://cobrainnovations.blogspot.com/2013/02/babyboomer-audio-amplifier-and-filter.html


I have yet to incorporate the 1.03 improvements.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Mar 26, 2013, 08:54 pm
I'd like to see/learn more about making this Awesome library better sounding with the use of filter/amp?

Small? (all SMD?)

Is there a schematic posted for it?

I am VERY happy Tuttut released this lib.. it was a HUGE missing part of the Arduino community (easy audio)..
but as 'stock' the volume is just 'meh'...  so it needs some filters and an amp for sure for more sound hungry projects..

still learning/finding my way through filters and amps..

thanks!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: thomashooper on Apr 11, 2013, 06:36 am
What timers are used in this library for 16MHz, Full rate mono?

I'm hoping there is a timer or two open that I can use to output PWM so I can brighten and fade an LED while the audio file is playing.

In the case that there is a timer I can use, would using the timer affect the audio too much?

Thanks.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Apr 11, 2013, 10:12 am
The lib use only the timer that is bound to the output port. It might be possible to even use analogWrite on neighbor ports that use thevsame timer but I never tested it, so please do so. But in this case the PWM is fixed to 8-Bit and the sampling rate of audio-playback, which should be no issue for LED dimming.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Apr 11, 2013, 04:29 pm
I have done/tried a set-up using the SimpleSDAudio lib as the audio output.

the most simple design, straight outout put on pin9 via a 100uF polarized cap.


the pwm 'works'...  but you get noise in the audio.


https://www.youtube.com/watch?v=unyKKA1JOnw

Specs:

ATmga328P-AU
+3.3v @ 8MHz internal clock  (ie; no crystal, cap or resonator)
straight connect microSD (ie: no level shifter or voltage divider)
3 x leds on PWM fade
5 x leds (digital on/off)
no filter
no amp

(I need to learn more about low-pass filter set-up and using an amp better)  :(



@cobra18t-

is there any schematics or anything for your BabyBOOMER?

Does it need the 'dual' output?  I only have  set-up where Im outputting on pin9 only (most basic)..

looking for the smallest way to get better sound.. :)

thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Apr 11, 2013, 09:45 pm
Hi,
the thing is that people often don't understand where the noise in such systems come from and try to build filters to try to filter out 8-bit noise. This is just stupid, as the noise of having too less bits is usually even distributed over the audible spectrum and not only at the high frequencies. With very good algorithms that do dithering you can try to buy better noise performance at the cost of spectrum - in such a case the noise is not longer evenly distributed over the spectrum (this is called noise-shaping, SOX can do this under special conditions, see http://sox.sourceforge.net/SoX/NoiseShaping (http://sox.sourceforge.net/SoX/NoiseShaping). But this only makes sense if you have a high sampling rate AND you are using an external filter. You can do a simple experiment to understand 8-bit noise: Convert your audio file at your PC to 8-bit and listen to it and you will hear the static noise. I tried this using Audacity and the result is pretty much what I get with the Arduino 8-Bit output.

But: If you want an easy way to get rid of the noise go for double-PWM-Ouput aka 16-bit mode. Often you only need one additional output port and one resistor to get a much better sound with so less noise that you don't even think about filtering (which is often useless anyway!). If you want it cheap try my circuit from this entry (2nd post circuit for 16-bit): http://arduino.cc/forum/index.php/topic,158024.0.html (http://arduino.cc/forum/index.php/topic,158024.0.html). Just build one half of it if you stick with Mono-Output. The nice thing is: It is much louder on a speaker than a port-pin, so no need for additional amplifier and much less noise and still cheap. I tested it several times, I'll try if I can do it a little smaller using transistors.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: xl97 on Apr 11, 2013, 10:07 pm
thanks for the reply..

for myself..

1.) can 'dual' output be done on an UNO/Duemilanove?  (I though I had read only on Mega's?   could be wrong of course.. I thought i had 'tried' it originally and dont recall seeing (hearing) a difference.. however that could also have been user/set-up error.. LOL


also.. as to the noise I guess I was referring to.. I mean more specifically wen you run/do PWM actions 'while' playing audio.. you can hear the hum/buzz..etc..etc  playing over the audio or interfering...etc..


unfortunately.. I dont have any 74AC14 chip..  (never even heard of them before now) :)..

but I do have a LM386 amp laying around..?

form the schematic though.. looks like only a:

coupling cap on the power rails
2 x resistors..
and the DC blocking cap on the PIN9 output?

actually looking again.. is that two caps for the decoupling?  hard to see in the fritzing image) :)



Are you saying that just using the DUAL PWM output will (not only help eliminate the noise) but increase the volume.. to where you say/think/believe no amp is even needed to boost volume?

I currently only have things set-up for single (pin9) output.. and actually used pin10 as the CS pin for my SD card..

but next revision could have that changed easy enough......

I'll have to go back and try the dual output again?

thanks.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Apr 11, 2013, 11:03 pm
Hi,
with standard Arduino (with ATmega328) two PWM outputs for SimpleSDAudio are availible, either for stereo 8-bit or mono 16-bit. For mono 16-bit you have to set it up like it would be stereo mode and you have to use the 16-bit SOX batch-files for processing. You end up with 2 PWM outputs, one playing the 8-bit sound and one playing loud "noise". But when you add this noise-channel to the other using those pots, the result will be much less noise.

For start you can also use a 74HC14 chip. Often in catalogs these chips have numbers starting with SN, so SN74AC14 is also the right one.

If you want to use your LM386 amp do the 16-bit combining before routing it to the amp. Use this circuit: http://hackerspace-ffm.de/wiki/index.php?title=Datei:SSDA_Simple16bit.png (http://hackerspace-ffm.de/wiki/index.php?title=Datei:SSDA_Simple16bit.png). But without the 74HC14 or 74AC14 it is hard to get rid of the noise coming from PWM-LED-Dimming.

Good power deblocking is essential for audio quality. Try to add some caps, 100nF but also one much bigger electrolytic cap in the 10uF to 100uF region. This is also done in my Fritzing schematic, so you got it right.

Dual-PWM output does not increase the volume itself (only if you use bridge-mode without any additional amplifiers). I use two PWM outputs with stereo-setting (SSDA_MODE_STEREO) and combine those to 16-bit mono for better audio quality. The 74AC14 will then increase volume and decrease noise if decoupled correctly by filtering the uC-noise out on the PWM outputs.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: thomashooper on Apr 13, 2013, 03:43 am
Hi,

I am trying to work on a Tardis project from Dr. Who. Basically I want to play the Tardis theme and have an LED brighten and dim while the Tardis Theme is playing. I have gotten the file and music to play correctly. In a separate sketch I have used timer 0 to brighten and dim the LED, which worked perfectly. When I put the codes together, however, only the light will work, and not the sound. The debug sketch in the library says it cannot initialize the card once I have my LED code in there.

Hopefully I am making sense. I will post my current code and explain what I am trying to do.

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

//Here I have set up an array of integers that start from zero and go to 255, and then decrease to 0. This is so I can brighten and dim an LED while the file is playing.
int array[]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,255,254,253,252,251,250,249,248,247,246,245,244,243,242,241,240,239,238,237,236,235,234,233,232,231,230,229,228,227,226,225,224,223,222,221,220,219,218,217,216,215,214,213,212,211,210,209,208,207,206,205,204,203,202,201,200,199,198,197,196,195,194,193,192,191,190,189,188,187,186,185,184,183,182,181,180,179,178,177,176,175,174,173,172,171,170,169,168,167,166,165,164,163,162,161,160,159,158,157,156,155,154,153,152,151,150,149,148,147,146,145,144,143,142,141,140,139,138,137,136,135,134,133,132,131,130,129,128,127,126,125,124,123,122,121,120,119,118,117,116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,100,99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63,62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0};
int y=0;

void setup()
{
  pinMode (6, OUTPUT);   //This is the OC0A pin that I want to use for the LED

 
  cli();
 
 
  TCCR0A = 0x83;         //In the control registers, I have set fast PWM, non inverting mode. I used a prescaler of 256, so that every 4ms the OCR0B would match and set an interrupt.
                         //During the interrupt, I want to increment the element in the array. So every 4ms, the light brigthens slightly.
  TCCR0B = 0x04;
 
  OCR0A = 255;
 
  OCR0B = 249;
 
  TCNT0 = 0;
 
  TIMSK0 = 0x04;
 
  sei();

  SdPlay.setSDCSPin(10); // Enable if your SD card CS-Pin is not at Pin 4...
  SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER);
  SdPlay.setFile("EXAMPLE.AFM");
  SdPlay.play();
}

void loop(void) {
}

ISR(TIMER0_COMPB_vect)
{
  y++;
  OCR0A = (array [y]);
  if(y==512)
  {
    y=0;
  }

}


This section of code:

Code: [Select]
#include <SimpleSDAudio.h>
void setup()
{
  // SdPlay.setSDCSPin(10); // Enable if your SD card CS-Pin is not at Pin 4...
  SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER);
  SdPlay.setFile("EXAMPLE.AFM");
  SdPlay.play();
}

void loop(void) {
}


comes directly from the AbsoluteMinimum example in the simple sd audio library. The only things I added is the controls for timer 0 to run the light, and an interrupt service routine.

So to set up timer0, I set Bits 7:6 - COM0A1:0 in the timer 0 control register A (TCCR0A) to 1, 0, which is non inverting PWM for the OC0A pin. I set Bits 1:0 - WGM01:0: in the TCCR0A to 1, 1, which selects the fast PWM mode. All I did in the TCCR0B register was set the clock to a 256 prescaler.

The way I set it up, the OCR0A register holds the PWM value for the OC0A pin (pin 6 on the arduino). The OCR0B holds a value that will set an interrupt every 4ms. In this interrupt, I set the next PWM value that needs to be in the OCR0A register.  So in summary, every 4 ms, the OCR0A register is set to the next integer in the array, and the array makes the PWM values increase to 255 and then decrease to 0. This way I get my brightening and dimming LED on pin 6.

So, the SD audio works fine on its own, and the LED works fine on its own. But when I try to combine the two, only the light works; I do not get any audio. So is my ISR taking too much time and ruining the audio? Or does the audio library use all the timers? Note: if I use the BareMinimumWithDebug example in the library, and insert my timer 0 code, it says the SD card will not initialize. I checked the CS pin too, so it has something to do with my timer setup.

I hope my code makes sense and that I have explained my problem well. If anybody could let me know what is wrong, and if there is a possible solution or better way to do this, I would greatly appreciate it.

Thanks,
Thomas Hooper
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Apr 13, 2013, 10:44 am
Hi,
the reason is that SimpleSDAudio uses millis() in sd_l0.h for timeout and timing purposes. Unfortunately, timer0 is heavily used by the Arduino library for all kinds of Timings, like millis, delay etc., so it is a good idea not to figure with it. But: two interesting OCR-Outputs are only availible at this timer, that might be used even for 4-channel output with my lib even on ATmega328. On the other hand, timer2 is not as interesting, so I build a patch that moves all internal Arduino timing functions from timer0 to timer2. This patch can help you too. You find it already in the deepths of SimpleSDAudio library. Try it, if you got stuck ask again.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: thomashooper on Apr 13, 2013, 07:08 pm
Do you think it would work if I used timer 2 for my pwm settings instead of timer 0? Also, I could not find the patch you said I could try, do I need to download a newer version of the Simple SD audio library?  Thanks for your help.

Thomas Hooper :)
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Apr 13, 2013, 07:22 pm
Timer2 is usually not used in Arduino, so if you do your PWM stuff with that timer instead of timer0 it should work. For the other way: The patch is in the "patches" folder of SimpleSDAudio. It provides a patched wiring.c file which replaces the wiring.c in the Arduino folder.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: afch on May 10, 2013, 03:37 pm
Hi, all.
Help me solve the problem - when I call the Play(), I hear a loud clicking before file playback. How to get rid of this very loud clicks?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on May 10, 2013, 06:55 pm
Hi, usually this lib does not do loud clicks, maybe a little after init, but not when playing files. So maybe your file is not good - add a fade-in to the wav file (e.g. using Audacity) before converting it.

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: MrMW on Oct 09, 2013, 10:49 pm
I hope people are still working with this library. At least I am :)

I have got a question. I have built the schematic from the site: http://www.hackerspace-ffm.de/wiki/index.php?title=Datei:SSDA_Better16bit.png.  When I connect my speaker, I hear a very high pitch tone, which is very annoying. I think this tone is there because of the square wave that is constantly present at PIN 9. So when I'm not playing any audio, I would like PIN 9 to be constant 0 V. When I want to play an audiofile, the square wave should be there again. How do I do that? When I use analogWrite(9,0); the tone is indeed gone, but then the audiofiles are almost not hearable anymore.

sincerely,

Marcel
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 09, 2013, 11:48 pm
Hi, I see no reason why there should be an audible tone because the PWM frequency is ~62kHz for 16 MHz and ~31kHz for 8 MHz controllers. I have this circuit here in use and if playback stops there is not such a tone. Of course you can try to override the output pin to input when not in use, but I don't think that it will help. BUT: If you really use a 74HC14 or something like that please ensure that all inputs of unused buffers are connected to GND. If there is still noise also try to improve the supply of the buffer by placing a small 100nF capacitor in parallel to the bigger one. Please let us know here if anything of that I've written helps.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 09, 2013, 11:57 pm
Hi, want to add something:

Please also beware of one common made mistake:

If you want to use the 16-Bit feature of the library, you have to set the correct configuration flags: If you want 1 channel mono output but with 16-Bit you have to choose SSDA_MODE_STEREO and not SSDA_MODE_MONO to enable that "magic additional pin that makes audio better".
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: MrMW on Oct 10, 2013, 05:58 pm
Hello,

Thanks for the quick reaction.

I have used the HEF40106, a 100nF and a 100uF capacitor over the supply. The input pins of the non-used buffers were indeed floating. I have connected them to the ground now but the tone is still very present. The tone isn't introduced by the schmitt triggers anyway since connecting ports 9 and 10 directly to the resistor network still causes the tone to appear on the output.
With the most simple piece of code the tone still appears:
#include <SimpleSDAudio.h>
void setup()
{
 
   if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_STEREO | SSDA_MODE_AUTOWORKER)) {
     while(1); // Error while initialization of SD card -> stop.
  }
 
void loop(void) {
}

I'm using this amplifier: http://www.ebay.com/itm/PAM8403-Mini-Digital-Power-Amplifier-Board-Class-D-2-3W-/221293221137?pt=LH_DefaultDomain_0&hash=item33861a9511
Could that be of any influence?

The PWM frequency is 62 kHz, but can a minor random shift in the duty cycle cause a tone that is hearable?


Marcel
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 10, 2013, 07:03 pm
Hi,
sorry that I have to say that, but I think both IC's are not the best choice.

Your CMOS inverter is pretty slow - remember that the PWM is operating with full 16 MHz resolution, so 1 bit change means a length of 62ns, whereas your inverter is way slower than that! Even if that might not be the source of your issues this could make the audio quality worse. I recommend fast ones like SN74HC14 or even SN74AC14. The last one is so powerfull that it is often enough to connect the speaker just to a bunch of paralleled inverters. But for 16-Bit you will need a little modification then (the resistors are then too big).

Second: You are using a class-D amplifier. Have you tried it before using some other active speakers or line-in from other amplifier? The issue is that my circuit is lacking a low pass filter and in combination with Class-D amp this might not be a good idea. So just try to add a capacitor between ground and the point where the 1k and 220k are connected together. Experiment with different values e.g. 1nF, 100nF up to 1uF.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: MrMW on Oct 10, 2013, 08:00 pm
Hello,

Ok I have already a few 74HC14's. I will buy some capacitors tomorrow and order 74AC14's. I will get back at you with the results as soon as possible, but maybe that will be after the weekend.

Thanks.


Marcel

Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: MrMW on Oct 14, 2013, 08:20 pm
Hi,

Adding a capacitor after the resistance network helped to decrease the noise. However, still ordered some analog amplifiers to see whether I can get better results. Haven't tested the SN74AC14 yet, that one has arrived today.
To get 16 bit mono output I have to set the flags like: SSDA_MODE_FULLRATE | SSDA_MODE_STEREO | SSDA_MODE_AUTOWORKER ? And I have to convert my .wav file to: .BFM? Because with this combination of settings I do not get good results. I get some kind of very noisy output where I'm trying to play a gunshot. What could be the cause of this? Are there any restrictions for the .wav file, too?


Marcel
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Oct 15, 2013, 01:39 am
Hi,
your flags seem to be correct as well as the file format. Of course you need good quality audio material if you want good results. Maybe you have to swap the pwm pins, try playing in 16 bit mode and test what you hear on each of both channels by connecting only one of them to the input of the circuit where the resistor with the lower value is.
On one channel you should hear the sound in good but 8 bit quality and on the other one you should hear loud noise when the 16-bit file is playing. this goes later to the input with the higher value resitor. With both outputs combined you have to adjust the poti the lowest noise. The quality should be then less noisy than 8 bit mode.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: robsmok on Nov 11, 2013, 04:40 pm
how to build class
play next, previous file
Please help :)

THX
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: robsmok on Nov 11, 2013, 09:53 pm
hmm
#include <SimpleSDAudio.h>
not working with
#include <SD.h>
:(
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Nov 12, 2013, 01:18 am
Hm, *looking into crystal ball*, try starting with the examples provided by the library. Use Arduino IDE V1.0.x instead of beta versions in case of build trouble.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: skoubri on Feb 10, 2014, 09:04 am
Great project!!! i will try it!

i am just looking not very much for quality but if possible gapless play of parts of the file or between files... don't know if possible. Want to use atmega328 or 2560

thanks!!
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Feb 14, 2014, 10:48 am
Gap-less playback from SD is always a challenge. Even the .play() function might be fast enough, at least the .setFile() function will always do a lot of searching through the FAT filesystem. First try to play the same file again and again using a loop like:

Code: [Select]

while(1) {
   if(SdPlay.isStopped()) SdPlay.play();
}


If this works ok for you, you might youself patch the library in a way that the information that is retrieved by setFile is stored somewhere in RAM and used for quicker change of the file to playback. But this might be not the right starting-project for beginners...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: skoubri on Feb 14, 2014, 02:06 pm

Gap-less playback from SD is always a challenge. Even the .play() function might be fast enough, at least the .setFile() function will always do a lot of searching through the FAT filesystem. First try to play the same file again and again using a loop like:

Code: [Select]

while(1) {
   if(SdPlay.isStopped()) SdPlay.play();
}


If this works ok for you, you might youself patch the library in a way that the information that is retrieved by setFile is stored somewhere in RAM and used for quicker change of the file to playback. But this might be not the right starting-project for beginners...


Thank you SO MUCH for the quick answer and the tip too! ... I'll check it and come back with results..
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: skoubri on Feb 14, 2014, 05:32 pm
Hi again.. used the code below

Code: [Select]
while (S < 1000) {
   S=(pulseIn(13,HIGH,20000);
   if (millis()-t > 999){p=1;t=millis();
   if (p == 1) {
     SdPlay.setFile("START.AFM");
     SdPlay.play();p=0;t=millis();}

and my loop played perfect!!.. BUT now i noticed another problem with pulseIn as i am reading a PWM input to change sounds...

any tips if i can do that? is this an interrupt problem or because changes of the timers? is there anyway to measure PWM while playing sound?
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Moko on Jul 09, 2014, 11:56 pm
Is there a way to adjust the volume?
I have a home automation including a clock with my arduino mega, and  would decrease the sound (westminster gong) in the night and set it to normal (it's loud enough) at the day.
Currently i must disable the sound in the night :(
thanks
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Tuttut on Jul 11, 2014, 05:59 pm
Hi,
actually there is no such a feature. But usually SD cards have plenty of space - so just prepare one set of files with a lower volume (using a wav editor like Audacity) and switch between them.
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: Moko on Jul 13, 2014, 12:09 am

Hi,
actually there is no such a feature. But usually SD cards have plenty of space - so just prepare one set of files with a lower volume (using a wav editor like Audacity) and switch between them.



Good idea. Done. Works.
Thanks...
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: fx3200 on Jul 17, 2014, 10:50 am
its possible make this with this library? http://onixarts.pl/blog/2014/01/arduino-soundcard
Title: Re: New library for PWM playback from SD cards: SimpleSDAudio
Post by: SWinter on Oct 04, 2017, 04:12 pm
SimpleSDAudio patch for Atmega128 with MegaCore bootloader (file SimpleSDAudioDef.h)