Você está na página 1de 69

Analog to Digital Conversion

The Analog World

Microcontrollers are capable of detecting binary signals: is the button pressed or not? These are digital signals.
When a microcontroller is powered from five volts, it understands zero volts (0V) as a binary 0 and a five volts
(5V) as a binary 1. The world however is not so simple and likes to use shades of gray. What if the signal is
2.72V? Is that a zero or a one? We often need to measure signals that vary; these are called analog signals. A
5V analog sensor may output 0.01V or 4.99V or anything inbetween. Luckily, nearly all microcontrollers have a
device built into them that allows us to convert these voltages into values that we can use in a program to make
a decision.

Here are some topics and concepts you may want to know before reading this tutorial:

 Voltage, Current, Resistance


 Binary
 Analog vs Digital
 Arduino analogRead()
 Voltage Dividers
 Digital Multimeter
 Powering Your Project

What is the ADC?

An Analog to Digital Converter (ADC) is a very useful feature that converts an analog voltage on a pin to a
digital number. By converting from the analog world to the digital world, we can begin to use electronics to
interface to the analog world around us.

Not every pin on a microcontroller has the ability to do analog to digital conversions. On the Arduino board,
these pins have an ‘A’ in front of their label (A0 through A5) to indicate these pins can read analog voltages.

ADCs can vary greatly between microcontroller. The ADC on the Arduino is a 10-bit ADC meaning it has the
ability to detect 1,024 (210) discrete analog levels. Some microcontrollers have 8-bit ADCs (28 = 256 discrete
levels) and some have 16-bit ADCs (216 = 65,536 discrete levels).
The way an ADC works is fairly complex. There are a few different ways to achieve this feat (see Wikipedia for
a list), but one of the most common technique uses the analog voltage to charge up an internal capacitor and
then measure the time it takes to discharge across an internal resistor. The microcontroller monitors the number
of clock cycles that pass before the capacitor is discharged. This number of cycles is the number that is returned
once the ADC is complete.

Relating ADC Value to Voltage

The ADC reports a ratiometric value. This means that the ADC assumes 5V is 1023 and anything less than 5V
will be a ratio between 5V and 1023.

Analog to digital conversions are dependant on the system voltage. Because we predominantly use the 10-bit
ADC of the Arduino on a 5V system, we can simplify this equation slightly:

If your system is 3.3V, you simply change 5V out with 3.3V in the equation. If your system is 3.3V and your
ADC is reporting 512, what is the voltage measured? It is approximately 1.65V.

If the analog voltage is 2.12V what will the ADC report as a value?

Rearrange things a bit and we get:

Ahah! The ADC should report 434.

Arduino ADC Example

To show this in the real world let’s use the Arduino to detect an analog voltage. Use a trimpot, or light sensor,
or simple voltage divider to create a voltage. Let’s setup a simple trimpot circuit for this example:
To start, we need to define the pin as an input. To match the circuit diagram we will use A3:

pinMode(A3, INPUT);

and then do the analog to digital version by using the analogRead() command:

int x = analogRead(A3); //Reads the analog value on pin A3 into x

The value that is returned and stored in x will be a value from 0 to 1023. The Arduino has a 10-bit ADC (210 =
1024). We store this value into an int because x is bigger (10 bits) than what a byte can hold (8 bits).

Let’s print this value to watch it as it changes:

Serial.print(“Analog value: “);


Serial.println(x);

As we change the analog value, x should also change. For example, if x is reported to be 334, and we’re using
the Arduino at 5V, what is the actual voltage? Pull out your digital multimeter and check the actual voltage. It
should be approximately 1.63V. Congratulations! You have just created your own digital multimeter with an
Arduino!

Hooking Things Up Backward

What happens if you connect an analog sensor to a regular (digital) pin? Nothing bad will happen. You just
won’t be able to do an analogRead successfully:

int x = analogRead(8); //Try to read the analog value on digital pin 8 - this doesn’t
work!

This will compile but x will be filled with a nonsensical value.

What happens if I connect a digital sensor to an analog pin? Again, you will not break anything. If you do
an analog-to-digital conversion on a button, you will most likely see ADC values very close to 1023 (or 5V
which is binary 1) or very close to 0 (or 0V which is binary 0).
Resources and Going Further

Doing analog digital conversions is a great thing to learn! Now that you have an understanding of this important
concept, check out all the projects and sensors that utilize analog to digital conversion.

 Some varieties of accelerometers and gyroscopes have anlog outputs that must be read in on an ADC to get
usable values.
 Pulse-width Modulation (PWM) is like an analog output, which is the opposite of analog input.
 The INA169 allows you to sense current using ADC.
 Using a voltage divider and the ADC, you can read in all sorts of sensors and variable components such as
trimpots, joysticks, sliders, and force sensitive resistors amongst many, many more.
 The Arduino map() function
 Arduino Analog Pins

>>>>>>>>>>>>

Accelerometer Basics
Accelerometers are devices that measure acceleration, which is the rate of change of the velocity of an object.
They measure in meters per second squared (m/s2) or in G-forces (g). A single G-force for us here on planet
Earth is equivalent to 9.8 m/s2, but this does vary slightly with elevation (and will be a different value on
different planets due to variations in gravitational pull). Accelerometers are useful for sensing vibrations in
systems or for orientation applications.

ADXL345 Breakout Board

Suggested Reading

If you are unfamiliar with any of the topics below, you may want to read up on those before moving ahead with
accelerometers.

 Logic Levels
 SPI Communication
 I2C Communication
 Pulse-Width Modulation (PWM)
 Analog to Digital Conversion

How an Accelerometer Works

Accelerometers are electromechanical devices that sense either static or dynamic forces of acceleration. Static
forces include gravity, while dynamic forces can include vibrations and movement.

Axes of measurement for a triple axis accelerometer

Accelerometers can measure acceleration on one, two, or three axes. 3-axis units are becoming more common
as the cost of development for them decreases.

An example of the inside of a piezoelectric accelerometer


Generally, accelerometers contain capacitive plates internally. Some of these are fixed, while others are
attached to minuscule springs that move internally as acceleration forces act upon the sensor. As these plates
move in relation to each other, the capacitance between them changes. From these changes in capacitance, the
acceleration can be determined.

Other accelerometers can be centered around piezoelectric materials. These tiny crystal structures output
electrical charge when placed under mechanical stress ( e.g. acceleration).

An example of the inside of a piezoelectric accelerometer

How to Connect to an Accelerometer

For most accelerometers, the basic connections required for operation are power and the communication lines.
As always, read the datasheet to ensure proper connections are made.

Communication Interface

Accelerometers will communicate over an analog, digital, or pulse-width modulated connection interface.

 Accelerometers with an analog interface show accelerations through varying voltage levels. These
values generally fluctuate between ground and the supply voltage level. An ADC on a microcontroller
can then be used to read this value. These are generally less expensive than digital accelerometers.
 Accelerometers with a digital interface can either communicate over SPI or I2C communication
protocols. These tend to have more functionality and be less susceptible to noise than analog
accelerometers.
 Accelerometers that output data over pulse-width modulation (PWM) output square waves with a known
period, but a duty cycle that varies with changes in acceleration.

Power

Accelerometers are generally low-power devices. The required current typically falls in the micro (µ) or milli-
amp range, with a supply voltage of 5V or less. The current consumption can vary depending on the settings
(e.g., power saving mode versus standard operating mode). These different modes can make accelerometers
well suited for battery powered applications.

Make sure that proper logic levels are matched, especially with the digital interfaces.
How to Select an Accelerometer

When choosing which accelerometer to use, several features are important to consider including power
requirements and communication interfaces as discussed previously. Additional features for consideration are
below.

Range

Most accelerometers will have a selectable range of forces they can measure. These ranges can vary from ±1g
up to ±250g. Typically, the smaller the range, the more sensitive the readings will be from the accelerometer.
For example, to measure small vibrations on a tabletop, using a small-range accelerometer will provide more
detailed data than using a 250g range (which is more suited for rockets).

The ADXL362 Triple Axis Accelerometer can measure ±2g, ±4g, and ±8g.

Additional Features

Some accelerometers include features such as tap detection (useful for low-power applications), free-fall
detection (used for Active Hard Drive Protection), temperature compensation (to increase accuracy in dead
reckoning situations ) and 0-g range sensing, which are other features to take into consideration when
purchasing an accelerometer. The need for these types of features on the accelerometer will be determined by
the application in which the accelerometer is incorporated.

There are also IMUs (Inertial Measurement Units) available, which can include accelerometers, gyroscopes and
even, occasionally, magnetometers into a single IC package or board. Some examples of this include the
MPU6050 and MPU9150. These are commonly used in motion tracking applications and UAV guidance
systems, where location and orientation of an object is important.

Purchasing an Accelerometer

Now that you’ve learned the abc’s of the x’s, y’s, and z’s, take a look at our recommended accelerometers.
Our recommendations:

>>>>>>>>>>>>>>>

