Hardware Reference
In-Depth Information
Listing 18-1: ( continued)
96 }
97
98 // Loop the contents of the file
99 while (myFile.available())
100 {
101 // Read from the file into buffer
102 myFile.read(buffer, sizeof(buffer));
103
104 // Prepare samples
105 int volume = 1023;
106 Audio.prepare(buffer, S, volume);
107 // Feed samples to audio
108 Audio.write(buffer, S);
109 }
110 myFile.close();
111 }
This sketch has three main functions: the usual setup() and loop() but also
playfile() , the function that will be called to play audio i les.
setup() is declared on line 8. The serial port is coni gured on line 11, and the
SD card reader is initialized on line 14. Communication between the Arduino
and the SD card controller is done via the SPI protocol, and reading wave i les
requires high-speed transfers. To do this, on line 21, the SPI clock divider is
dei ned to speed up communications. On line 24, the Audio library is initial-
ized. It will expect mono i les with a bit rate of 44.1 kHz, and allocates a buffer
for 100 milliseconds, more than enough for most data reads from the SD card.
Two pins are then dei ned on lines 27 and 28; the pin used to read the state of
the button is set as an input, and then the sensor pin is also dei ned as an input.
loop() is declared on line 31. This is where most of the work will be done.
On line 35, the state of the button is read. If the button is not pressed, almost
all of loop() is skipped, and the sketch pauses for 50 milliseconds on line 75
before repeating.
If the button is pressed, then the analog value on the sensor pin is read and
stored as a variable. To help debugging, the value is displayed over the serial
port. On line 44, a calculation is made, converting the reading from the sen-
sor to degrees Celsius. Remember that the Arduino Due is a 3.3-V device, and
therefore, the analog value is compared to 3.3 V, not to 5 V. The temperature is
then output to the serial port.
To save space on the SD card, the recording of the different numbers have
been separated into different i les. If the temperature is below 21 degrees, then
a single i lename will be used; put simply, the i lename is the temperature. If the
temperature is eighteen degrees, it refers to a i le called “18.wav”. Temperatures
of 21 degrees and more will cause two i les to be called; one containing the 10s,
and one containing the single 1s. Twenty-four degrees will cause the sketch to
Search WWH ::




Custom Search