Gyroscope
What is a Gyroscope

Gyroscopes, or gyros, are devices that measure or maintain rotational motion. MEMS (microelectromechanical
system) gyros are small, inexpensive sensors that measure angular velocity. The units of angular velocity are
measured in degrees per second (°/s) or revolutions per second (RPS). Angular velocity is simply a
measurement of speed of rotation.

What is a Gyroscope

Gyroscopes, or gyros, are devices that measure or maintain rotational motion. MEMS (microelectromechanical
system) gyros are small, inexpensive sensors that measure angular velocity. The units of angular velocity are
measured in degrees per second (°/s) or revolutions per second (RPS). Angular velocity is simply a
measurement of speed of rotation.

The LPY503 gyro on a breakout board.

Gyros, similar to the one above, can be used to determine orientation and are found in most autonomous
navigation systems. For example, if you want to balance a robot, a gyroscope can be used to measure rotation
from the balanced position and send corrections to a motor.
Concepts in this tutorial

Before diving into this tutorial, you may want to read up on some of these concepts if you are unfamiliar with
them.

 Logic Levels
 SPI Communication
 I2C Communication
 Analog to Digital Conversion

How a Gyro Works

When things rotate around an axis they have what’s called angular velocity. A spinning wheel can be measured
in revolutions per second (RPS) or degrees per second (°/s).

Note that the z axis of the gyro below aligns with the axis of rotation on the wheel.

If you attach the sensor to the wheel shown above, you can measure the angular velocity of the z axis of the
gyro. The other two axes would not measure any rotation.

Imagine if the wheel spins once per second. It would have an angular velocity of 360 degrees per second. The
spinning direction of the wheel is also important. Is it clockwise around the axis, or is it counter-clockwise?

A triple axis MEMS gyroscope, similar to the one pictured above (ITG-3200), can measure rotation around
three axes: x, y, and z. Some gyros come in single and dual axis varieties, but the triple axis gyro in a single
chip is becoming smaller, less expensive, and more popular.
Gyros are often used on objects that are not spinning very fast at all. Aircrafts (hopefully) do not spin. Instead
they rotate a few degrees on each axis. By detecting these small changes gyros help stabilize the flight of the
aircraft. Also, note that the acceleration or linear velocity of the aircraft does not affect the measurement of the
gyro. Gyros only measure angular velocity.

How does the MEMS gyro detect angular velocity?

Internal operational view of a MEMS gyro sensor

The gyroscope sensor within the MEMS is tiny (between 1 to 100 micrometers, the size of a human hair). When
the gyro is rotated, a small resonating mass is shifted as the angular velocity changes. This movement is
converted into very low-current electrical signals that can be amplified and read by a host microcontroller.

How to Connect to a Gyro

The primary hardware connections to use a gyro are power and a communication interface. As always, refer to
the sensor datasheet for all of the information on specifications and example connections.

Communication Interface

Gyros can have either a digital or analog communication interface.

 Gyros with a digital interface usually use either the SPI or I2C communication protocols. Using these
interfaces allow for an easy connection to a host microcontroller. One limitation of a digital interface is
max sample rate. I2C has a max sample rate of 400Hz. SPI, on the other hand, can have a much higher
sample rate.
 Gyros with an analog interface represent rotational velocity by a varying voltage, usually between
ground and the supply voltage. An ADC on a microcontroller can be used to read the signal. Analog
gyros can be less expensive and sometimes more accurate, depending on how you are reading the analog
signal.

Power

MEMS gyros are generally low power devices. Operating currents are in the mA and sometimes &microA
range. The supply voltage for gyros is usually 5V or less. Digital gyros can have selectable logic voltages or
operate at the supply voltage. For any digital interface, remember to connect 5V to 5V lines and 3.3V to 3.3V
lines. Also, gyros with digital interfaces can have low power and sleep modes that allow them to be used in
battery powered applications. Sometimes this is an advantage over an analog gyro.
How to Select a Gyro

There are many specifications to consider when figuring out what type of gyro to use. Here are a few of the
more important useful ones:

Range

The measurement range, or full-scale range, is the maximum angular velocity that the gyro can read. Think
about what you are measuring. Do you need to measure the spin of a record player, which is very slow or a
spinning wheel, which could be very fast?

Sensitivity

The sensitivity is measured in mV per degree per second (mV/°/s). Don’t let the weird dimension of this value
scare you. It determines how much the voltage changes for a given angular velocity. For example, if a gyro is
specified with a sensitivity of 30mV/°/s and you see a 300mV change in the output, you rotated the gyro at 10
°/s.

A good rule to remember: as the sensitivity increases, the range decreases. For example, look at the
LPY503 gyro datasheet or any gyro with a selectable range:

Notice that with a greater range, the sensitivity suffers and you get less resolution.

Bias

As with any sensor, the values you measure will contain some amount of error or bias. You can see gyro bias by
measuring the output when the gyro is still. Though you’d think you would see 0° when the gyro is still, you
will always see a slight non-zero error in the output. These errors are sometimes called bias drift or bias
instability. The temperature of the sensor greatly affects the bias. To help minimize the source of this error,
most gyros have a built in temperature sensor. Thus, you are able to read the temperature of the sensor and
correct or any temperature dependent changes. In order to correct for these errors, the gyro must be calibrated.
This is usually done by keeping the gyro still and zeroing all of the readings in your code.

Going Further

By now you should know how a gyro works and have a good foundation to start working with a gyro in a
project of your own.

Check out these tutorials that use gyros:

 Analog Gyro + Arduino


 Gyro Buying Guide
 Balancing Robot

The LPY503 gyro on a breakout board.

Gyros, similar to the one above, can be used to determine orientation and are found in most autonomous
navigation systems. For example, if you want to balance a robot, a gyroscope can be used to measure rotation
from the balanced position and send corrections to a motor.

Concepts in this tutorial

Before diving into this tutorial, you may want to read up on some of these concepts if you are unfamiliar with
them.

 Logic Levels
 SPI Communication
 I2C Communication
 Analog to Digital Conversion

How a Gyro Works

When things rotate around an axis they have what’s called angular velocity. A spinning wheel can be measured
in revolutions per second (RPS) or degrees per second (°/s).

Note that the z axis of the gyro below aligns with the axis of rotation on the wheel.

If you attach the sensor to the wheel shown above, you can measure the angular velocity of the z axis of the
gyro. The other two axes would not measure any rotation.

Imagine if the wheel spins once per second. It would have an angular velocity of 360 degrees per second. The
spinning direction of the wheel is also important. Is it clockwise around the axis, or is it counter-clockwise?

A triple axis MEMS gyroscope, similar to the one pictured above (ITG-3200), can measure rotation around
three axes: x, y, and z. Some gyros come in single and dual axis varieties, but the triple axis gyro in a single
chip is becoming smaller, less expensive, and more popular.

Gyros are often used on objects that are not spinning very fast at all. Aircrafts (hopefully) do not spin. Instead
they rotate a few degrees on each axis. By detecting these small changes gyros help stabilize the flight of the
aircraft. Also, note that the acceleration or linear velocity of the aircraft does not affect the measurement of the
gyro. Gyros only measure angular velocity.

How does the MEMS gyro detect angular velocity?


Internal operational view of a MEMS gyro sensor

The gyroscope sensor within the MEMS is tiny (between 1 to 100 micrometers, the size of a human hair). When
the gyro is rotated, a small resonating mass is shifted as the angular velocity changes. This movement is
converted into very low-current electrical signals that can be amplified and read by a host microcontroller.

How to Connect to a Gyro

The primary hardware connections to use a gyro are power and a communication interface. As always, refer to
the sensor datasheet for all of the information on specifications and example connections.

Communication Interface

Gyros can have either a digital or analog communication interface.

 Gyros with a digital interface usually use either the SPI or I2C communication protocols. Using these
interfaces allow for an easy connection to a host microcontroller. One limitation of a digital interface is
max sample rate. I2C has a max sample rate of 400Hz. SPI, on the other hand, can have a much higher
sample rate.
 Gyros with an analog interface represent rotational velocity by a varying voltage, usually between
ground and the supply voltage. An ADC on a microcontroller can be used to read the signal. Analog
gyros can be less expensive and sometimes more accurate, depending on how you are reading the analog
signal.

Power

MEMS gyros are generally low power devices. Operating currents are in the mA and sometimes &microA
range. The supply voltage for gyros is usually 5V or less. Digital gyros can have selectable logic voltages or
operate at the supply voltage. For any digital interface, remember to connect 5V to 5V lines and 3.3V to 3.3V
lines. Also, gyros with digital interfaces can have low power and sleep modes that allow them to be used in
battery powered applications. Sometimes this is an advantage over an analog gyro.

How to Select a Gyro

There are many specifications to consider when figuring out what type of gyro to use. Here are a few of the
more important useful ones:

Range

The measurement range, or full-scale range, is the maximum angular velocity that the gyro can read. Think
about what you are measuring. Do you need to measure the spin of a record player, which is very slow or a
spinning wheel, which could be very fast?

Sensitivity

The sensitivity is measured in mV per degree per second (mV/°/s). Don’t let the weird dimension of this value
scare you. It determines how much the voltage changes for a given angular velocity. For example, if a gyro is
specified with a sensitivity of 30mV/°/s and you see a 300mV change in the output, you rotated the gyro at 10
°/s.
A good rule to remember: as the sensitivity increases, the range decreases. For example, look at the
LPY503 gyro datasheet or any gyro with a selectable range:

Notice that with a greater range, the sensitivity suffers and you get less resolution.

Bias

As with any sensor, the values you measure will contain some amount of error or bias. You can see gyro bias by
measuring the output when the gyro is still. Though you’d think you would see 0° when the gyro is still, you
will always see a slight non-zero error in the output. These errors are sometimes called bias drift or bias
instability. The temperature of the sensor greatly affects the bias. To help minimize the source of this error,
most gyros have a built in temperature sensor. Thus, you are able to read the temperature of the sensor and
correct or any temperature dependent changes. In order to correct for these errors, the gyro must be calibrated.
This is usually done by keeping the gyro still and zeroing all of the readings in your code.

Going Further

By now you should know how a gyro works and have a good foundation to start working with a gyro in a
project of your own.

Check out these tutorials that use gyros:

 Analog Gyro + Arduino


 Gyro Buying Guide
 Balancing Robot

>>>>>>>>>>

Analog Input Pins

A description of the analog input pins on an Arduino chip (ATmega8, ATmega168, ATmega328P, or
ATmega1280).

A/D converter

The ATmega controllers used for the Arduino contain an onboard 6 channel (8 channels on the Mini and Nano,
16 on the Mega) analog-to-digital (A/D) converter. The converter has 10 bit resolution, returning integers from
0 to 1023. While the main function of the analog pins for most Arduino users is to read analog sensors, the
analog pins also have all the functionality of general purpose input/output (GPIO) pins (the same as digital pins
0 - 13).

Consequently, if a user needs more general purpose input output pins, and all the analog pins are not in use, the
analog pins may be used for GPIO.

Pin mapping

The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For
example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

Pull-up resistors

The analog pins also have pull-up resistors, which work identically to pull-up resistors on the digital pins. They
are enabled by issuing a command such as

pinMode(A0, INPUT_PULLUP); // set pull-up on analog pin 0

Be aware however that turning on a pull-up will affect the values reported by analogRead().

Details and Caveats

The analogRead command will not work correctly if a pin has been previously set to an output, so if this is the
case, set it back to an input before using analogRead. Similarly if the pin has been set to HIGH as an output, the
pull-up resistor will be set, when switched back to an input.

The ATmega datasheet also cautions against switching analog pins in close temporal proximity to making A/D
readings (analogRead) on other analog pins. This can cause electrical noise and introduce jitter in the analog
system. It may be desirable, after manipulating analog pins (in digital mode), to add a short delay before using
analogRead() to read other analog pins.

>>>>>>>>>>>>>

Interfacing Gyros
This is just a basic code snippet for the time being, but please feel free to contribute more information

Gyroscopes measure the rate of change of a particular axis at the current moment in time. This means that to
keep track of our angle, we need to sum all of the rates of change over a given period of time. We're essentially
looking for the integral of our gyro data. In the sample code below we'll be looking at just one gyro axis.

First off, you'll want to set the voltage of your gyro (typically 3.3v or 5v) for the gyroVoltage variable. This will
setup how the values are scaled.

Next you'll need to know the zero voltage of your gyro. You'll be able to find this in the gyro's datasheet. It is
sometimes called the Null voltage. In this example, I set the gyroZeroVoltage to 2.5. This is the voltage your
gyro normally outputs when it's not rotating.

The other value you'll need from the datasheet is the sensitivity. This is expressed in mV/degree/second. Since
this is mV, we need to convert to volts. You'll see in the examples, my gyro had a sensitivity of 7mV/deg/sec.

The Arduino has 10 bit ADC which can represent a voltage (0-5V) in values from 0 to 1023. Unfortunately
you'll definitely see error building up over time since we can never get a perfectly accurate voltage reading from
the gyro and our numbers never divide out evenly. You can set the rotationThreshold to a minimum
degree/second that the gyro has to be detected rotating at. If this degree/second rate is not met, the data will be
discarded.

/* Keep track of gyro angle over time


* Connect Gyro to Analog Pin 0
*
* Sketch by eric barch / ericbarch.com
* v. 0.1 - simple serial output
*
*/

int gyroPin = 0; //Gyro is connected to analog pin 0


float gyroVoltage = 5; //Gyro is running at 5V
float gyroZeroVoltage = 2.5; //Gyro is zeroed at 2.5V
float gyroSensitivity = .007; //Our example gyro is 7mV/deg/sec
float rotationThreshold = 1; //Minimum deg/sec to keep track of - helps with gyro drifting

float currentAngle = 0; //Keep track of our current angle

void setup() {
Serial.begin (9600);
}

void loop() {
//This line converts the 0-1023 signal to 0-5V
float gyroRate = (analogRead(gyroPin) * gyroVoltage) / 1023;

//This line finds the voltage offset from sitting still


gyroRate -= gyroZeroVoltage;

//This line divides the voltage we found by the gyro's sensitivity


gyroRate /= gyroSensitivity;

//Ignore the gyro if our angular velocity does not meet our threshold
if (gyroRate >= rotationThreshold || gyroRate <= -rotationThreshold) {
//This line divides the value by 100 since we are running in a 10ms loop (1000ms/10ms)
gyroRate /= 100;
currentAngle += gyroRate;
}

//Keep our angle between 0-359 degrees


if (currentAngle < 0)
currentAngle += 360;
else if (currentAngle > 359)
currentAngle -= 360;

//DEBUG
Serial.println(currentAngle);

delay(10);
}
>>>>>>>>>>>
Serial
[Communication]

Description

Used for communication between the Arduino board and a computer or other devices. All Arduino boards have
at least one serial port (also known as a UART or USART): Serial. It communicates on digital pins 0 (RX) and
1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1
for digital input or output.
You can use the Arduino environment’s built-in serial monitor to communicate with an Arduino board. Click
the serial monitor button in the toolbar and select the same baud rate used in the call to begin().

Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on the board). Don’t
connect these pins directly to an RS232 serial port; they operate at +/- 12V and can damage your Arduino
board.

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins
17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To use these pins to communicate with your
personal computer, you will need an additional USB-to-serial adaptor, as they are not connected to the Mega’s
USB-to-serial adaptor. To use them to communicate with an external TTL serial device, connect the TX pin to
your device’s RX pin, the RX to your device’s TX pin, and the ground of your Mega to your device’s ground.

The Arduino DUE has three additional 3.3V TTL serial ports: Serial1 on pins 19 (RX) and 18 (TX); Serial2
on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). Pins 0 and 1 are also connected to the
corresponding pins of the ATmega16U2 USB-to-TTL Serial chip, which is connected to the USB debug port.
Additionally, there is a native USB-serial port on the SAM3X chip, SerialUSB'.

The Arduino Leonardo board uses Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX).
Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started
page and hardware page.

Functions

If (Serial)
available()
availableForWrite()
begin()
end()
find()
findUntil()
flush()
parseFloat()
parseInt()
peek()
print()
println()
read()
readBytes()
readBytesUntil()
readString()
readStringUntil()
setTimeout()
write()
serialEvent()

See also

 LANGUAGE stream

 EXAMPLE ReadASCIIString
 EXAMPLE ASCII TAble
 EXAMPLE Dimmer
 EXAMPLE Graph
 EXAMPLE Physical Pixel
 EXAMPLE Serial Call Response
 EXAMPLE Serial Call Response ASCII

>>>>>>>>>>>>

Serial Call and Response (handshaking) with ASCII-encoded output

This example demonstrates string-based communication from the Arduino or Genuino board to the computer
using a call-and-response (handshaking) method.

The sketch sends an ASCII string on startup and repeats that until it gets a serial response from the computer.
Then it sends three sensor values as ASCII-encoded numbers, separated by commas and terminated by a
linefeed and carriage return, and waits for another response from the computer.

You can use the Arduino Software (IDE) serial monitor to view the sent data, or it can be read by Processing
(see code below), Flash, PD, Max/MSP (see example below), etc. The examples below split the incoming string
on the commas and convert the string into numbers again.

Compare this to the Serial call and response example. They are similar, in that both use a handshaking method,
but this one encodes the sensor readings as strings, while the other sends them as binary values. While sending
as ASCII-encoded strings takes more bytes, it means you can easily send values larger than 255 for each sensor
reading. It's also easier to read in a serial terminal program.

Hardware Required

 Arduino or Genuino Board


 2 analog sensors (potentiometer, photocell, FSR, etc.)
 pushbutton
 3 10K ohm resistors
 hook-up wires
 breadboard
Software Required

 Processing or
 Max/MSP version 5

Circuit

Connect analog sensors to analog input pin 0 and 1 with 10K ohm resistors used as voltage dividers. Connect a
pushbutton or switch to digital I/O pin 2 with a 10K ohm resistor as a reference to ground.

click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

click the image to enlarge


Code
/*
Serial Call and Response in ASCII
Language: Wiring/Arduino

This program sends an ASCII A (byte of value 65) on startup and repeats that
until it gets some data in. Then it waits for a byte in the serial port, and
sends three ASCII-encoded, comma-separated sensor values, truncated by a
linefeed and carriage return, whenever it gets a byte in.

The circuit:
- potentiometers attached to analog inputs 0 and 1
- pushbutton attached to digital I/O 2

created 26 Sep 2005


by Tom Igoe
modified 24 Apr 2012
by Tom Igoe and Scott Fitzgerald
Thanks to Greg Shakar and Scott Fitzgerald for the improvements

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII
*/

int firstSensor = 0; // first analog sensor


int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte

void setup() {
// start serial port at 9600 bps and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

pinMode(2, INPUT); // digital sensor is on digital pin 2


establishContact(); // send a byte to establish contact until receiver responds
}

void loop() {
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
// read first analog input:
firstSensor = analogRead(A0);
// read second analog input:
secondSensor = analogRead(A1);
// read switch, map it to 0 or 255
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values:
Serial.print(firstSensor);
Serial.print(",");
Serial.print(secondSensor);
Serial.print(",");
Serial.println(thirdSensor);
}
}

void establishContact() {
while (Serial.available() <= 0) {
Serial.println("0,0,0"); // send an initial string
delay(300);
}
}

/* Processing code to run with this example:

// This example code is in the public domain.


import processing.serial.*; // import the Processing serial library
Serial myPort; // The serial port

float bgcolor; // Background color


float fgcolor; // Fill color
float xpos, ypos; // Starting position of the ball

void setup() {
size(640, 480);

// List all the available serial ports


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// I know that the first port in the serial list on my Mac is always my
// Arduino board, so I open Serial.list()[0].
// Change the 0 to the appropriate number of the serial port that your
// microcontroller is attached to.
myPort = new Serial(this, Serial.list()[0], 9600);

// read bytes into a buffer until you get a linefeed (ASCII 10):
myPort.bufferUntil('\n');

// draw with smooth edges:


smooth();
}

void draw() {
background(bgcolor);
fill(fgcolor);
// Draw the shape
ellipse(xpos, ypos, 20, 20);
}

// serialEvent method is run automatically by the Processing applet whenever


// the buffer reaches the byte value set in the bufferUntil()
// method in the setup():

void serialEvent(Serial myPort) {


// read the serial buffer:
String myString = myPort.readStringUntil('\n');
// if you got any bytes other than the linefeed:
myString = trim(myString);

// split the string at the commas and convert the sections into integers:
int sensors[] = int(split(myString, ','));

// print out the values you got:


for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
}
// add a linefeed after all the sensor values are printed:
println();
if (sensors.length > 1) {
xpos = map(sensors[0], 0, 1023, 0, width);
ypos = map(sensors[1], 0, 1023, 0, height);
fgcolor = sensors[2];
}
// send a byte to ask for more data:
myPort.write("A");
}

*/

>>>>>>>>>>>>>>>

Serial Call and Response (handshaking)

This example demonstrates multi-byte communication from the Arduino or Genuino board to the computer
using a call-and-response (handshaking) method.

This sketch sends an ASCII A (byte of value 65) on startup and repeats that until it gets a serial response from
the computer. Then it sends three sensor values as single bytes, and waits for another response from the
computer.

You can use the Arduino Software (IDE) serial monitor to view the sent data, or it can be read by Processing
(see code below), Flash, PD, Max/MSP (see example below), etc.

Hardware Required

 Arduino or Genuino Board


 2 analog sensors (potentiometer, photocell, FSR, etc.)
 pushbutton
 3 10K ohm resistors
 hook-up wires
 breadboard

Software Required

 Processing or
 Max/MSP version 5
Circuit

Connect analog sensors to analog input pin 0 and 1 with 10K ohm resistors used as voltage dividers. Connect a
pushbutton or switch to digital I/O pin 2 with a 10K ohm resistor as a reference to ground.

click on the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

click the image to enlarge

Code
/*
Serial Call and Response
Language: Wiring/Arduino
This program sends an ASCII A (byte of value 65) on startup and repeats that
until it gets some data in. Then it waits for a byte in the serial port, and
sends three sensor values whenever it gets a byte in.

The circuit:
- potentiometers attached to analog inputs 0 and 1
- pushbutton attached to digital I/O 2

created 26 Sep 2005


by Tom Igoe
modified 24 Apr 2012
by Tom Igoe and Scott Fitzgerald
Thanks to Greg Shakar and Scott Fitzgerald for the improvements

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/SerialCallResponse
*/

int firstSensor = 0; // first analog sensor


int secondSensor = 0; // second analog sensor
int thirdSensor = 0; // digital sensor
int inByte = 0; // incoming serial byte

void setup() {
// start serial port at 9600 bps:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

pinMode(2, INPUT); // digital sensor is on digital pin 2


establishContact(); // send a byte to establish contact until receiver responds
}

void loop() {
// if we get a valid byte, read analog ins:
if (Serial.available() > 0) {
// get incoming byte:
inByte = Serial.read();
// read first analog input, divide by 4 to make the range 0-255:
firstSensor = analogRead(A0) / 4;
// delay 10ms to let the ADC recover:
delay(10);
// read second analog input, divide by 4 to make the range 0-255:
secondSensor = analogRead(1) / 4;
// read switch, map it to 0 or 255L
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values:
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
}
}

void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send a capital A
delay(300);
}
}

/* Processing sketch to run with this example:

// This example code is in the public domain.

import processing.serial.*;

int bgcolor; // Background color


int fgcolor; // Fill color
Serial myPort; // The serial port
int[] serialInArray = new int[3]; // Where we'll put what we receive
int serialCount = 0; // A count of how many bytes we receive
int xpos, ypos; // Starting position of the ball
boolean firstContact = false; // Whether we've heard from the microcontroller

void setup() {
size(256, 256); // Stage size
noStroke(); // No border on the next thing drawn

// Set the starting position of the ball (middle of the stage)


xpos = width / 2;
ypos = height / 2;

// Print a list of the serial ports for debugging purposes


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// I know that the first port in the serial list on my Mac is always my FTDI
// adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}

void draw() {
background(bgcolor);
fill(fgcolor);
// Draw the shape
ellipse(xpos, ypos, 20, 20);
}

void serialEvent(Serial myPort) {


// read a byte from the serial port:
int inByte = myPort.read();
// if this is the first byte received, and it's an A, clear the serial
// buffer and note that you've had first contact from the microcontroller.
// Otherwise, add the incoming byte to the array:
if (firstContact == false) {
if (inByte == 'A') {
myPort.clear(); // clear the serial port buffer
firstContact = true; // you've had first contact from the microcontroller
myPort.write('A'); // ask for more
}
}
else {
// Add the latest byte from the serial port to array:
serialInArray[serialCount] = inByte;
serialCount++;

// If we have 3 bytes:
if (serialCount > 2 ) {
xpos = serialInArray[0];
ypos = serialInArray[1];
fgcolor = serialInArray[2];

// print the values (for debugging purposes only):


println(xpos + "\t" + ypos + "\t" + fgcolor);

// Send a capital A to request new sensor readings:


myPort.write('A');
// Reset serialCount:
serialCount = 0;
}
}
}
*/

>>>>>>>>>>>>>>>>

Physical Pixel

This example example uses the Arduino or Genuino board to receive data from the computer. The board turns
on an LED when it receives the character 'H', and turns off the LED when it receives the character 'L'.

The data can be sent from the Arduino Software (IDE) serial monitor, or another program like Processing (see
code below), Flash (via a serial-net proxy), PD, or Max/MSP.

Hardware Required

 Arduino or Genuino Board


 LED (optional)
 220 ohm resistor (optional)

Software Required

 Processing or
 Max/MSP version 5

Circuit

Many Arduino and Genuino boards have a built-in LED connected to pin 13; if your board has no built-in LED,
attach an external LED to pin 13. The long leg, or anode, goes to pin 13 through a 220 resistor. The short leg, or
cathode, goes to ground.

click the image to enlarge


image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

click the image to enlarge

Code
/*
Physical Pixel

An example of using the Arduino board to receive data from the computer. In
this case, the Arduino boards turns on an LED when it receives the character
'H', and turns off the LED when it receives the character 'L'.

The data can be sent from the Arduino Serial Monitor, or another program like
Processing (see code below), Flash (via a serial-net proxy), PD, or Max/MSP.

The circuit:
- LED connected from digital pin 13 to ground

created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/PhysicalPixel
*/
const int ledPin = 13; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into

void setup() {
// initialize serial communication:
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}

void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
}
}
}

/* Processing code for this example

// Mouse over serial

// Demonstrates how to send data to the Arduino I/O board, in order to turn ON
// a light if the mouse is over a square and turn it off if the mouse is not.

// created 2003-4
// based on examples by Casey Reas and Hernando Barragan
// modified 30 Aug 2011
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

float boxX;
float boxY;
int boxSize = 20;
boolean mouseOverBox = false;
Serial port;

void setup() {
size(200, 200);
boxX = width / 2.0;
boxY = height / 2.0;
rectMode(RADIUS);

// List all the available serial ports in the output pane.


// You will need to choose the port that the Arduino board is connected to
// from this list. The first port in the list is port #0 and the third port
// in the list is port #2.
// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());

// Open the port that the Arduino board is connected to (in this case #0)
// Make sure to open the port at the same speed Arduino is using (9600bps)
port = new Serial(this, Serial.list()[0], 9600);
}

void draw() {
background(0);

// Test if the cursor is over the box


if (mouseX > boxX - boxSize && mouseX < boxX + boxSize &&
mouseY > boxY - boxSize && mouseY < boxY + boxSize) {
mouseOverBox = true;
// draw a line around the box and change its color:
stroke(255);
fill(153);
// send an 'H' to indicate mouse is over square:
port.write('H');
}
else {
// return the box to its inactive state:
stroke(153);
fill(153);
// send an 'L' to turn the LED off:
port.write('L');
mouseOverBox = false;
}

// Draw the box


rect(boxX, boxY, boxSize, boxSize);
}
*/

>>>>>>>>>>>>>>>>>>>

Graph

This example shows you how to send a byte of data from the Arduino or Genuino to a personal computer and
graph the result. This is called serial communication because the connection appears to both the board and the
computer as a serial port, even though it may actually use a USB cable, a serial to USB and a USB to serial
converter.

You can use the serial monitor of the Arduino Software (IDE) to view the sent data, or it can be read by
Processing (see code below), Flash, PD, Max/MSP, etc.

Hardware Required

 Arduino or Genuino Board


 Analog Sensor (potentiometer, photocell, FSR, etc.)

Software Required

 Processing or
 Max/MSP version 5

Circuit

Connect a potentiometer or other analog sensor to analog input 0.

click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page
Schematic

click the image to enlarge

Code
/*
Graph

A simple example of communication from the Arduino board to the computer: The
value of analog input 0 is sent out the serial port. We call this "serial"
communication because the connection appears to both the Arduino and the
computer as a serial port, even though it may actually use a USB cable. Bytes
are sent one after another (serially) from the Arduino to the computer.

You can use the Arduino Serial Monitor to view the sent data, or it can be
read by Processing, PD, Max/MSP, or any other program capable of reading data
from a serial port. The Processing code below graphs the data received so you
can see the value of the analog input changing over time.

The circuit:
- any analog input sensor attached to analog in pin 0

created 2006
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe and Scott Fitzgerald
This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Graph
*/

void setup() {
// initialize the serial communication:
Serial.begin(9600);
}

void loop() {
// send the value of analog input 0:
Serial.println(analogRead(A0));
// wait a bit for the analog-to-digital converter to stabilize after the last
// reading:
delay(2);
}

/* Processing code for this example

// Graphing sketch

// This program takes ASCII-encoded strings from the serial port at 9600 baud
// and graphs them. It expects values in the range 0 to 1023, followed by a
// newline, or newline and carriage return

// created 20 Apr 2005


// updated 24 Nov 2015
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

Serial myPort; // The serial port


int xPos = 1; // horizontal position of the graph
float inByte = 0;

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());
// I know that the first port in the serial list on my Mac is always my
// Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);

// don't generate a serialEvent() unless you get a newline character:


myPort.bufferUntil('\n');

// set initial background:


background(0);
}

void draw () {
// draw the line:
stroke(127, 34, 255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:


if (xPos >= width) {
xPos = 0;
background(0);
} else {
// increment the horizontal position:
xPos++;
}
}

void serialEvent (Serial myPort) {


// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
inByte = float(inString);
println(inByte);
inByte = map(inByte, 0, 1023, 0, height);
}
}

*/
Processing Sketch

Using the Processing sketch in the code sample above, you'll get a graph of the sensor's value. As you change
the value of the analog sensor, you'll get a graph something like this:

See Also:

 serial()
 analogRead()
 ASCIITable - Demonstrates Arduino's advanced serial output functions.
 Dimmer - Move the mouse to change the brightness of an LED.
 Midi - Send MIDI note messages serially.
 MultiSerialMega - Use two of the serial ports available on the Arduino and Genuino Mega.
 PhysicalPixel - Turn a LED on and off by sending data to your board from Processing or Max/MSP.
 ReadASCIIString - Parse a comma-separated string of integers to fade an LED.
 SerialCallResponse - Send multiple variables using a call-and-response (handshaking) method.
 SerialCallResponseASCII - Send multiple variables using a call-and-response (handshaking) method, and ASCII-
encode the values before sending.
 SerialEvent - Demonstrates the use of SerialEvent().
 VirtualColorMixer - Send multiple variables from Arduino to your computer and read them in Processing or
Max/MSP.

>>>>>>>>>>>>>>

Dimmer

This example shows how to send data from a personal computer to an Arduino or Genuino board to control the
brightness of an LED. The data is sent in individual bytes, each of which ranges in value from 0 to 255. The
sketch reads these bytes and uses them to set the brightness of the LED.
You can send bytes to the board from any software that can access the computer serial port. Examples for
Processing and Max/MSP version 5 are shown below.

Hardware Required

 Arduino or Genuino Board


 LED
 220 ohm resistor

Software Required

 Processing or
 Max/MSP version 5

Circuit

Connect the 220 ohm current limiting resistor to digital pin 9, with an LED in series. The long, positive leg (the
anode) of the LED should be connected to the output from the resistor, with the shorter, negative leg (the
cathode) connected to ground.

click the image to enlarge


image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

click the image to enlarge

Code
/*
Dimmer

Demonstrates sending data from the computer to the Arduino board, in this case
to control the brightness of an LED. The data is sent in individual bytes,
each of which ranges from 0 to 255. Arduino reads these bytes and uses them to
set the brightness of the LED.

The circuit:
- LED attached from digital pin 9 to ground.
- Serial connection to Processing, Max/MSP, or another serial application

created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe and Scott Fitzgerald

This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Dimmer
*/

const int ledPin = 9; // the pin that the LED is attached to

void setup() {
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}

void loop() {
byte brightness;

// check if data has been sent from the computer:


if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}

/* Processing code for this example

// Dimmer - sends bytes over a serial port

// by David A. Mellis
// This example code is in the public domain.

import processing.serial.*;
Serial port;

void setup() {
size(256, 150);

println("Available serial ports:");


// if using Processing 2.1 or later, use Serial.printArray()
println(Serial.list());
// Uses the first port in this list (number 0). Change this to select the port
// corresponding to your Arduino board. The last parameter (e.g. 9600) is the
// speed of the communication. It has to correspond to the value passed to
// Serial.begin() in your Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600);

// If you know the name of the port used by the Arduino board, you can specify
// it directly like this.
//port = new Serial(this, "COM1", 9600);
}

void draw() {
// draw a gradient from black to white
for (int i = 0; i < 256; i++) {
stroke(i);
line(i, 0, i, 150);
}

// write the current X-position of the mouse to the serial port as


// a single byte
port.write(mouseX);
}

*/

>>>>>>>>>>>

Read ASCII String

This sketch uses the Serial.parseInt() function to locate values separated by a non-alphanumeric character. Often
people use a comma to indicate different pieces of information (this format is commonly referred to as comma-
separated-values or CSV), but other characters like a space or a period will work too. The values are parsed
into integers and used to determine the color of a RGB LED. You'll use the Arduino Software (IDE) serial
monitor to send strings like "5,220,70" to the board to change the light color.

Hardware Required

 Arduino or Genuino Board


 common anode RGB LED
 3 220 ohm resistors
 hook-up wires
 breadboard
Circuit

image developed using Fritzing. For more circuit examples, see the Fritzing project page
Schematic

click the image to enlarge

You'll need four wires to make the circuit above. A wire connects the 5V from the POWER connector of the
board to the longest pin of the RGB LED. You should turn the LED so that the longest pin is the second from
the left..

Place the RGB LED on your breadboard with the longest pin as the second from the top. Check the datasheet
for your specific LED to verify the pins, but they should be R, V+, G and B. The wire from 5V should therefore
connect that second pin from top, as in the connection scheme above.
With your remaining wires, connect your red cathode to pin 3, green cathode to pin 5, and blue cathode to pin 6
in series with the resistors.

RGB LEDs with a common anode share a common power pin. Instead of turning a pin HIGH to illuminate the
LED, you need to turn the pin LOW, to create a voltage difference across the diode. So sending 255 via
analogWrite() turns the LED off, while a value of 0 turns it on at full brightness. In the code below, you'll use a
little bit of math on the sketch side, so you can send values which correspond to the expected brightness.
Essentially, instead of using analogWrite(pin, brightness), you'll be calling analogWrite(pin, 255-brightness).

Code

You'll first set up some global variables for the pins your LED will connect to. This will make it easier to
differentiate which one is red, green, and blue in the main part of your program:

const int redPin = 3;


const int greenPin = 5;
const int bluePin = 6;

In your setup(), begin serial communication at 9600 bits of data per second between the board and your
computer with the line:

Serial.begin(9600);

Also in the setup, you'll want to configure the pins as outputs:

pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

In the loop(), check to see if there is any data in the serial buffer. By making this a while() statement, it will run
as long as there is information waiting to be read :

while (Serial.available() > 0) {

Next, declare some local variables for storing the serial information. This will be the brightness of the LEDs.
Using Serial.parseInt() to separate the data by commas, read the information into your variables:

int red = Serial.parseInt();


int green = Serial.parseInt();
int blue = Serial.parseInt();

Once you've read the data into your variables, check for the newline character to proceed:

if (Serial.read() == '\n') {

Using constrain(), you can keep the values in an acceptable range for PWM control. This way, if the value was
outside the range of what PWM can send, it will be limited to a valid number. By subtracting this value from
255 you will be formatting the value to use with a common anode LED. As explained above, these LEDs will
illuminate when there is a voltage difference between the anode and the pin connected to the board:
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);

Now that you have formatted the values for PWM, use analogWrite() to change the color of the LED. Because
you subtracted your value from 255 in the step above:

analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

Send the value of each LED back to the serial monitor in one string as HEX values :

Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);

Finally, close up your brackets from the if statement, while statement, and main loop :

}
}
}

Once you have programmed the board, open your Arduino Software (IDE) serial monitor. Make sure you have
chosen to send a newline character when sending a message. Enter values between 0-255 for the lights in the
following format : Red,Green,Blue. Once you have sent the values to the board, the attached LED will turn into
the color you specified and you will receive back the HEX values in the serial monitor.

/*
Reading a serial ASCII-encoded string.

This sketch demonstrates the Serial parseInt() function.


It looks for an ASCII string of comma-separated values.
It parses them into ints, and uses those to fade an RGB LED.

Circuit: Common-Cathode RGB LED wired like so:


- red anode: digital pin 3
- green anode: digital pin 5
- blue anode: digital pin 6
- cathode: GND

created 13 Apr 2012


by Tom Igoe
modified 14 Mar 2016
by Arturo Guadalupi

This example code is in the public domain.


*/
// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

void setup() {
// initialize serial:
Serial.begin(9600);
// make the pins outputs:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

void loop() {
// if there's any serial available, read it:
while (Serial.available() > 0) {

// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();

// look for the newline. That's the end of your sentence:


if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);

// fade the red, green, and blue legs of the LED:


analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);

// print the three numbers in one string as hexadecimal:


Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
}
}
}

[Get Code]

See Also:

 if()
 while()
 Serial
 ASCIITable - Demonstrates Arduino's advanced serial output functions.
 Dimmer - Move the mouse to change the brightness of an LED.
 Graph - Send data to the computer and graph it in Processing.
 Midi - Send MIDI note messages serially.
 MultiSerialMega - Use two of the serial ports available on the Arduino and Genuino Mega.
 PhysicalPixel - Turn a LED on and off by sending data to your board from Processing or Max/MSP.
 SerialCallResponse - Send multiple variables using a call-and-response (handshaking) method.
 SerialCallResponseASCII - Send multiple variables using a call-and-response (handshaking) method, and ASCII-
encode the values before sending.
 SerialEvent - Demonstrates the use of SerialEvent().
 VirtualColorMixer - Send multiple variables from Arduino to your computer and read them in Processing or
Max/MSP.

>>>>>>>>>>>>>>>>

MIDI Note Player

This tutorial shows how to send MIDI notes from an Arduino or Genuino board to a MIDI instrument connected
through the standard 5 poles DIN cable.

MIDI, the Musical Instrument Digital Interface, is a useful protocol for controlling synthesizers, sequencers,
and other musical devices. MIDI devices are generally grouped in to two broad classes: controllers (i.e. devices
that generate MIDI signals based on human actions) and synthesizers (including samplers, sequencers, and so
forth). The latter take MIDI data in and make sound, light, or some other effect.

MIDI is a serial protocol that operates at 31,250 bits per second. The board built-in serial port (all of them on
the Mega as well) can send data at that rate.

MIDI bytes are divided into two types: command bytes and data bytes. Command bytes are always 128 or
greater, or 0x80 to 0xFF in hexadecimal. Data bytes are always less than 127, or 0x00 to 0x7F in hex.
Commands include things such as note on, note off, pitch bend, and so forth. Data bytes include things like the
pitch of the note to play, the velocity, or loudness of the note, amount of pitch bend and so forth. For more
details, see the MIDI specification or one of the many MIDI Protocol Guides on the Web.

MIDI data is usually notated in hexadecimal because MIDI banks and instruments are grouped in groups of 16.

For more see this introduction to MIDI or this example.

Hardware Required

 Arduino or Genuino Uno


 Female MIDI jack
 2 220 ohm resistors
 hook-up wires
 MIDI enabled device (optional, for testing)

Circuit

All MIDI connectors are female, by definition of the MIDI spec. Here's how to wire the connector to the board:

 MIDI jack pin 5 connected to Digital pin 1 through a 220 ohm resistor
 MIDI jack pin 2 connected to ground
 MIDI jack pin 4 connected to +5V through a 220 ohm resistor

click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

click the image to enlarge


Code

Attention If you're using a board with ATmega32U4 like DUE or Leonardo, please replace Serial with Serial1
in the sketch below.

/*
MIDI note player

This sketch shows how to use the serial transmit pin (pin 1) to send MIDI note data.
If this circuit is connected to a MIDI synth, it will play the notes
F#-0 (0x1E) to F#-5 (0x5A) in sequence.

The circuit:
- digital in 1 connected to MIDI jack pin 5
- MIDI jack pin 2 connected to ground
- MIDI jack pin 4 connected to +5V through 220 ohm resistor
- Attach a MIDI cable to the jack, then to a MIDI synth, and play music.

created 13 Jun 2006


modified 13 Aug 2012
by Tom Igoe
This example code is in the public domain.

http://www.arduino.cc/en/Tutorial/Midi
*/

void setup() {
// Set MIDI baud rate:
Serial.begin(31250);
}

void loop() {
// play notes from F#-0 (0x1E) to F#-5 (0x5A):
for (int note = 0x1E; note < 0x5A; note ++) {
//Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
noteOn(0x90, note, 0x45);
delay(100);
//Note on channel 1 (0x90), some note value (note), silent velocity (0x00):
noteOn(0x90, note, 0x00);
delay(100);
}
}

// plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that
// data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}

>>>>>>>>>>>>>>

Reference Language | Libraries | Comparison | Changes

parseInt()
Description

parseInt() returns the first valid (long) integer number from the serial buffer. Characters that are not integers (or
the minus sign) are skipped.

In particular:

 Initial characters that are not digits or a minus sign, are skipped;
 Parsing stops when no characters have been read for a configurable time-out value, or a non-digit is read;
 If no valid digits were read when the time-out (see Serial.setTimeout()) occurs, 0 is returned;

Serial.parseInt() inherits from the Stream utility class.


Syntax

Serial.parseInt()

Serial.parseInt(char skipChar)

Parameters

skipChar: used to skip the indicated char in the search. Used for example to skip thousands divider.

Returns

long

See also

 Stream
 Stream.parseInt()
 Tutorial : Read ASCII String

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License.
Code samples in the reference are released into the public domain.

>>>>>>>>>>

Simple Arduino Audio Player and Amplifier with


LM386
Arduino

ByB.Aswinth Raj Jun 26, 2017 98

Simple Arduino Audio Player and Amplifier with LM386


Adding sounds or music to our project will always make it looks cool and sounds much more attractive.
Especially if you are using an Arduino and you have lots of pins free, you can easily add sound effects to your
project by just investing in an extra SD card module and a normal speaker. In this article I will show you how
easy it is to Play music/add sound effects using your Arduino Board. Thanks to the Arduino community
who have developed some libraries to build this in a fast and easy way. We have also used IC LM386 here for
amplification and noise cancelation purpose.

Hardware Required:

1. Arduino UNO
2. SD Card Reader module
3. SD card
4. LM386 Audio Amplifier
5. 10uf Capacitor (2 Nos)
6. 100uf Capacitor (2 Nos)
7. 1K,10K Resistor
8. Push buttons (2 Nos)
9. Breadboard
10. Connecting Wires

Getting ready with your WAV audio files:

For playing sounds from SD Card using Arduino, we need audio files in .wav format because Arduino Board
can play an audio file in a specific format that is wav format. To make an arduino mp3 player, there are a lot
of mp3 shields are available which you can use with arduino. Or else to play mp3 files in arduino, there are
websites which you can be used to convert any audio file on your computer into that specific WAV file.

So to convert any audio file into wav format, follow the below steps:

Step 1: Click on “Online Wav Converter” to enter into the website.

Step 2: Arduino can play a wav file in the following format. You can toy around with the settings later, but
these settings were experiment to be the best in quality.

Bit Resolution 8 Bit


Sampling Rate 16000 Hz
Audio Channel Mono
PCM format PCM unsigned 8-bit
Step 3: In the website click on “choose file” and select the file you want to convert. Then feed in the above
settings. Once done it should look something like this in the below image

Step 4: Now, click on “Convert File” and your Audio file will be converter to .Wav file format. It will also be
downloaded once the conversion is done.

Step 5: Finally format your SD card and save your .wav audio file into it. Make sure you format it before you
add this file. Also remember the name of your audio file. Similarly you can select any of your four audios and
save them with names 1, 2, 3 and 4(Names should not be changed). I have converted four songs and have saved
them as 1.wav, 2.wav, 3.wav and 4.wav like shown below.

Circuit and Hardware:

Circuit Diagram for this Arduino Audio File Player is simple. The complete circuit diagram is shown in the
Image below.
As we know our audio files are saved into the SD card, hence we interface a SD card reader module with our
Arduino. The Arduino and SD card communicate using the SPI communication protocol. Hence the Module
is interfaced with the SPI pins of the Arduino as shown above in the diagram. It is further listed in the table
below.

Arduino SD card module


+5V Vcc
Gnd Gnd
Pin 12 MISO (Master In Slave out)
Pin 11 MOSI (Master Out Slave In)
Pin 13 SCK (Synchronous Clock)
Pin 4 CS (Chip Select)

Now the Arduino will be able to read the music file from the SD card and play it on the pin number 9. But the
audio signals produced by the Arduino on pin 9 will not be audible much. Hence we amplify it by using the
LM386 Low voltage Audio amplifier IC.

The amplifier shown above is designed for a Gain of 200 and the Vdd (pin 6) is powered by the 5V pin of the
Arduino. If you want to increase/decrease the sound you can increase/decrease the voltage provided to this pin.
It can withstand a maximum of 15V. Learn more about this 200 gain amplification configuration for LM386
here.

We also have two push buttons connected to the pin 2 and 3 of the Arduino. These switches are used to play the
next track of the song and play/pause the music respectively. I have used these buttons just to demonstrate its
abilities; you can play the song whenever required. Check the Demo Video at the end.

You can assemble this circuit completely over a Breadboard as shown in the picture below

Programming your Arduino:

Once we are ready with the Hardware and the SD card, we are just one step away playing those songs. Insert the
card into your SD card module and follow the steps below.

Step 1: As said earlier we will be using a library to make this project work. The link for the library is given
below. Click on it and select “Clone or download” and choose download as ZIP.

 TMRpcm library

Step 2: Add this Zip file into your Arduino IDE by selecting Sketch->Include Library -> Add .ZIP Library as
shown below and select the ZIP file that we just downloaded.

Step 3: The complete program of the arduino music player project is given at the end of this article, simply
copy it and paste it in the Arduino Program. Now, click on Upload and get ready to play your audio files.

The program is self explanatory since they have the comment lines. But, I have also explained the ability of the
TMRpcm library below.
Playing an audio file:

You can play any audio that is stored in Wav format inside the SD card module by using the line below.

music.play("3.wav");
//object name.play (“FileName.wav”);

You can use this line at places where you want to trigger the Audio

Pause an audio File:

To pause an Audio file, you can simply call the line below.

music.pause();
//objectname.pause();

Forwarding/Rewinding an Audio:

There are not direct ways to forward or rewind an Audio file, but you can use the line below to play a song at a
particular time. This can be used to forward/rewind with some additional programming.

music.play("2.wav",33); //Plays the song from 33rd second


//objectname.play(“Filename.wav”,time in second);

Setting the quality of the audio:

The library gives us two qualities to play the music, one is to play as normal mode the other to play with 2X
oversampling.

music.quality(0); //Normal Mode


music.quality(1); //2X over sampling mode

Setting the Volume of the audio:

Yes, you can control the volume of the audio through software. You can simply set the volume by using the line
below. Higher music volumes tend to affect the quality of the audio, hence use hardware control when possible.

music.setVolume(5); //Plays the song at volume 5


//objectname.setVolume(Volume level);

Working of this Arduino Music Player:

After programming your Arduino simply press the button connected to pin 2 and your Arduino will play the
first song (saved as 1.wav) for you. Now you can press the button again to change your track to the next song
that is to play 2.wav. Likewise you can navigate to all four songs.

You can also play/Pause the song by pressing the button connected to pin 3. Press it once to pause the song and
press it again to play it from where it stopped. Watch the video below for complete working (or maybe to relax
yourself with some songs).
Hope you enjoyed the project. Now it is up to your creativity to use them in your projects. You can make a
speaking clock, voice assistant, talking robot, voice alert security system and much more. Let me know how
you are planning to use it through the comment section and also if you have any problems in getting this thing
work you can reach me through the forums or the comment section below.

Code

/*
Arduino Based Music Player

This example shows how to play three songs from SD card by pressing a push button

The circuit:
* Push Button on pin 2 and 3
* Audio Out - pin 9
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created 25 Jun 2017


by Aswinth Raj

This example code was created for CircuitDigest.com

*/

#include "SD.h" //Lib to read SD card


#include "TMRpcm.h" //Lib to play auido
#include "SPI.h" //SPI lib for SD card

#define SD_ChipSelectPin 4 //Chip select is pin number 4


TMRpcm music; //Lib object is named "music"

int song_number=0;
boolean debounce1=true;
boolean debounce2=true;
boolean play_pause;

void setup(){
music.speakerPin = 9; //Auido out on pin 9
Serial.begin(9600); //Serial Com for debugging
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

pinMode(2, INPUT_PULLUP); //Button 1 with internal pull up to chage track


pinMode(3, INPUT_PULLUP); //Button 2 with internal pull up to play/pause
pinMode(3, INPUT_PULLUP); //Button 2 with internal pull up to fast forward
music.setVolume(5); // 0 to 7. Set volume level
music.quality(1); // Set 1 for 2x oversampling Set 0 for normal
//music.volume(0); // 1(up) or 0(down) to control volume
//music.play("filename",30); plays a file starting at 30 seconds into the track
}

void loop()
{

if (digitalRead(2)==LOW && debounce1 == true) //Button 1 Pressed


{
song_number++;
if (song_number==5)
{song_number=1;}
debounce1=false;
Serial.println("KEY PRESSED");
Serial.print("song_number=");
Serial.println(song_number);

if (song_number ==1)
{music.play("1.wav",10);} //Play song 1 from 10th second

if (song_number ==2)
{music.play("2.wav",33);} //Play song 2 from 33rd second

if (song_number ==3)
{music.play("3.wav");} //Play song 3 from start

if (song_number ==4)
{music.play("4.wav",25);} //Play song 4 from 25th second

if (digitalRead(3)==LOW && debounce2 == true) //Button 2 Pressed


{
music.pause(); Serial.println("PLAY / PAUSE");
debounce2=false;
}

if (digitalRead(2)==HIGH) //Avoid debounce


debounce1=true;

if (digitalRead(3)==HIGH)//Avoid debounce
debounce2=true;
}

>>>>>>>>>>>>>>>>>
Simple Audio Player
Hardware Required

 Arduino Due Board


 8-ohm speaker or headphones
 Arduino shield with an SD card with cs CS 4 (like the Ethernet shield)

Componets to build an external audio amplifier

 LM386 (low power audio amplifier)


 10 kohm potentiometer
 10 ohm resistor
 2 x 10 µF capacitor
 0.05 µF (or 0.1 µF) capacitor
 250 µF capacitor

The Circuit

The shield sits on top of the Due with a micro-SD card in the slot. A .wav file named "test.wav" is in the card's
root directory. For a simple test you can attach a pair of headphones directly to ground and DAC0, respecting
the polarity.

To connect a speaker to the board you have add an amplification circuit connected between the DAC0 pin and
the speaker. The amplification circuit will increase the volume of the speaker. There are many audio amplifiers
available, one of the most common is the LM386. The following scheme shows how to build the circuit using
the LM386 and a bunch of components. You can supply the LM386 connecting the Vs pin with different
voltages sources, like for example the +5 V present on the 5V pin of the Arduino Due or an external 9V battery.
The gain of the amplifier is given by the capacitor connected to pin 1 and 8 of the LM386. With the 10 µF
capacitor the gain is set to 200, without the capacitor the gain is 50. With the potentiometer you can control the
volume of the amplifier.
Warning: do not connect the speaker directly to the pins of the Arduino Due.

LM386 electronic schematic


LM386 mounting on breadboard

Audio File

The Audio file to store on the SD card must be in the .wav format with 44100 Hz, 16-bit stereo quality.

Code
/*
Simple Audio Player

Demonstrates the use of the Audio library for the Arduino Due

Hardware required :
* Arduino shield with a SD card on CS4
* A sound file named "test.wav" in the root directory of the SD card
* An audio amplifier to connect to the DAC0 and ground
* A speaker to connect to the audio amplifier

Original by Massimo Banzi September 20, 2012


Modified by Scott Fitzgerald October 19, 2012
Modified by Arturo Guadalupi December 18, 2015

This example code is in the public domain

http://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

*/

#include <SD.h>
#include <SPI.h>
#include <Audio.h>

void setup() {
// debug output at 9600 baud
Serial.begin(9600);

// setup SD-card
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println(" failed!");
while(true);
}
Serial.println(" done.");
// hi-speed SPI transfers

// 44100kHz stereo => 88200 sample rate


// 100 mSec of prebuffering.
Audio.begin(88200, 100);
}

void loop() {
int count = 0;

// open wave file from sdcard


File myFile = SD.open("test.wav");
if (!myFile) {
// if the file didn't open, print an error and stop
Serial.println("error opening test.wav");
while (true);
}

const int S = 1024; // Number of samples to read in block


short buffer[S];

Serial.print("Playing");
// until the file is not finished
while (myFile.available()) {
// read from the file into buffer
myFile.read(buffer, sizeof(buffer));

// Prepare samples
int volume = 1024;
Audio.prepare(buffer, S, volume);
// Feed samples to audio
Audio.write(buffer, S);

// Every 100 block print a '.'


count++;
if (count == 100) {
Serial.print(".");
count = 0;
}
}
myFile.close();

Serial.println("End of file. Thank you for listening!");


while (true) ;
}

>>>>>>>>>>>>>>>>>>>>>>>>

Play .wav files on Arduino without an SD card


Usually when you're trying to play .wav files on an Arduino Uno, you'll need a SD card module because the
Arduino cannot play sounds that are longer than 4s.

However, if you want to play around with shorter sounds, you can upload them onto your Arduino without
having to buy an SD card shield.

If your .wav file is in iTunes, go through the following steps:

 go to Preferences > General Tab.


 click 'import settings'.
 select 'custom' from the 'setting' dropdown.
 Inside the custom settings, enter the same settings as below:
 click ok on everything.
 Right-click on the audio you want to convert and select 'create MP3 version'.

After this, you're gonna have to convert this new 8KHz sound to numeric values so it can be interpreted by the
Arduino. To do this, you can download a software called EncodeAudio, and select your newly converted audio
file. Once the program has finished encoding it, it will copy it to your clipboard automatically so you can paste
it in your code.

Now, to be able to use it with your Arduino, you have to download the PCM library for Arduino.

Once this is downloaded, rename it to just 'PCM' and add it to the libraries folder where you usually have your
other Arduino libraries. You'll probably have to restart Arduino to be able to see it in the 'include library'
dropdown.

After this, re-open Arduino, go to File > Examples > PCM and click on the playback example.

Where you see the array of numeric values, delete them and replace them with the ones you just copied to your
clipboard.

Once you get a speaker connected to your Arduino on PIN 11, you can upload the sketch and you should hear
your sound!

Of course, using a SD card module or a sound board would be better but if you don't have one right now, it's a
good way to prototype stuff!

>>>>>>>>>>>>>
Playing Wave File Using Arduino

Step 1: Parts
1- Arduino Nano V3.0 (I used the chines version called Funduino Nano).
2- SD card Module.
3- SD card.
4- Bread Board.
5- four push Button .
6- four 22K resistors.
7- one 4.7K resistor.
8- BC546B NPN transistor.
9- Speaker.
10- wires.
Step 2: Prepare Your SD Card

1- Format SD card and make sure the setting as attached picture.


2- Convert your music to .WAV files and make sure the below:
-Samples Per second(Hz):16000
-Channel :Mono
- Bits Per Sample: 8
I use Wav Sample rate converter software (picture attached).
3- Wave files samples attached.

Attachments

 WAV files.zip
Step 3: Circuit Digram

Attachments

 Wav player.fzz

Step 4: Source Code


1-Before writing the code you need to install TMRpcm library from below link:
https://github.com/TMRh20/TMRpcm/wiki

all information how to install and use the library included in the website .

2- Download the attached WavSW_ino.zip file and open it with arduino sketch ,I tried to copy and paste the Source Code
from arduino sketch to instructable but for some reason the text convert to rubbish.

Attachments

 WavSW_ino.zip

Step 5: Troubleshooting Update 29/5/2016

For people whom unable to make this circuit work ,I created the attached folder "for test" for troubleshooting
purpose .

The folder includes tested code for Arduino Nano ,UNO and MEGA.

No need to connect the push buttons,the sounds will play automatically.

No need to connect the transistor ,Connect a small speaker or headphone directly to pin 9 for arduino nano or
pin 11 for Mega .

Copy the .wav files directly to SD card ,Do not put them inside folder.

Pin Connection:

Arduino Nano ---------> SD Card

12 -------------------> MISO

11 -------------------->MOSI

13 -------------------->SCK

4 ---------------------->CS

9 ---------------------->Speaker

GND ------------------>GND

5V ------------------> VCC
Arduino MEGA ---------> SD Card
50-------------------> MISO

51-------------------->MOSI

52 -------------------->SCK

53---------------------->CS

11---------------------->Speaker

GND ------------------>GND

5V ------------------> VCC

if the tested code worked fine do the following for the push buttons code file to make it work:

1-If you faced problem in compiling the original push buttons code file ,please add line #include<SPI.h>

in the 3rd line of the code.

still have no sound add a delay command between the play commands delay(1000);

Good luck

>>>>>>>>>>>>>

How to play WAV audio files with Arduino Uno and


MicroSD card
A couple days ago I printed Yoda on my 3d Printer – http://instagram.com/p/U2HR__StrH/

Yesterday I put him on a remote controlled micro robotic platform, watch video of it in action here:

The basics setup is this :

 Arduino Uno.
 MicroSD card reader (4$ at DX.com ).
 MicroSD card (6$ on Amazon)
 Speaker and a transistor to act as amplifier.
 LED
 3D printed Yoda.

I found some Yoda WAV sound files online and encoded them from iTunes into 8bit 16Khz mono sound. Then
put the files on the microSD card from the computer.

Put the MicroSD card into the card reader.

Hook up the card reader as follows:


 3.3v goes to 3.3v on the Arduino UNO (for power)
 GND goes to Ground on Arduino UNO
 D0 goes to pin 12 on Arduino UNO
 D1 goes to pin 11 on Arduino UNO
 CLK goes to pin 13 on Arduino UNO
 D3 goes to pin 10 on Arduino UNO

Now you are able to read and write files to the MicroSD card.

The next step is to download this Arduino library to play WAV files and install it :

https://github.com/TMRh20/TMRpcm

Here is the code for my Arduino sketch :

#include <SD.h> // need to include the SD library


//#define SD_ChipSelectPin 53 //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10 //using digital pin 4 on arduino nano 328
#include <TMRpcm.h> // also need to include this library...

TMRpcm tmrpcm; // create an object for use in this sketch


char mychar;

void setup(){

tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) { // see if the card is present and can be
initialized:
Serial.println("SD fail");
return; // don't do anything more if not
}
tmrpcm.play("beware.wav"); //the sound file "music" will play each time the arduino
powers up, or is reset
}

void loop(){

if(Serial.available()){
mychar = Serial.read();

if(mychar == 'o'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("helpyou.wav");
} else if(mychar == 'r'){ //send the letter p over the serial monitor to start
playback
tmrpcm.play("chortle.wav");
} else if(mychar == 'q'){ //send the letter p over the serial monitor to start
playback
tmrpcm.play("helpyou.wav");
} else if(mychar == 'p'){
tmrpcm.play("beware.wav");
}
else if(mychar == 'w'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("impresiv.wav");
}
else if(mychar == 't'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("seekyoda.wav");
}
else if(mychar == 'y'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("sensefear.wav");
}
else if(mychar == 'u'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("strongami.wav");
}
else if(mychar == 'i'){ //send the letter p over the serial monitor to start playback
tmrpcm.play("whyhere.wav");
}
}

Upload that sketch to the Arduino after installing the TMRpcm WAV library.

All that’s left is connecting a speaker!

I found a spare transistor (2N2222) and hooked it up before connecting the speaker (you can also use a piezo
speaker without transistor just to test if it works as intended),

Follow this schematic to connect the speaker to the arduino : http://blog.bryanduxbury.com/2012/01/one-


transistor-audio-amplifier-for.html

My speaker is on pin 9 so do the same and you will be all set.

After connecting the speaker and uploading the sketch I open up serial connection terminal and send commands
– letters from q to p on the keyboard, sending each character will play a different sound on the Arduino.

Now you can play audio files through your Arduino, on the cheap and with a lot of fun to come!

>>>>>>>>>>>>>>

Você também pode gostar