SlideShare une entreprise Scribd logo
1  sur  180
Télécharger pour lire hors ligne
What is Arduino?
Arduino is a tool for making computers that can sense and control more of the physical world than your
desktop computer. It's an open-source physical computing platform based on a simple microcontroller
board, and a development environment for writing software for the board.
Arduino can be used to develop interactive objects, taking inputs from a variety of switches or sensors,
and controlling a variety of lights, motors, and other physical outputs. Arduino projects can be standalone, or they can be communicate with software running on your computer (e.g. Flash,
Processing, MaxMSP.) The boards can be assembled by hand or purchased preassembled; the opensource IDE can be downloaded for free.
The Arduino programming language is an implementation of Wiring, a similar physical computing
platform, which is based on the Processing multimedia programming environment.
Why Arduino?
There are many other microcontrollers and microcontroller platforms available for physical computing.
Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard, and many others offer similar
functionality. All of these tools take the messy details of microcontroller programming and wrap it up in
an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it
offers some advantage for teachers, students, and interested amateurs over other systems:


Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller platforms.
The least expensive version of the Arduino module can be assembled by hand, and even the preassembled Arduino modules cost less than $50



Cross-platform - The Arduino software runs on Windows, Macintosh OSX, and Linux operating systems.
Most microcontroller systems are limited to Windows.



Simple, clear programming environment - The Arduino programming environment is easy-to-use for
beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it's
conveniently based on the Processing programming environment, so students learning to program in
that environment will be familiar with the look and feel of Arduino



Open source and extensible software- The Arduino software is published as open source tools, available
for extension by experienced programmers. The language can be expanded through C++ libraries, and
people wanting to understand the technical details can make the leap from Arduino to the AVR C
programming language on which it's based. SImilarly, you can add AVR-C code directly into your
Arduino programs if you want to.



Open source and extensible hardware - The Arduino is based on
Atmel's ATMEGA8 and ATMEGA168microcontrollers. The plans for the modules are published under a
Creative Commons license, so experienced circuit designers can make their own version of the module,
extending it and improving it. Even relatively inexperienced users can build the breadboard version of
the module in order to understand how it works and save money.
Examples
See the foundations page for in-depth description of core concepts of the Arduino hardware and
software; thehacking page for information on extending and modifying the Arduino hardware and
software; and the links pagefor other documentation.
Note: these examples are written for Arduino 1.0 and later. Certain functions may not work in
earlier versions. For best results, download the latest version.
Here's a style guide that helps with writing examples for beginners.
Core F unctions

Libraries

Simple programs that demonstrate basic

Examples from the libraries that are included in

Arduino commands. These are included with the

the Arduino software.

Arduino environment; to open them, click the

EEPROM Library

Open button on the toolbar and look in
the examples folder.
1.Basics


BareMinimum: The bare minimum of code



EEPROM Clear: clear the bytes in the EEPROM.



EEPROM Read: read the EEPROM and send its
values to the computer.



needed to start an Arduino sketch.


input to the EEPROM.

Blink: Turn an LED on and off.



EEPROM Write: stores values from an analog

DigitalReadSerial: Read a switch, print the state

Ethernet Library

out to the Arduino Serial Monitor.



ChatServer: set up a simple chat server.

AnalogReadSerial: Read a potentiometer, print



WebClient: make a HTTP request.

it's state out to the Arduino Serial Monitor.







WebClientRepeating: Make repeated HTTP

Fade: Demonstrates the use of analog output to
fade an LED.



requests.


ReadAnalogVoltage : Reads an analog input and
prints the voltage to the serial monitor

displays analog sensor values.




PachubeClientString: send strings to
pachube.com.

Blink Without Delay: blinking an LED without
using the delay() function.

PachubeClient: connect to pachube.com, a free
datalogging site.

2.Digital


WebServer: host a simple HTML page that



BarometricPressureWebServer: outputs the



Button: use a pushbutton to control an LED.

values from a barometric pressure sensor as a



Debounce: read a pushbutton, filtering noise.

web page.



Button State Change: counting the number of



button pushes.


Input Pullup Serial: Demonstrates the use of

strings via UDP.


INPUT_PULLUP with pinMode().


Tone: play a melody with a Piezo speaker.



UDPSendReceiveString: Send and receive text
UdpNtpClient: Query a Network Time Protocol
(NTP) server using UDP.

Pitch follower: play a pitch on a piezo speaker



DnsWebClient: DNS and DHCP-based Web
client.

depending on an analog input.




DhcpChatServer: A simple DHCP Chat Server

Simple Keyboard: a three-key musical keyboard



DhcpAddressPrinter: Get an IP address via

using force sensors and a piezo speaker.


DHCP and print it out

Tone4: play tones on multiple speakers



TwitterClient: A Twitter client with Strings

sequentially using the tone() command.



TelnetClient: A simple Telnet client

3.Analog

Firmata Libraries


AnalogInOutSerial: read an analog input pin,



map the result, and then use that data to dim or

Liq uidCrystal Library

brighten an LED.


Analog Input: use a potentiometer to control the

Guide to the Standard Firmata Library



blinking of an LED.

Hello World: displays "hello world!" and the
seconds since reset.



AnalogWriteMega: fade 12 LEDs on and off, one



Blink: control of the block-style cursor.

by one, using an Arduino Mega board.





Cursor: control of the underscore-style cursor.

Calibration: define a maximum and minimum



Display: quickly blank the display without losing

for expected analog sensor values.


Fading: use an analog output (PWM pin) to fade

what's on it.


an LED.

TextDirection: control which way text flows from
the cursor.

Smoothing: smooth multiple readings of an



Scroll: scroll text left and right.

analog input.





Serial input: accepts serial input, displays it.



SetCursor: set the cursor position.



Autoscroll: shift text right and left.

4.Communication
These examples include code that allows the
Arduino to talk to Processing sketches running

SPI Library

on the computer. For more information or to
download Processing, seeprocessing.org. There



BarometricPressureSensor: read air pressure

are also Max/MSP patches that can

and temperature from a sensor using the SPI

communicate with each Arduino sketch as well.

protocol.

For more on Max/MSP see Cycling 74. For Pd



potentiometer using the SPI protocol.

patches that can communicate with these
sketches, see Scott Fitzgerald's examples.


ReadASCIIString: parse a comma-separated
string of ints to fade an LED



ASCII Table: demonstrates Arduino's advanced
serial output functions.



Servo Library






Software Serial Library

Graph: send data to the computer and graph it


one serial port just isn't enough!

data to your Arduino from Processing or


Software Serial Example: how to use
theSoftwareSerial Library...Because sometimes

Physical Pixel: turn a LED on and off by sending
Max/MSP.

Sweep: sweeps the shaft of a servo motor back
and forth.

Dimmer: move the mouse to change the

in Processing.

Knob: control the shaft of a servo motor by
turning a potentiometer.

brightness of an LED.


SPIDigitalPot: control a AD5206 digital



Two Port Receive: how to work with multiple
software serial ports.

Virtual Color Mixer: send multiple variables
from Arduino to your computer and read them

Stepper Library

in Processing or Max/MSP.


Serial Call Response: send multiple vairables



motor using a potentiometer.

using a call-and-response (handshaking)
method.


Wire Library

Serial Call Response ASCII: send multiple
variables using a call-and-response

Motor Knob: control a highly accurate stepper



SFRRanger_reader: read a

(handshaking) method, and ASCII-encode the

Devantech SRFxx ultra-sonic range finder

values before sending.

using I2C communication.


SerialEvent: Demonstrates the use



of SerialEvent().


Serial input (Switch (case) Statement): how to

digital_potentiometer: control a AD5171 digital
pot using the Wire Library.



master reader/slave sender: set up two (or

take different actions based on characters

more) arduino boards to share information via a

received by the serial port.

master reader/slave sender configuration.



MIDI: send MIDI note messages serially.



MultiSerialMega: use two of the serial ports

arduino boards to share information using a

available on the Arduino Mega.

master writer/slave reader set up.

5.Control Structures

WiFi Library





The WiFi Library will be included in a future

If Statement (Conditional): how to use an if

release of the Arduino IDE. You can download

statement to change output conditions based on

the most recent version, and install it as you

changing input conditions.






Array: a variation on the For Loop example that
demonstrates how to use an array.



would any other library.

For Loop: controlling multiple LEDs with a for
loop and.

ConnectNoEncryption : Demonstrates how to
connect to an open network



While Loop: how to use a while loop to calibrate
a sensor while a button is being read.

master writer/slave reader: allow two (or more)

ConnectWithWEP : Demonstrates how to
connect to a network that is encrypted with WEP



ConnectWithWPA : Demonstrates how to

Switch Case: how to choose between a discrete

connect to a network that is encrypted

number of values. Equivalent to multiple If



with WPA2 Personal

statements. This example shows how to divide a



sensor's range into a set of four bands and to

ScanNetworks : Displays all WiFi networks in
range

take four different actions depending on which

WiFiChatServer : Set up a simple chat server

band the result is in.





WiFiPachubeClient : connect to pachube.com, a

Switch Case 2: a second switch-case example,
showing how to take different actions based in

free datalogging site


characters received in the serial port.
6.Sensors


ADXL3xx: read an ADXL3xx accelerometer.



Memsic2125 : two-axis acceleromoter.



Ping: detecting objects with an ultrasonic range

pachube.com


WiFiTwitterClient : A Twitter client with Strings



WiFiWebClient : Connect to a remote webserver



WiFiWebClientRepeating: Repeatedly make

Knock: detect knocks with a piezo element.



finder.

WiFiPachubeClientString: send strings to

HTTP calls to a server


WiFiWebServer : Serve a webpage from
the WiFishield
Arduino as ISP Programmer

7.Display

ArduinoISP turns your Arduino into an in-

Examples of basic display control

circuit programmer to re-program Atmega



LED Bar Graph: how to make an LED bar graph.



Row Column Scanning: how to control an 8x8
matrix of LEDs.
8.Strings



StringAdditionOperator: add strings together in
a variety of ways.

chips. Useful when you need to re-load the
bootloader on an Arduino, if you're going from
Arduino to an Atmega on a breadboard, or if
you're making your own Arduino-compatible
circuit on a breadboard.
More
For a huge list of examples from the Arduino


StringAppendOperator: append data to strings.

community, see the interfacing with



StringCaseChanges: change the case of a string.

hardware page on the playground wiki. Also see



StringCharacters: get/set the value of a specific

the list of old examples.

character in a string.


StringComparisonOperators: compare strings
alphabetically.



StringConstructors: how to initialize string
objects.



StringIndexOf: look for the first/last instance of
a character in a string.



StringLength & StringLengthTrim: get and trim
the length of a string.



StringReplace: replace individual characters in a
string.



StringStartsWithEndsWith: check which
characters/substrings a given string starts or
ends with.



StringSubstring: look for "phrases" within a
given string.
9.USB (Leonardo, Micro, and D ue
specific examples)
The Keyboard and Mouse examples are unique
to the Leonardo, Micro and Due. They
demonstrate the use of libraries that are unique
to the board.



KeyboardAndMouseControl: Demonstrates the
Mouse and Keyboard commands in one
program.
Keyboard



KeyboardMessage: Sends a text string when a
button is pressed.



KeyboardLogout : Logs out the current user with
key commands



KeyboardSerial: Reads a byte from the serial
port, and sends back a keystroke.



KeyboardReprogram : opens a new window in
the Arduino IDE and reprograms the Leonardo
with a simple blink program
Mouse



ButtonMouseControl: Control cursor movement
with 5 pushbuttons.



JoystickMouseControl: Controls a computer's
cursor movement with a Joystick when a button
is pressed.

Core Functions

1-BASICS
Bare minimum

Bare Minimum code needed to get started
This example contains the bare minimum of code you need for an Arduino sketch to compile:
the setup() method and theloop() method.
Hardware Required


Arduino Board
Circuit
Only your Arduino Board is needed for this example.

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

Code
The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using
libraries, etc. The setup function will only run once, after each powerup or reset of the Arduino board.
After creating a setup() function, the loop() function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond as it runs. Code in the loop() section of your
sketch is used to actively control the Arduino board.
The code below won't actually do anything, but it's structure is useful for copying and pasting to get you
started on any sketch of your own. It also shows you how to make comments in your code.
Any line that starts with two slashes (//) will not be read by the compiler, so you can write anything you
want after it. Commenting your code like this can be particularly helpful in explaining, both to yourself
and others, how your program functions step by step.
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}

Blink
Blink
This example shows the simplest thing you can do with an Arduino to see physical output: it blinks an
LED.
Hardware Required


Arduino Board



LED
Circuit
To build the circuit, attach a 220-ohm resistor to pin 13. Then attach the long leg of an LED (the positive
leg, called the anode) to the resistor. Attach the short leg (the negative leg, called the cathode) to ground.
Then plug your Arduino board into your computer, start the Arduino program, and enter the code below.
Most Arduino boards already have an LED attached to pin 13 on the board itself. If you run this example
with no hardware attached, you should see that LED blink.
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
In the program below, the first thing you do is to initialize pin 13 as an output pin with the line
pinMode(13, OUTPUT);

In the main loop, you turn the LED on with the line:
digitalWrite(13, HIGH);

This supplies 5 volts to pin 13. That creates a voltage difference across the pins of the LED, and lights it
up. Then you turn it off with the line:
digitalWrite(13, LOW);

That takes pin 13 back to 0 volts, and turns the LED off. In between the on and the off, you want enough
time for a person to see the change, so the delay() commands tell the Arduino to do nothing for 1000
milliseconds, or one second. When you use the delay() command, nothing else happens for that amount
of time. Once you've understood the basic examples, check out the BlinkWithoutDelay example to learn
how to create a delay while doing other things.
Once you've understood this example, check out the DigitalReadSerial example to learn how read a
switch connected to the Arduino.
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH);
// turn the LED on (HIGH is the voltage level)
delay(1000);
// wait for a second
digitalWrite(led, LOW);
// turn the LED off by making the voltage LOW
delay(1000);
// wait for a second
}

Digital Read Serial
Digital Read Serial
This example shows you how to monitor the state of a switch by establishing serial
communication between your Arduino and your computer over USB.
Hardware Required


Arduino Board



A momentary switch, button, or toggle switch



10k ohm resistor



breadboard



hook-up wire
Circuit
image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect three wires to the Arduino board. The first two, red and black, connect to the two long vertical
rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes
from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pulldown resistor (here 10 KOhms) to ground. The other leg of the button connects to the 5 volt supply.
Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is
open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected
to ground (through the pull-down resistor) and reads as LOW, or 0. When the button is closed (pressed),
it makes a connection between its two legs, connecting the pin to 5 volts, so that the pin reads as HIGH,
or 1.
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the
input is "floating" - that is, it doesn't have a solid connection to voltage or ground, and it will randomly
return either HIGH or LOW. That's why you need a pull-down resistor in the circuit.
Schematic
Code
In the program below, the very first thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with the
line:
Serial.begin(9600);

Next, initialize digital pin 2, the pin that will read the output from your button, as an input:
pinMode(2,INPUT);

Now that your setup has been completed, move into the main loop of your code. When your button is
pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be
connected to ground through the 10-kilohm resistor. This is a digital input, meaning that the switch can
only be in either an on state (seen by your Arduino as a "1", or HIGH) or an off state (seen by your
Arduino as a "0", or LOW), with nothing in between.
The first thing you need to do in the main loop of your program is to establish a variable to hold the
information coming in from your switch. Since the information coming in from the switch will be either a
"1" or a "0", you can use anint datatype. Call this variable sensorValue, and set it to equal whatever is
being read on digital pin 2. You can accomplish all this with just one line of code:
int sensorValue = digitalRead(2);

Once the Arduino has read the input, make it print this information back to the computer as a decimal
value. You can do this with the command Serial.println() in our last line of code:
Serial.println(sensorValue);

Now, when you open your Serial Monitor in the Arduino environment, you will see a stream of "0"s if
your switch is open, or "1"s if your switch is closed.
/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor
This example code is in the public domain.
*/
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1);
// delay in between reads for stability
}

Analog Read Serial
Analog Read Serial
This example shows you how to read analog input from the physical world using a potentiometer.
A potentiometer is a simple mechanical device that provides a varying amount of resistance when its
shaft is turned. By passing voltage through a potentiometer and into an analog input on your Arduino, it
is possible to measure the amount of resistance produced by a potentiometer (or pot for short) as an
analog value. In this example you will monitor the state of your potentiometer after establishing serial
communication between your Arduino and your computer.
Hardware Required


Arduino Board



10-kilohm Potentiometer
Circuit
Connect the three wires from the potentiometer to your Arduino board. The first goes to ground from
one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer pin of the
potentiometer. The third goes from analog input 2 to the middle pin of the potentiometer.
click the image to enlarge

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

By turning the shaft of the potentiometer, you change the amount of resistance on either side of the
wiper which is connected to the center pin of the potentiometer. This changes the voltage at the center
pin. When the resistance between the center and the side connected to 5 volts is close to zero (and the
resistance on the other side is close to 10 kilohms), the voltage at the center pin nears 5 volts. When the
resistances are reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog
voltage that you're reading as an input.
The Arduino has a circuit inside called an analog-to-digital converter that reads this changing
voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in one
direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned all the way
in the opposite direction, there are 5 volts going to the pin and the input value is 1023. In
between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of
voltage being applied to the pin.
Schematic
click the image to enlarge
Code
In the program below, the only thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with the
command:
Serial.begin(9600);

Next, in the main loop of your code, you need to establish a variable to store the resistance value (which
will be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer:
int sensorValue = analogRead(A0);

Finally, you need to print this information to your serial window as a decimal (DEC) value. You can do this
with the command Serial.println() in your last line of code:
Serial.println(sensorValue, DEC)

Now, when you open your Serial Monitor in the Arduino development environment (by clicking the
button directly to the right of the "Upload" button in the header of the program), you should see a steady
stream of numbers ranging from 0-1023, correlating to the position of the pot. As you turn your
potentiometer, these numbers will respond almost instantly.
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1);
// delay in between reads for stability
}

Fading

Fading
Demonstrates the use of the analogWrite() function in fading an LED off and on. AnalogWrite uses pulse
width modulation (PWM), turning a digital pin on and off very quickly, to create a fading effect.
Hardware Required


Arduino board



Breadboard



a LED



a 220 ohm resistor
Circuit
Connect the anode (the longer, positive leg) of your LED to digital output pin 9 on your Arduino
through a 220-ohm resistor. Connect the cathode (the shorter, negative leg) directly to ground.
click the image to enlarge

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

Code
After declaring pin 9 to be your ledPin, there is nothing to do in the setup() function of your code.
The analogWrite() function that you will be using in the main loop of your code requires two arguments:
One telling the function which pin to write to, and one indicating what PWM value to write.
In order to fade your LED off and on, gradually increase your PWM value from 0 (all the way off) to 255
(all the way on), and then back to 0 once again to complete the cycle. In the sketch below, the PWM value
is set using a variable calledbrightness. Each time through the loop, it increases by the value of the
variable fadeAmount.
If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In
other words, if fadeAmount is 5, then it is set to -5. If it's 55, then it's set to 5. The next time through the
loop, this change causesbrightness to change direction as well.
analogWrite()

can change the PWM value very fast, so the delay at the end of the sketch controls the speed

of the fade. Try changing the value of the delay and see how it changes the program.
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
int led = 9;
int brightness = 0;
int fadeAmount = 5;

// the pin that the LED is attached to
// how bright the LED is
// how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the
if (brightness
fadeAmount =
}
// wait for 30
delay(30);

direction of the fading at the ends of the fade:
== 0 || brightness == 255) {
-fadeAmount ;
milliseconds to see the dimming effect

}

Analog Read Voltage

Analog Read Voltage
This example shows you how to read an analog input on Pin 0, convert the values from analogRead()
into voltage, and print it out to the serial monitor.
Hardware Required


Arduino Board



a variable resistor, like a potentiometer
Circuit

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

Connect the three wires from the potentiometer to your Arduino board. The first goes to ground from
one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer pin of the
potentiometer. The third goes from analog input 2 to the middle pin of the potentiometer.
By turning the shaft of the potentiometer, you change the amount of resistance on either side of the
wiper which is connected to the center pin of the potentiometer. This changes the voltage at the center
pin. When the resistance between the center and the side connected to 5 volts is close to zero (and the
resistance on the other side is close to 10 kilohms), the voltage at the center pin nears 5 volts. When the
resistances are reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog
voltage that you're reading as an input.
The Arduino has a circuit inside called an analog-to-digital converter that reads this changing
voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in one
direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned all the way
in the opposite direction, there are 5 volts going to the pin and the input value is 1023. In
between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of
voltage being applied to the pin.
Schematic

Code
In the program below, the very first thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with the
line:
Serial.begin(9600);

Next, in the main loop of your code, you need to establish a variable to store the resistance value (which
will be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer:
int sensorValue = analogRead(A0);

To change the values from 0-1023 to a range that corresponds to the voltage the pin is reading, you'll
need to create another variable, a float, and do a little math. To scale the numbers between 0.0 and 5.0,
divide 5.0 by 1023.0 and multiply that by sensorValue :
float voltage= sensorValue * (5.0 / 1023.0);

Finally, you need to print this information to your serial window as. You can do this with the
command Serial.println() in your last line of code:
Serial.println(voltage)
Now, when you open your Serial Monitor in the Arduino development environment (by clicking the
button directly to the right of the "Upload" button in the header of the program), you should see a steady
stream of numbers ranging from 0.0 - 5.0. As you turn the pot, the values will change, corresponding to
the voltage coming into pin A0.
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the
serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and
ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}

2.Digital

Blink Without Delay
Blink Without Delay
Sometimes you need to do two things at once. For example you might want to blink an LED (or some
other time-sensitive function) while reading a button press or other input. In this case, you can't
use delay(), or you'd stop everything else the program while the LED blinked. The program might miss
the button press if it happens during the delay(). This sketch demonstrates how to blink the LED without
using delay(). It keeps track of the last time the Arduino turned the LED on or off. Then, each time
through loop(), it checks if a long enough interval has passed. If it has, it toggles the LED on or off.
Hardware Required


Arduino Board



LED
Circuit
To build the circuit, grab an LED and attach its long, positive leg (called the anode) to pin 13. Attach the
short, negative leg (called the anode) to ground. Then plug your Arduino board into your computer, start
the Arduino program, and enter the code below.
Schematic:
click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page
Code
The code below uses the millis() function, a command that returns the number of milliseconds since the
Arduino board started running its current program, to blink an LED.
/* Blink without Delay
Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13;
// the number of the LED pin
// Variables will change:
int ledState = LOW;
long previousMillis = 0;

// ledState used to set the LED
// will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;
// interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
Button

Button
Pushbuttons or switches connect two points in a circuit when you press them. This example turns on the
built-in LED on pin 13 when you press the button.
Hardware


Arduino Board



momentary button or switch



10K ohm resistor



breadboard



hook-up wire
Circuit

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

Connect three wires to the Arduino board. The first two, red and black, connect to the two long vertical
rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes
from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pulldown resistor (here 10 KOhms) to ground. The other leg of the button connects to the 5 volt supply.
When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW.
When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5
volts, so that we read a HIGH.
You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going
LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED
normally on and turning off when you press the button.
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the
input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up
or pull-down resistor in the circuit.
Schematic:
click the image to enlarge
Code
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;
// the number of the pushbutton pin
const int ledPin = 13;
// the number of the LED pin
// variables will change:
int buttonState = 0;

// variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Debounce

Debounce
This example demonstrates the use of a pushbutton as a switch: each time you press the button, the LED
(or whatever) is turned on (if it's off) or off (if on). It also debounces the input, which means checking
twice in a short period of time to make sure it's definitely pressed. Without debouncing, pressing the
button once can appear to the code as multiple presses. Makes use of the millis() function to keep track
of the time when the button is pressed.
Hardware Required


Arduino Board



momentary button or switch



10K ohm resistor



breadboard



hook-up wire
Circuit

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

Schematic
click the image to enlarge
Code
The code below is based on Limor Fried's version of debounce, but the logic is inverted from her
example. In her example, the switch returns LOW when closed, and HIGH when open. Here, the switch
returns HIGH when pressed and LOW when not pressed.
/*
Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's
a minimum delay between toggles to debounce the circuit (i.e. to ignore
noise).
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground
* Note: On most Arduino boards, there is already an LED on the board
connected to pin 13, so you don't need any extra components for this example.
created 21 November 2006
by David A. Mellis
modified 30 Aug 2011
by Limor Fried
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Debounce
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;
// the number of the pushbutton pin
const int ledPin = 13;
// the number of the LED pin
// Variables will change:
int ledState = HIGH;

// the current state of the output pin
int buttonState;
int lastButtonState = LOW;

// the current reading from the input pin
// the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50;
// the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis()
// whatever
// than the
buttonState
}

- lastDebounceTime) > debounceDelay) {
the reading is at, it's been there for longer
debounce delay, so take it as the actual current state:
= reading;

// set the LED using the state of the button:
digitalWrite(ledPin, buttonState);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
}

Button State Change Detection (Edge Detection)

Button State Change Detection (Edge Detection)
Once you've got a pushbutton working, you often want to do some action based on how many times the
button is pushed. To do this, you need to know when the button changes state from off to on, and count
how many times this change of state happens. This is called state change detection or edge
detection.
Hardware Required


Arduino Board



momentary button or switch



10K ohm resistor



breadboard



hook-up wire
Circuit
image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect three wires to the Arduino board. The first goes from one leg of the pushbutton through a pulldown resistor (here 10 KOhms) to ground. The second goes from the corresponding leg of the
pushbutton to the 5 volt supply. The third connects to a digital i/o pin (here pin 2) which reads the
button's state.
When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW.
When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to
voltage, so that we read a HIGH. (The pin is still connected to ground, but the resistor resists the flow of
current, so the path of least resistance is to +5V.)
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the
input is "floating" - that is, not connected to either voltage or ground. It will more or less randomly
return either HIGH or LOW. That's why you need a pull-down resistor in the circuit.
Schematic
click the image to enlarge
The sketch below continually reads the button's state. It then compares the button's state to its state the
last time through the main loop. If the current button state is different from the last button state and the
current button state is high, then the button changed from off to on. The sketch then increments a button
push counter.
The sketch also checks the button push counter's value, and if it's an even multiple of four, it turns the
LED on pin 13 ON. Otherwise, it turns it off.
Code
/*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/ButtonStateChange
*/
// this constant won't change:
const int buttonPin = 2;
// the pin that the pushbutton is attached to
const int ledPin = 13;

// the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

// counter for the number of button presses
// current state of the button
// previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}

Input Pullup Serial

Input Pullup Serial
This example demonstrates the use of INPUT_PULLUP with pinMode(). It monitors the state of a switch
by establishingserial communication between your Arduino and your computer over USB.
Additionally, when the input is HIGH, the onboard LED attached to pin 13 will turn on; when LOW, the
LED will turn off.
Hardware Required


Arduino Board



A momentary switch, button, or toggle switch



breadboard



hook-up wire
Circuit

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

Connect two wires to the Arduino board. The black wire connects ground to one leg of the pushbutton.
The second wire goes from digital pin 2 to the other leg of the pushbutton.
Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is
open (unpressed) there is no connection between the two legs of the pushbutton. Because the internal
pull-up on pin 2 is active and connected to 5V, we read HIGH when the button is open. When the button
is closed, the Arduino reads LOW because a connection to ground is completed.
Schematic
Code
In the program below, the very first thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with the
line:
Serial.begin(9600);

Next, initialize digital pin 2 as an input with the internal pull-up resistor enabled:
pinMode(2,INPUT_PULLUP);

The following line make pin 13, with the onboard LED, an output :
pinMode(13, OUTPUT);

Now that your setup has been completed, move into the main loop of your code. When your button not is
pressed, the internal pull-up resistor connects to 5 volts. This causes the Arduino to report "1" or HIGH.
When the button is pressed, the Arduino pin is pulled to ground, causing the Arduino report a "0", or
LOW.
The first thing you need to do in the main loop of your program is to establish a variable to hold the
information coming in from your switch. Since the information coming in from the switch will be either a
"1" or a "0", you can use anint datatype. Call this variable sensorValue, and set it to equal whatever is being
read on digital pin 2. You can accomplish all this with just one line of code:
int sensorValue = digitalRead(2);

Once the Arduino has read the input, make it print this information back to the computer as a decimal
(DEC) value. You can do this with the command Serial.println() in our last line of code:
Serial.println(sensorValue, DEC);

Now, when you open your Serial Monitor in the Arduino environment, you will see a stream of "0"s if
your switch is closed, or "1"s if your switch is open.
The LED on pin 13 will illuminate when the switch is HIGH, and turn off when LOW.
/*
Input Pullup Serial
This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
digital input on pin 2 and prints the results to the serial monitor.
The circuit:
* Momentary switch attached from pin 2 to ground
* Built-in LED on pin 13
Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to
read HIGH when the switch is open, and LOW when it is closed.
created 14 March 2012
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/InputPullupSerial
This example code is in the public domain
*/
void setup(){
//start serial connection
Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop(){
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal);
// Keep in mind the pullup means the pushbutton's
// logic is inverted. It goes HIGH when it's open,
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
}
else {
digitalWrite(13, HIGH);
}
}

Play a Melody using the tone() function
Play a Melody using the tone() function
This example shows how to use the tone() command to generate notes. It plays a little melody you may
have heard before.
Hardware Required


Arduino board



8 ohm small speaker



100 ohm resistor



hook-up wire
Circuit

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

Connect one terminal of your speaker to digital pin 8 through a 100 ohm resistor. Connect the other
terminal to ground.
Schematic
click the image to enlarge
Code
The code below uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For
example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally
written by Brett Hagman, on whose work the tone() command was based. You may find it useful for
whenever you want to make musical notes.
The main sketch is as follows:
/*
Melody
Plays a melody
circuit:
* 8-ohm speaker on digital pin 8
created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone
*/
#include "pitches.h"
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };
void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}
void loop() {
// no need to repeat the melody.
}
[Get Code]

To make the pitches.h file, click on the "new Tab" button in the upper right hand corner of the window. It
looks like this:
The paste in the following code:
/*************************************************
* Public Constants
*************************************************/
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

NOTE_B0
NOTE_C1
NOTE_CS1
NOTE_D1
NOTE_DS1
NOTE_E1
NOTE_F1
NOTE_FS1
NOTE_G1
NOTE_GS1
NOTE_A1
NOTE_AS1
NOTE_B1
NOTE_C2
NOTE_CS2
NOTE_D2
NOTE_DS2
NOTE_E2
NOTE_F2
NOTE_FS2
NOTE_G2
NOTE_GS2
NOTE_A2
NOTE_AS2
NOTE_B2
NOTE_C3
NOTE_CS3
NOTE_D3
NOTE_DS3
NOTE_E3
NOTE_F3
NOTE_FS3
NOTE_G3
NOTE_GS3
NOTE_A3
NOTE_AS3
NOTE_B3
NOTE_C4
NOTE_CS4
NOTE_D4
NOTE_DS4
NOTE_E4
NOTE_F4
NOTE_FS4
NOTE_G4
NOTE_GS4
NOTE_A4
NOTE_AS4
NOTE_B4
NOTE_C5
NOTE_CS5
NOTE_D5
NOTE_DS5
NOTE_E5

31
33
35
37
39
41
44
46
49
52
55
58
62
65
69
73
78
82
87
93
98
104
110
117
123
131
139
147
156
165
175
185
196
208
220
233
247
262
277
294
311
330
349
370
392
415
440
466
494
523
554
587
622
659
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

NOTE_F5
NOTE_FS5
NOTE_G5
NOTE_GS5
NOTE_A5
NOTE_AS5
NOTE_B5
NOTE_C6
NOTE_CS6
NOTE_D6
NOTE_DS6
NOTE_E6
NOTE_F6
NOTE_FS6
NOTE_G6
NOTE_GS6
NOTE_A6
NOTE_AS6
NOTE_B6
NOTE_C7
NOTE_CS7
NOTE_D7
NOTE_DS7
NOTE_E7
NOTE_F7
NOTE_FS7
NOTE_G7
NOTE_GS7
NOTE_A7
NOTE_AS7
NOTE_B7
NOTE_C8
NOTE_CS8
NOTE_D8
NOTE_DS8

698
740
784
831
880
932
988
1047
1109
1175
1245
1319
1397
1480
1568
1661
1760
1865
1976
2093
2217
2349
2489
2637
2794
2960
3136
3322
3520
3729
3951
4186
4435
4699
4978

Pitch follower using the tone() function
Pitch follower using the tone() function
This example shows how to use the tone() command to generate a pitch that follows the values of an
analog input
Hardware Required


8-ohm speaker



1 photocell



4.7K ohm resistor



100 ohm resistor



breadboard



hook up wire
Circuit
image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect one terminal of your speaker to digital pin 9 through a 100 ohm resistor, and its other terminal
to ground. Power your photoresistor with 5V, and connect it to analog 0 with the addition of a 4.7K
resistor to ground.
Schematic
click the image to enlarge

Code
The code for this example is very simple. Just take an analog input and map its values to a range of
audible pitches. Humans can hear from 20 - 20,000Hz, but 120 - 1500 usually works pretty well for this
sketch.
You'll need to get the actual range of your analog input for the mapping. In the circuit shown, the analog
input value ranged from about 400 to about 1000. Change the values in the map() command to match
the range for your sensor.
The sketch is as follows:
/*
Pitch follower
Plays a pitch that changes based on a changing analog input
circuit:
* 8-ohm speaker on digital pin 8
* photoresistor on analog 0 to 5V
* 4.7K resistor on analog 0 to ground
created 21 Jan 2010
modified 31 May 2012
by Tom Igoe, with suggestion from Michael Flynn
This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone2
*/
void setup() {
// initialize serial communications (for debugging only):
Serial.begin(9600);
}
void loop() {
// read the sensor:
int sensorReading = analogRead(A0);
// print the sensor reading so you know its range
Serial.println(sensorReading);
// map the analog input range (in this case, 400 - 1000 from the photoresistor)
// to the output pitch range (120 - 1500Hz)
// change the minimum and maximum input numbers below
// depending on the range your sensor's giving:
int thisPitch = map(sensorReading, 400, 1000, 120, 1500);
// play the pitch:
tone(9, thisPitch, 10);
delay(1);
// delay in between reads for stability
}

Simple keyboard using the tone() function

Simple keyboard using the tone() function
This example shows how to use the tone() command to generate different pitches depending on which
sensor is pressed.
Hardware Required


8-ohm speaker



(3) force sensing resistors



(3) 10k ohm resistors



(1) 100 ohm resistor



breadboard



hook up wire
Circuit
Connect one terminal of your speaker to digital pin 8 through a 100 ohm resistor, and its other terminal
to ground.
Power your three FSRs (or any other analog sensor) with 5V in parallel. Connect each sensor to analog
pins 0-2, using a 10K resistor as a reference to groud on each input line.
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
The sketch below reads three analog sensors. Each corresponds to a note value in an array of notes. IF
any of the sensors is above a given threshold, the corresponding note is played.
Here's the main sketch:
/*
keyboard
Plays a pitch that changes based on a changing analog input
circuit:
* 3 force-sensing resistors from +5V to analog in 0 through 5
* 3 10K resistors from analog in 0 through 5 to ground
* 8-ohm speaker on digital pin 8
created 21 Jan 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone3
*/
#include "pitches.h"
const int threshold = 10;

// minimum reading of the sensors that generates a note

// notes to play, corresponding to the 3 sensors:
int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };
void setup() {
}
void loop() {
for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
// get a sensor reading:
int sensorReading = analogRead(thisSensor);
// if the sensor is pressed hard enough:
if (sensorReading > threshold) {
// play the note corresponding to this sensor:
tone(8, notes[thisSensor], 20);
}
}
}
[Get Code]

The sketch uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For
example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally
written by Brett Hagman, on whose work the tone() command was based. You may find it useful for
whenever you want to make musical notes.
To make this file, click on the "new Tab" button in the upper right hand corner of the window. It looks
like this:
The paste in the following code:
/*************************************************
* Public Constants
*************************************************/
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

NOTE_B0
NOTE_C1
NOTE_CS1
NOTE_D1
NOTE_DS1
NOTE_E1
NOTE_F1
NOTE_FS1
NOTE_G1
NOTE_GS1
NOTE_A1
NOTE_AS1
NOTE_B1
NOTE_C2
NOTE_CS2
NOTE_D2
NOTE_DS2
NOTE_E2
NOTE_F2
NOTE_FS2
NOTE_G2
NOTE_GS2
NOTE_A2
NOTE_AS2
NOTE_B2
NOTE_C3
NOTE_CS3
NOTE_D3
NOTE_DS3
NOTE_E3
NOTE_F3
NOTE_FS3
NOTE_G3
NOTE_GS3
NOTE_A3
NOTE_AS3
NOTE_B3
NOTE_C4
NOTE_CS4
NOTE_D4
NOTE_DS4
NOTE_E4
NOTE_F4
NOTE_FS4
NOTE_G4
NOTE_GS4
NOTE_A4
NOTE_AS4
NOTE_B4
NOTE_C5
NOTE_CS5

31
33
35
37
39
41
44
46
49
52
55
58
62
65
69
73
78
82
87
93
98
104
110
117
123
131
139
147
156
165
175
185
196
208
220
233
247
262
277
294
311
330
349
370
392
415
440
466
494
523
554
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

NOTE_D5
NOTE_DS5
NOTE_E5
NOTE_F5
NOTE_FS5
NOTE_G5
NOTE_GS5
NOTE_A5
NOTE_AS5
NOTE_B5
NOTE_C6
NOTE_CS6
NOTE_D6
NOTE_DS6
NOTE_E6
NOTE_F6
NOTE_FS6
NOTE_G6
NOTE_GS6
NOTE_A6
NOTE_AS6
NOTE_B6
NOTE_C7
NOTE_CS7
NOTE_D7
NOTE_DS7
NOTE_E7
NOTE_F7
NOTE_FS7
NOTE_G7
NOTE_GS7
NOTE_A7
NOTE_AS7
NOTE_B7
NOTE_C8
NOTE_CS8
NOTE_D8
NOTE_DS8

587
622
659
698
740
784
831
880
932
988
1047
1109
1175
1245
1319
1397
1480
1568
1661
1760
1865
1976
2093
2217
2349
2489
2637
2794
2960
3136
3322
3520
3729
3951
4186
4435
4699
4978

SPlaying tones on Multiple outputs using the tone() function

SPlay ing tones on Multiple outputs using the tone() function
This example shows how to use the tone() command to play different notes on multiple outputs.
The tone() command works by taking over one of the Atmega's internal timers, setting it to the frequency
you want, and using the timer to pulse an output pin. Since it's only using one timer, you can only play
one note at a time. You can, however, play notes on multiple pins sequentially. To do this, you need to
turn the timer off for one pin before moving on to the next.
Thanks to Greg Borenstein for clarifying this.
Hardware Required


(3) 8-ohm speakers



(3) 100 ohm resistor



breadboard



hook up wire
Circuit

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

Schematic
click the image to enlarge

Code
The sketch below plays a tone on each of the speakers in sequence, turning off the previous speaker first.
Note that the duration of each tone is the same as the delay that follows it.
Here's the main sketch:
/*
Multiple tone player
Plays multiple tones on multiple pins in sequence
circuit:
* 3 8-ohm speaker on digital pins 6, 7, and 11
created 8 March 2010
by Tom Igoe
based on a snippet from Greg Borenstein
This example code is in the public domain.
http://arduino.cc/en/Tutorial/Tone4
*/
void setup() {
}
void loop() {
// turn off tone function for pin 11:
noTone(11);
// play a note on pin 6 for 200 ms:
tone(6, 440, 200);
delay(200);
// turn off tone function for pin 6:
noTone(6);
// play a note on pin 7 for 500 ms:
tone(7, 494, 500);
delay(500);
// turn off tone function for pin 7:
noTone(7);
// play a note on pin 11 for 500 ms:
tone(11, 523, 300);
delay(300);
}

3.Analog

Analog In, Out Serial

Analog In, Out Serial
This example shows how to read an analog input pin, map the result to a range from 0 to 255, and then
use that result to set the pulsewidth modulation (PWM) of an output pin to dim or brighten an LED.
Hardware Required


Arduino Board



Potentiometer



LED



220 ohm resistor
Circuit
image developed using Fritzing. For more circuit examples, see the Fritzing project page

Connect one pin from your pot to 5V, the center pin to analog pin 0, and the remaining pin to ground.
Next, connect a 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.
Schematic

Code
In the program below, after declaring two pin assignments (analog 0 for your potentiometer and digital 9
for your LED) and two variables, sensorValue and outputValue, the only thing that you do will in the setup
function is to begin serial communication.
Next, in the main loop of the code, sensorValue is assigned to store the raw analog value coming in from
the potentiometer. Because the Arduino has an analogRead resolution of 0-1023, and
an analogWrite resolution of only 0-255, this raw data from the potentiometer needs to be scaled before
using it to dim the LED.
In order to scale this value, use a function called map()
outputValue = map(sensorValue, 0, 1023, 0, 255);
[Get Code]
outputValue

is assigned to equal the scaled value from the potentiometer. map() accepts five arguments:

The value to be mapped, the low range and high range of the raw data, and the low and high values for
that data to be scaled too. In this case, the sensor data is mapped down from its original range of 0 to
1023 to 0 to 255.
The newly mapped sensor data is then output to the analogOutPin dimming or brightening the LED as the
potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino serial
window in a steady stream of data.
/*
Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255
and uses the result to set the pulsewidth modulation (PWM) of an output pin.
Also prints the results to the serial monitor.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground
created 29 Dec. 2008
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to
int sensorValue = 0;
int outputValue = 0;

// value read from the pot
// value output to the PWM (analog out)

void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("t output = ");
Serial.println(outputValue);
// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
}
Analog Input

Analog Input
A potentiometer is a simple knob that provides a variable resistance, which you can read into the
Arduino board as an analog value. In this example, you'll connect a poterntiometer to one of the
Arduino's analog inputs to control the rate at which the built-in LED on pin 13 blinks.
Hardware Required


Arduino Board



Potentiometer



built-in LED on pin 13
Circuit
click the image to enlarge

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

Connect three wires to the Arduino board. The first goes to ground from one of the outer pins of the
potentiometer. The second goes from 5 volts to the other outer pin of the potentiometer. The third goes
from analog input 0 to the middle pin of the potentiometer.
For this example, it is possible to use the Arduino board's built in LED attached to pin 13. To use an
additional LED, attach its longer leg (the positive leg, or anode), to digital pin 13, and it's shorter leg (the
negative leg, or cathode) to the ground (gnd) pin next to pin 13. Because of the low amount of current
coming from digital pin 13, it is not necessary to use a current limiting resistor in this particular case.
Schematic
click the image to enlarge

Code
In the beginning of this program, the variable sensorPin is set to to analog pin 0, where your
potentiometer is attached, and ledPin is set to digital pin 13. You'll also create another
variable, sensorValue i to store the values read from your sensor.
The analogRead() command converts the input voltage range, 0 to 5 volts, to a digital value between 0 and
1023. This is done by a circuit inside the Arduino called an analog-to-digital converter or ADC.
By turning the shaft of the potentiometer, you change the amount of resistance on either side of the
center pin (or wiper) of the potentiometer. This changes the relative resistances between the center pin
and the two outside pins, giving you a different voltage at the analog input. When the shaft is turned all
the way in one direction, there is no resistance between the center pin and the pin connected to ground.
The voltage at the center pin then is 0 volts, and analogRead() returns 0. When the shaft is turned all the
way in the other direction, there is no resistance between the center pin and the pin connected to +5
volts. The voltage at the center pin then is 5 volts, and analogRead() returns 1023. In
between,analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage
being applied to the pin.
That value, stored in sensorValue, is used to set a delay() for your blink cycle. The higher the value, the
longer the cycle, the smaller the value, the shorter the cycle.
/*
Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on
the value obtained by analogRead().
The circuit:
* Potentiometer attached to analog input 0
* center pin of the potentiometer to the analog pin
* one side pin (either one) to ground
* the other side pin to +5V
* LED anode (long leg) attached to digital output 13
* LED cathode (short leg) attached to ground
* Note: because most Arduinos have a built-in LED attached
to pin 13 on the board, the LED is optional.
Created by David Cuartielles
modified 30 Aug 2011
By Tom Igoe
This example code is in the public domain.
http://arduino.cc/en/Tutorial/AnalogInput
*/
int sensorPin = A0;
int ledPin = 13;
int sensorValue = 0;

// select the input pin for the potentiometer
// select the pin for the LED
// variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}

Analog Write with 12 LEDs on an Arduino Mega

Analog Write with 12 LEDs on an Arduino Mega
This example fades 12 LEDs up and the down, one by one, on an Arduino Mega board.
Hardware Required


Arduino Mega Board



(12) LEDs



(12) 220 ohm resistors



hook up wire



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

Connect the longer, positive legs of (anodes) 12 LEDs to digital pins 2-13 through 220 ohm current
limiting resistors. Connect the shorter, negative legs (cathodes) to ground.
Schematic
Code
In the setup() function of the code below, a for() loop is used to assign digital pins 2-13 of the Mega as
outputs.
Next, in the loop() function of the program below, a trio of nested for() loops are used.
The first of these loops,
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++)
[Get Code]

moves through each of the LEDS one by one, from the lowest pin to the highest. Before this loop is
allowed to move from one pin to the next, two things must be accomplished. First, you brighten the
individual LED through these lines of code:
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness);
delay(2);
}
[Get Code]

With each pass through the loop above, the variable brightness increases by one point, and that value is
written to the pin currently selected to the main loop. One that pin reaches the maximum PWM value
(255), the following loop kicks in:
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness);
delay(2);
}
[Get Code]

This loop subtracts a point from the brightness variable, dimming the LED back down to 0. Once zero is
reached, the mainfor() loop kicks in, and the program moves on to the next LED pin, repeating all the
steps mentioned above.
/*
Mega analogWrite() test
This sketch fades LEDs up and down one at a time on digital pins 2 through 13.
This sketch was written for the Arduino Mega, and will not work on previous boards.
The circuit:
* LEDs attached from pins 2 through 13 to ground.
created 8 Feb 2009
by Tom Igoe
This example code is in the public domain.
*/
// These constants won't change.
// to the pins used:
const int lowestPin = 2;
const int highestPin = 13;

They're used to give names

void setup() {
// set pins 2 through 13 as outputs:
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) {
pinMode(thisPin, OUTPUT);
}
}
void loop() {
// iterate over the pins:
for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) {
// fade the LED on thisPin from off to brightest:
for (int brightness = 0; brightness < 255; brightness++) {
analogWrite(thisPin, brightness);
delay(2);
}
// fade the LED on thisPin from brithstest to off:
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(thisPin, brightness);
delay(2);
}
// pause between LEDs:
delay(100);
}
}

Calibration

Calibration
This example demonstrates one techinque for calibrating sensor input. The Arduino takes sensor
readings for five seconds during the startup, and tracks the highest and lowest values it gets. These
sensor readings during the first five seconds of the sketch execution define the minimum and maximum
of expected values for the readings taken during the loop.
Hardware Required


Arduino board



(1) LED



(1) analog sensor (a photocell will do)



(1) 10K ohm resistor



(1) 220 ohm resistor



breadboard



hook-up wire
Circuit
Analog sensor (e.g. potentiometer, light sensor) on analog input 2. LED on digital pin 9.
click the image to enlarge

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

Connect an LED to digital pin 9 with a 220 ohm current limiting resistor. Connect a photocell to 5V and
then to analog pin 0 with a 10K ohm resistor as a reference to ground.
Schematic
click the image to enlarge
Code
Before the setup, you set initial values for the minimum and maximum like so:
int sensorMin = 1023;
int sensorMax = 0;

// minimum sensor value
// maximum sensor value
[Get Code]

These may seem backwards. Initially, you set the minimum high and read for anything lower than that,
saving it as the new minimum. Likewise, you set the maximum low and read for anything higher as the
new maximum, like so:
// calibrate during the first five seconds
while (millis() < 5000) {
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
[Get Code]

This way, any further readings you take can be mapped to the range between this minimum and
maximum like so:
// apply the calibration to the sensor reading
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
[Get Code]

Here's the whole program:
/*
Calibration
Demonstrates one technique for calibrating sensor input. The
sensor readings during the first five seconds of the sketch
execution define the minimum and maximum of expected values
attached to the sensor pin.
The sensor minimum and maximum initial values may seem backwards.
Initially, you set the minimum high and listen for anything
lower, saving it as the new minimum. Likewise, you set the
maximum low and listen for anything higher as the new maximum.
The circuit:
* Analog sensor (potentiometer will do) attached to analog input 0
* LED attached from digital pin 9 to ground
created 29 Oct 2008
By David A Mellis
modified 30 Aug 2011
By Tom Igoe
http://arduino.cc/en/Tutorial/Calibration
This example code is in the public domain.
*/
// These constants won't change:
const int sensorPin = A0;
// pin that the sensor is attached to
const int ledPin = 9;
// pin that the LED is attached to
// variables:
int sensorValue = 0;
int sensorMin = 1023;
int sensorMax = 0;

// the sensor value
// minimum sensor value
// maximum sensor value

void setup() {
// turn on LED to signal the start of the calibration period:
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// calibrate during the first five seconds
while (millis() < 5000) {
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
// signal the end of the calibration period
digitalWrite(13, LOW);
}
void loop() {
// read the sensor:
sensorValue = analogRead(sensorPin);
// apply the calibration to the sensor reading
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
// in case the sensor value is outside the range seen during calibration
sensorValue = constrain(sensorValue, 0, 255);
// fade the LED using the calibrated value:
analogWrite(ledPin, sensorValue);
}
Fading

Fading
Demonstrates the use of analog output (Pulse Width Modulation (PWM)) to fade an LED. PWM is a
technique for getting an analog-like behavior from a digital output by switching it off and on very fast.
Circuit
An LED connected to digital output pin 9 through a 220-ohm resistor.
click the image to enlarge

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

Code
/*
Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
* LED attached from digital pin 9 to ground.
Created 1 Nov 2008
By David A. Mellis
modified 30 Aug 2011
By Tom Igoe
http://arduino.cc/en/Tutorial/Fading
This example code is in the public domain.
*/
int ledPin = 9;

// LED connected to digital pin 9

void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}

Smoothing

Smoothing
This sketch reads repeatedly from an analog input, calculating a running average and printing it to the
computer. This example is useful for smoothing out the values from jumpy or erratic sensors, and also
demonstrates the use of arrays to store data.
Hardware


Arduino Board



Potentiometer
Circuit
click the image to enlarge

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

Connect one pin of a potentiometer to 5V, the center pin to analog pin 0, and the the last pin to ground.
Schematic
click the image to enlarge
Code
The code below sequentially stores 10 readings from your analog sensor into an arrays, one by one. With
each new value, the sum of all the numbers is generated and divided, producing an average value which
then be used to smooth outlying data. Because this averaging takes place each time a new value is added
to the array (rather then waiting for 10 new values, for instance) there is no lag time in calculating this
running average.
Altering the size of the array used, by changing numReadings to a larger value will smooth the data collected
even further.
/*
Smoothing
Reads repeatedly from an analog input, calculating a running average
and printing it to the computer. Keeps ten readings in an array and
continually averages them.
The circuit:
* Analog sensor (potentiometer will do) attached to analog input 0
Created 22 April 2007
By David A. Mellis <dam@mellis.org>
modified 9 Apr 2012
by Tom Igoe
http://www.arduino.cc/en/Tutorial/Smoothing
This example code is in the public domain.
*/
// Define the number of samples to keep track of. The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input. Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
const int numReadings = 10;
int readings[numReadings];

// the readings from the analog input
int index = 0;
int total = 0;
int average = 0;

// the index of the current reading
// the running total
// the average

int inputPin = A0;
void setup()
{
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}
void loop() {
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(inputPin);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
Serial.println(average);
delay(1);
// delay in between reads for stability
}

4.Communication

Read ASCII String

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), but other characters like a space or a period will work too.
The values are parsed into ints and used to determine the color of a RGB LED. You'll use the serial
monitor to send strings like "5,220,70" to the Arduino to change the lights.
Hardware Required


Arduino Board



Breadboard



Hookup wire



Common anode RGB LED



Three 220-ohm resistors
Circuit

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

You'll need five wires to make the circuit above. Connect a red wire to one of the long vertical rows on
your breadboard. Connect the other end to the 5V pin on your Arduino.
Place an RGB LED on your breadboard. Check the datasheet for your specific LED to verify the pins.
Connect the power rail you just created to the common anode on the LED.
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 Arduino 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 Arduino 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. UsingSerial.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 Arduino:
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 Arduino, open your Serial minitor. 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 Arduino, the attached LED will turn the
color you specified, and you will receive 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-anode RGB LED wired like so:
* Red cathode: digital pin 3
* Green cathode: digital pin 5
* blue cathode: digital pin 6
* anode: +5V
created 13 Apr 2012
by Tom Igoe
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);
}
}
}

ASCII Table

ASCII Table
Demonstrates the advanced serial printing functions by generating a table of characters and their ASCII
values in decimal, hexadecimal, octal, and binary. For more on ASCII, see asciitable.com
Hardware Required


Arduino Board
Circuit

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

None, but the Arduino has to be connected to the computer.
Code
/*
ASCII table
Prints out byte values in all possible formats:
* as raw binary values
* as ASCII-encoded decimal, hex, octal, and binary values
For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII
The circuit:

No external hardware needed.

created 2006
by Nicholas Zambetti
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
<http://www.zambetti.com>
*/
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// prints title with ending line break
Serial.println("ASCII Table ~ Character Map");
}
// first visible ASCIIcharacter '!' is number 33:
int thisByte = 33;
// you can also write ASCII characters in single quotes.
// for example. '!' is the same as 33, so you could also use this:
//int thisByte = '!';
void loop() {
// prints value unaltered, i.e. the raw binary version of the
// byte. The serial monitor interprets all bytes as
// ASCII, so 33, the first number, will show up as '!'
Serial.write(thisByte);
Serial.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed:
Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to.
//this also works if you uncomment it:
// Serial.print(thisByte, DEC);
Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
// prints value as string in octal (base 8);
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
// prints value as string in binary (base 2)
// also prints ending line break:
Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop:
if(thisByte == 126) {
// you could also use if (thisByte == '~') {
// This loop loops forever and does nothing
while(true) {
continue;
}
}
// go on to the next character
thisByte++;
}
[Get Code]

Output
ASCII Table ~ Character Map
!, dec: 33, hex: 21, oct: 41, bin
4, decúASCII Table ~ Character Map
!, dec: 33, hex: 21, oct: 41, bin: 100001
", dec: 34, hex: 22, oct: 42, bin: 100010
#, dec: 35, hex: 23, oct: 43, bin: 100011
$, dec: 36, hex: 24, oct: 44, bin: 100100
%, dec: 37, hex: 25, oct: 45, bin: 100101
&, dec: 38, hex: 26, oct: 46, bin: 100110
', dec: 39, hex: 27, oct: 47, bin: 100111
(, dec: 40, hex: 28, oct: 50, bin: 101000
), dec: 41, hex: 29, oct: 51, bin: 101001
*, dec: 42, hex: 2A, oct: 52, bin: 101010
+, dec: 43, hex: 2B, oct: 53, bin: 101011
,, dec: 44, hex: 2C, oct: 54, bin: 101100
-, dec: 45, hex: 2D, oct: 55, bin: 101101
., dec: 46, hex: 2E, oct: 56, bin: 101110
/, dec: 47, hex: 2F, oct: 57, bin: 101111
0, dec: 48, hex: 30, oct: 60, bin: 110000
1, dec: 49, hex: 31, oct: 61, bin: 110001
2, dec: 50, hex: 32, oct: 62, bin: 110010
3, dec: 51, hex: 33, oct: 63, bin: 110011
4, dec: 52, hex: 34, oct: 64, bin: 110100
5, dec: 53, hex: 35, oct: 65, bin: 110101
6, dec: 54, hex: 36, oct: 66, bin: 110110
7, dec: 55, hex: 37, oct: 67, bin: 110111
8, dec: 56, hex: 38, oct: 70, bin: 111000
9, dec: 57, hex: 39, oct: 71, bin: 111001
:, dec: 58, hex: 3A, oct: 72, bin: 111010
;, dec: 59, hex: 3B, oct: 73, bin: 111011
<, dec: 60, hex: 3C, oct: 74, bin: 111100
=, dec: 61, hex: 3D, oct: 75, bin: 111101
>, dec: 62, hex: 3E, oct: 76, bin: 111110
?, dec: 63, hex: 3F, oct: 77, bin: 111111
@, dec: 64, hex: 40, oct: 100, bin: 1000000
A, dec: 65, hex: 41, oct: 101, bin: 1000001
B, dec: 66, hex: 42, oct: 102, bin: 1000010
C, dec: 67, hex: 43, oct: 103, bin: 1000011
D, dec: 68, hex: 44, oct: 104, bin: 1000100
E, dec: 69, hex: 45, oct: 105, bin: 1000101
...
Dimmer

Dimmer
This example shows how to send data from a personal computer to an Arduino 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.
Arduino reads these bytes and uses them to set the brightness of the LED.
You can send bytes to the Arduino from any software that can access the computer serial port. Examples
for Processingand Max/MSP version 5 are shown below.
Hardware Required


Arduino Board



LED



220 ohm resistor
Software Required



Processing or



Max/MSP version 5
Circuit
An LED connected to pin 9. Use an appropriate resistor as needed. For most common LEDs, you can
usually do without the resistor, as the current output of the digital I/O pins is limited.
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 the 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:");
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);
}
*/
/* Max/MSP v5 patch for this example
----------begin_max5_patcher---------1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M
YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC
ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP
xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK
rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W
sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui
FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv
AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK
z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu
xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2
uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj
jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA
4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr
TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS
xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6
WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9
FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7
3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc
cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ
+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x
D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8
ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS
xqZqbd3ZLdera1iPqYxOm++v7SUSz
-----------end_max5_patcher----------*/
[Get Code]

Processing Code
The Processing sketch in the code sample above will send bytes out the serial port to the Arduino to dim
the LED.
Max code
The Max/MSP patch in the code sample above looks like the image below. Copy it and paste it into a new
patch window.
Graph

Graph
This example shows you how to send a byte of data from the Arduino to a personal computer and graph
the result. This is called 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.
You can use the Arduino serial monitor to view the sent data, or it can be read by Processing (see code
below), Flash, PD, Max/MSP, etc.
Hardware Required


Arduino 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 is 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
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino
What is arduino

Contenu connexe

Tendances

Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduinoyeokm1
 
Oop 2014 embedded systems with open source hardware v2
Oop 2014 embedded systems with open source hardware v2Oop 2014 embedded systems with open source hardware v2
Oop 2014 embedded systems with open source hardware v2Michael Stal
 
Programming with arduino
Programming with arduinoProgramming with arduino
Programming with arduinoMakers of India
 
Intro to Hardware Programming with the Arduino Uno
Intro to Hardware Programming with the Arduino UnoIntro to Hardware Programming with the Arduino Uno
Intro to Hardware Programming with the Arduino UnoVui Nguyen
 
Arduino e-Course Syllabus for Beginners
Arduino e-Course Syllabus for BeginnersArduino e-Course Syllabus for Beginners
Arduino e-Course Syllabus for BeginnersMadhu Honey
 
Arduino slides
Arduino slidesArduino slides
Arduino slidessdcharle
 
Introducing the Arduino
Introducing the ArduinoIntroducing the Arduino
Introducing the ArduinoCharles A B Jr
 
FinalThesisdraft
FinalThesisdraftFinalThesisdraft
FinalThesisdraftSyed Kazmi
 
Hello Arduino.
Hello Arduino.Hello Arduino.
Hello Arduino.mkontopo
 
All about ir arduino - cool
All about ir   arduino - coolAll about ir   arduino - cool
All about ir arduino - coolVlada Stoja
 
Microcontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware IntroductionMicrocontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware IntroductionJoseph Sanchez
 
Arduino training day 1
Arduino training day 1Arduino training day 1
Arduino training day 1Binod Thapa
 

Tendances (20)

Arduino course
Arduino courseArduino course
Arduino course
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Ardui no
Ardui no Ardui no
Ardui no
 
Arduino basics
Arduino basicsArduino basics
Arduino basics
 
Oop 2014 embedded systems with open source hardware v2
Oop 2014 embedded systems with open source hardware v2Oop 2014 embedded systems with open source hardware v2
Oop 2014 embedded systems with open source hardware v2
 
Programming with arduino
Programming with arduinoProgramming with arduino
Programming with arduino
 
Arduino
ArduinoArduino
Arduino
 
Introduction to arduino
Introduction to arduinoIntroduction to arduino
Introduction to arduino
 
Intro to Hardware Programming with the Arduino Uno
Intro to Hardware Programming with the Arduino UnoIntro to Hardware Programming with the Arduino Uno
Intro to Hardware Programming with the Arduino Uno
 
Arduino tutorial
Arduino tutorialArduino tutorial
Arduino tutorial
 
Arduino e-Course Syllabus for Beginners
Arduino e-Course Syllabus for BeginnersArduino e-Course Syllabus for Beginners
Arduino e-Course Syllabus for Beginners
 
Arduino slides
Arduino slidesArduino slides
Arduino slides
 
Introducing the Arduino
Introducing the ArduinoIntroducing the Arduino
Introducing the Arduino
 
FinalThesisdraft
FinalThesisdraftFinalThesisdraft
FinalThesisdraft
 
Arduino uno
Arduino unoArduino uno
Arduino uno
 
Hello Arduino.
Hello Arduino.Hello Arduino.
Hello Arduino.
 
All about ir arduino - cool
All about ir   arduino - coolAll about ir   arduino - cool
All about ir arduino - cool
 
Microcontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware IntroductionMicrocontroller Programming & Hardware Introduction
Microcontroller Programming & Hardware Introduction
 
Indroduction the arduino
Indroduction the arduinoIndroduction the arduino
Indroduction the arduino
 
Arduino training day 1
Arduino training day 1Arduino training day 1
Arduino training day 1
 

Similaire à What is arduino

Arduino and Circuits.docx
Arduino and Circuits.docxArduino and Circuits.docx
Arduino and Circuits.docxAjay578679
 
Arduino - Learning.pdf
Arduino - Learning.pdfArduino - Learning.pdf
Arduino - Learning.pdfKhalilSedki1
 
NSTA 2013 Denver - ArduBlock and Arduino
NSTA 2013 Denver - ArduBlock and ArduinoNSTA 2013 Denver - ArduBlock and Arduino
NSTA 2013 Denver - ArduBlock and ArduinoBrian Huang
 
Interface stepper motor through Arduino using LABVIEW.
Interface stepper motor through Arduino using LABVIEW.Interface stepper motor through Arduino using LABVIEW.
Interface stepper motor through Arduino using LABVIEW.Ankita Tiwari
 
Arduino by yogesh t s'
Arduino by yogesh t s'Arduino by yogesh t s'
Arduino by yogesh t s'tsyogesh46
 
Microcontroller arduino uno board
Microcontroller arduino uno boardMicrocontroller arduino uno board
Microcontroller arduino uno boardGaurav
 
Arduino Slides With Neopixels
Arduino Slides With NeopixelsArduino Slides With Neopixels
Arduino Slides With Neopixelssdcharle
 
Arduino اردوينو
Arduino اردوينوArduino اردوينو
Arduino اردوينوsalih mahmod
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptxAkshat Bijronia
 
Introduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and ProgrammingIntroduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and ProgrammingEmmanuel Obot
 
1.Arduino Ecosystem.pptx
1.Arduino Ecosystem.pptx1.Arduino Ecosystem.pptx
1.Arduino Ecosystem.pptxMohamed Essam
 

Similaire à What is arduino (20)

Arduino and Circuits.docx
Arduino and Circuits.docxArduino and Circuits.docx
Arduino and Circuits.docx
 
Arduino - Learning.pdf
Arduino - Learning.pdfArduino - Learning.pdf
Arduino - Learning.pdf
 
Arduino
Arduino Arduino
Arduino
 
Introduction of Arduino Uno
Introduction of Arduino UnoIntroduction of Arduino Uno
Introduction of Arduino Uno
 
Arduino: Arduino starter kit
Arduino: Arduino starter kitArduino: Arduino starter kit
Arduino: Arduino starter kit
 
Arduino
ArduinoArduino
Arduino
 
NSTA 2013 Denver - ArduBlock and Arduino
NSTA 2013 Denver - ArduBlock and ArduinoNSTA 2013 Denver - ArduBlock and Arduino
NSTA 2013 Denver - ArduBlock and Arduino
 
Interface stepper motor through Arduino using LABVIEW.
Interface stepper motor through Arduino using LABVIEW.Interface stepper motor through Arduino using LABVIEW.
Interface stepper motor through Arduino using LABVIEW.
 
Arduino by yogesh t s'
Arduino by yogesh t s'Arduino by yogesh t s'
Arduino by yogesh t s'
 
Microcontroller arduino uno board
Microcontroller arduino uno boardMicrocontroller arduino uno board
Microcontroller arduino uno board
 
Arduino Slides With Neopixels
Arduino Slides With NeopixelsArduino Slides With Neopixels
Arduino Slides With Neopixels
 
What is Arduino ?
What is Arduino ?What is Arduino ?
What is Arduino ?
 
Arduino اردوينو
Arduino اردوينوArduino اردوينو
Arduino اردوينو
 
Aurdino presentation
Aurdino presentationAurdino presentation
Aurdino presentation
 
Report on arduino
Report on arduinoReport on arduino
Report on arduino
 
ARDUINO Presentation1.pptx
ARDUINO Presentation1.pptxARDUINO Presentation1.pptx
ARDUINO Presentation1.pptx
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptx
 
Introduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and ProgrammingIntroduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and Programming
 
Indroduction arduino
Indroduction arduinoIndroduction arduino
Indroduction arduino
 
1.Arduino Ecosystem.pptx
1.Arduino Ecosystem.pptx1.Arduino Ecosystem.pptx
1.Arduino Ecosystem.pptx
 

Dernier

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Dernier (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

What is arduino

  • 1. What is Arduino? Arduino is a tool for making computers that can sense and control more of the physical world than your desktop computer. It's an open-source physical computing platform based on a simple microcontroller board, and a development environment for writing software for the board. Arduino can be used to develop interactive objects, taking inputs from a variety of switches or sensors, and controlling a variety of lights, motors, and other physical outputs. Arduino projects can be standalone, or they can be communicate with software running on your computer (e.g. Flash, Processing, MaxMSP.) The boards can be assembled by hand or purchased preassembled; the opensource IDE can be downloaded for free. The Arduino programming language is an implementation of Wiring, a similar physical computing platform, which is based on the Processing multimedia programming environment. Why Arduino? There are many other microcontrollers and microcontroller platforms available for physical computing. Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard, and many others offer similar functionality. All of these tools take the messy details of microcontroller programming and wrap it up in an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it offers some advantage for teachers, students, and interested amateurs over other systems:  Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the preassembled Arduino modules cost less than $50  Cross-platform - The Arduino software runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows.  Simple, clear programming environment - The Arduino programming environment is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it's conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with the look and feel of Arduino  Open source and extensible software- The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it's based. SImilarly, you can add AVR-C code directly into your Arduino programs if you want to.  Open source and extensible hardware - The Arduino is based on Atmel's ATMEGA8 and ATMEGA168microcontrollers. The plans for the modules are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it. Even relatively inexperienced users can build the breadboard version of the module in order to understand how it works and save money.
  • 2. Examples See the foundations page for in-depth description of core concepts of the Arduino hardware and software; thehacking page for information on extending and modifying the Arduino hardware and software; and the links pagefor other documentation. Note: these examples are written for Arduino 1.0 and later. Certain functions may not work in earlier versions. For best results, download the latest version. Here's a style guide that helps with writing examples for beginners. Core F unctions Libraries Simple programs that demonstrate basic Examples from the libraries that are included in Arduino commands. These are included with the the Arduino software. Arduino environment; to open them, click the EEPROM Library Open button on the toolbar and look in the examples folder. 1.Basics  BareMinimum: The bare minimum of code  EEPROM Clear: clear the bytes in the EEPROM.  EEPROM Read: read the EEPROM and send its values to the computer.  needed to start an Arduino sketch.  input to the EEPROM. Blink: Turn an LED on and off.  EEPROM Write: stores values from an analog DigitalReadSerial: Read a switch, print the state Ethernet Library out to the Arduino Serial Monitor.  ChatServer: set up a simple chat server. AnalogReadSerial: Read a potentiometer, print  WebClient: make a HTTP request. it's state out to the Arduino Serial Monitor.    WebClientRepeating: Make repeated HTTP Fade: Demonstrates the use of analog output to fade an LED.  requests.  ReadAnalogVoltage : Reads an analog input and prints the voltage to the serial monitor displays analog sensor values.   PachubeClientString: send strings to pachube.com. Blink Without Delay: blinking an LED without using the delay() function. PachubeClient: connect to pachube.com, a free datalogging site. 2.Digital  WebServer: host a simple HTML page that  BarometricPressureWebServer: outputs the  Button: use a pushbutton to control an LED. values from a barometric pressure sensor as a  Debounce: read a pushbutton, filtering noise. web page.  Button State Change: counting the number of  button pushes.  Input Pullup Serial: Demonstrates the use of strings via UDP.  INPUT_PULLUP with pinMode().  Tone: play a melody with a Piezo speaker.  UDPSendReceiveString: Send and receive text UdpNtpClient: Query a Network Time Protocol (NTP) server using UDP. Pitch follower: play a pitch on a piezo speaker  DnsWebClient: DNS and DHCP-based Web client. depending on an analog input.   DhcpChatServer: A simple DHCP Chat Server Simple Keyboard: a three-key musical keyboard  DhcpAddressPrinter: Get an IP address via using force sensors and a piezo speaker.  DHCP and print it out Tone4: play tones on multiple speakers  TwitterClient: A Twitter client with Strings sequentially using the tone() command.  TelnetClient: A simple Telnet client 3.Analog Firmata Libraries
  • 3.  AnalogInOutSerial: read an analog input pin,  map the result, and then use that data to dim or Liq uidCrystal Library brighten an LED.  Analog Input: use a potentiometer to control the Guide to the Standard Firmata Library  blinking of an LED. Hello World: displays "hello world!" and the seconds since reset.  AnalogWriteMega: fade 12 LEDs on and off, one  Blink: control of the block-style cursor. by one, using an Arduino Mega board.   Cursor: control of the underscore-style cursor. Calibration: define a maximum and minimum  Display: quickly blank the display without losing for expected analog sensor values.  Fading: use an analog output (PWM pin) to fade what's on it.  an LED. TextDirection: control which way text flows from the cursor. Smoothing: smooth multiple readings of an  Scroll: scroll text left and right. analog input.   Serial input: accepts serial input, displays it.  SetCursor: set the cursor position.  Autoscroll: shift text right and left. 4.Communication These examples include code that allows the Arduino to talk to Processing sketches running SPI Library on the computer. For more information or to download Processing, seeprocessing.org. There  BarometricPressureSensor: read air pressure are also Max/MSP patches that can and temperature from a sensor using the SPI communicate with each Arduino sketch as well. protocol. For more on Max/MSP see Cycling 74. For Pd  potentiometer using the SPI protocol. patches that can communicate with these sketches, see Scott Fitzgerald's examples.  ReadASCIIString: parse a comma-separated string of ints to fade an LED  ASCII Table: demonstrates Arduino's advanced serial output functions.  Servo Library    Software Serial Library Graph: send data to the computer and graph it  one serial port just isn't enough! data to your Arduino from Processing or  Software Serial Example: how to use theSoftwareSerial Library...Because sometimes Physical Pixel: turn a LED on and off by sending Max/MSP. Sweep: sweeps the shaft of a servo motor back and forth. Dimmer: move the mouse to change the in Processing. Knob: control the shaft of a servo motor by turning a potentiometer. brightness of an LED.  SPIDigitalPot: control a AD5206 digital  Two Port Receive: how to work with multiple software serial ports. Virtual Color Mixer: send multiple variables from Arduino to your computer and read them Stepper Library in Processing or Max/MSP.  Serial Call Response: send multiple vairables  motor using a potentiometer. using a call-and-response (handshaking) method.  Wire Library Serial Call Response ASCII: send multiple variables using a call-and-response Motor Knob: control a highly accurate stepper  SFRRanger_reader: read a (handshaking) method, and ASCII-encode the Devantech SRFxx ultra-sonic range finder values before sending. using I2C communication.
  • 4.  SerialEvent: Demonstrates the use  of SerialEvent().  Serial input (Switch (case) Statement): how to digital_potentiometer: control a AD5171 digital pot using the Wire Library.  master reader/slave sender: set up two (or take different actions based on characters more) arduino boards to share information via a received by the serial port. master reader/slave sender configuration.  MIDI: send MIDI note messages serially.  MultiSerialMega: use two of the serial ports arduino boards to share information using a available on the Arduino Mega. master writer/slave reader set up. 5.Control Structures WiFi Library   The WiFi Library will be included in a future If Statement (Conditional): how to use an if release of the Arduino IDE. You can download statement to change output conditions based on the most recent version, and install it as you changing input conditions.    Array: a variation on the For Loop example that demonstrates how to use an array.  would any other library. For Loop: controlling multiple LEDs with a for loop and. ConnectNoEncryption : Demonstrates how to connect to an open network  While Loop: how to use a while loop to calibrate a sensor while a button is being read. master writer/slave reader: allow two (or more) ConnectWithWEP : Demonstrates how to connect to a network that is encrypted with WEP  ConnectWithWPA : Demonstrates how to Switch Case: how to choose between a discrete connect to a network that is encrypted number of values. Equivalent to multiple If  with WPA2 Personal statements. This example shows how to divide a  sensor's range into a set of four bands and to ScanNetworks : Displays all WiFi networks in range take four different actions depending on which WiFiChatServer : Set up a simple chat server band the result is in.    WiFiPachubeClient : connect to pachube.com, a Switch Case 2: a second switch-case example, showing how to take different actions based in free datalogging site  characters received in the serial port. 6.Sensors  ADXL3xx: read an ADXL3xx accelerometer.  Memsic2125 : two-axis acceleromoter.  Ping: detecting objects with an ultrasonic range pachube.com  WiFiTwitterClient : A Twitter client with Strings  WiFiWebClient : Connect to a remote webserver  WiFiWebClientRepeating: Repeatedly make Knock: detect knocks with a piezo element.  finder. WiFiPachubeClientString: send strings to HTTP calls to a server  WiFiWebServer : Serve a webpage from the WiFishield Arduino as ISP Programmer 7.Display ArduinoISP turns your Arduino into an in- Examples of basic display control circuit programmer to re-program Atmega  LED Bar Graph: how to make an LED bar graph.  Row Column Scanning: how to control an 8x8 matrix of LEDs. 8.Strings  StringAdditionOperator: add strings together in a variety of ways. chips. Useful when you need to re-load the bootloader on an Arduino, if you're going from Arduino to an Atmega on a breadboard, or if you're making your own Arduino-compatible circuit on a breadboard. More For a huge list of examples from the Arduino
  • 5.  StringAppendOperator: append data to strings. community, see the interfacing with  StringCaseChanges: change the case of a string. hardware page on the playground wiki. Also see  StringCharacters: get/set the value of a specific the list of old examples. character in a string.  StringComparisonOperators: compare strings alphabetically.  StringConstructors: how to initialize string objects.  StringIndexOf: look for the first/last instance of a character in a string.  StringLength & StringLengthTrim: get and trim the length of a string.  StringReplace: replace individual characters in a string.  StringStartsWithEndsWith: check which characters/substrings a given string starts or ends with.  StringSubstring: look for "phrases" within a given string. 9.USB (Leonardo, Micro, and D ue specific examples) The Keyboard and Mouse examples are unique to the Leonardo, Micro and Due. They demonstrate the use of libraries that are unique to the board.  KeyboardAndMouseControl: Demonstrates the Mouse and Keyboard commands in one program. Keyboard  KeyboardMessage: Sends a text string when a button is pressed.  KeyboardLogout : Logs out the current user with key commands  KeyboardSerial: Reads a byte from the serial port, and sends back a keystroke.  KeyboardReprogram : opens a new window in the Arduino IDE and reprograms the Leonardo with a simple blink program Mouse  ButtonMouseControl: Control cursor movement with 5 pushbuttons.  JoystickMouseControl: Controls a computer's
  • 6. cursor movement with a Joystick when a button is pressed. Core Functions 1-BASICS Bare minimum Bare Minimum code needed to get started This example contains the bare minimum of code you need for an Arduino sketch to compile: the setup() method and theloop() method. Hardware Required  Arduino Board Circuit Only your Arduino Board is needed for this example. image developed using Fritzing. For more circuit examples, see the Fritzing project page Code The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup function will only run once, after each powerup or reset of the Arduino board.
  • 7. After creating a setup() function, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond as it runs. Code in the loop() section of your sketch is used to actively control the Arduino board. The code below won't actually do anything, but it's structure is useful for copying and pasting to get you started on any sketch of your own. It also shows you how to make comments in your code. Any line that starts with two slashes (//) will not be read by the compiler, so you can write anything you want after it. Commenting your code like this can be particularly helpful in explaining, both to yourself and others, how your program functions step by step. void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } Blink Blink This example shows the simplest thing you can do with an Arduino to see physical output: it blinks an LED. Hardware Required  Arduino Board  LED Circuit To build the circuit, attach a 220-ohm resistor to pin 13. Then attach the long leg of an LED (the positive leg, called the anode) to the resistor. Attach the short leg (the negative leg, called the cathode) to ground. Then plug your Arduino board into your computer, start the Arduino program, and enter the code below. Most Arduino boards already have an LED attached to pin 13 on the board itself. If you run this example with no hardware attached, you should see that LED blink. click the image to enlarge
  • 8. image developed using Fritzing. For more circuit examples, see the Fritzing project page Schematic click the image to enlarge Code
  • 9. In the program below, the first thing you do is to initialize pin 13 as an output pin with the line pinMode(13, OUTPUT); In the main loop, you turn the LED on with the line: digitalWrite(13, HIGH); This supplies 5 volts to pin 13. That creates a voltage difference across the pins of the LED, and lights it up. Then you turn it off with the line: digitalWrite(13, LOW); That takes pin 13 back to 0 volts, and turns the LED off. In between the on and the off, you want enough time for a person to see the change, so the delay() commands tell the Arduino to do nothing for 1000 milliseconds, or one second. When you use the delay() command, nothing else happens for that amount of time. Once you've understood the basic examples, check out the BlinkWithoutDelay example to learn how to create a delay while doing other things. Once you've understood this example, check out the DigitalReadSerial example to learn how read a switch connected to the Arduino. /* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: int led = 13; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } Digital Read Serial Digital Read Serial This example shows you how to monitor the state of a switch by establishing serial communication between your Arduino and your computer over USB. Hardware Required  Arduino Board  A momentary switch, button, or toggle switch  10k ohm resistor  breadboard  hook-up wire Circuit
  • 10. image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect three wires to the Arduino board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pulldown resistor (here 10 KOhms) to ground. The other leg of the button connects to the 5 volt supply. Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and reads as LOW, or 0. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that the pin reads as HIGH, or 1. If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it doesn't have a solid connection to voltage or ground, and it will randomly return either HIGH or LOW. That's why you need a pull-down resistor in the circuit. Schematic
  • 11. Code In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your Arduino and your computer with the line: Serial.begin(9600); Next, initialize digital pin 2, the pin that will read the output from your button, as an input: pinMode(2,INPUT); Now that your setup has been completed, move into the main loop of your code. When your button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the input pin will be connected to ground through the 10-kilohm resistor. This is a digital input, meaning that the switch can only be in either an on state (seen by your Arduino as a "1", or HIGH) or an off state (seen by your Arduino as a "0", or LOW), with nothing in between. The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch. Since the information coming in from the switch will be either a "1" or a "0", you can use anint datatype. Call this variable sensorValue, and set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one line of code: int sensorValue = digitalRead(2); Once the Arduino has read the input, make it print this information back to the computer as a decimal value. You can do this with the command Serial.println() in our last line of code: Serial.println(sensorValue); Now, when you open your Serial Monitor in the Arduino environment, you will see a stream of "0"s if your switch is open, or "1"s if your switch is closed. /* DigitalReadSerial Reads a digital input on pin 2, prints the result to the serial monitor This example code is in the public domain. */ // digital pin 2 has a pushbutton attached to it. Give it a name: int pushButton = 2; // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // make the pushbutton's pin an input: pinMode(pushButton, INPUT); } // the loop routine runs over and over again forever: void loop() { // read the input pin: int buttonState = digitalRead(pushButton); // print out the state of the button: Serial.println(buttonState); delay(1); // delay in between reads for stability } Analog Read Serial
  • 12. Analog Read Serial This example shows you how to read analog input from the physical world using a potentiometer. A potentiometer is a simple mechanical device that provides a varying amount of resistance when its shaft is turned. By passing voltage through a potentiometer and into an analog input on your Arduino, it is possible to measure the amount of resistance produced by a potentiometer (or pot for short) as an analog value. In this example you will monitor the state of your potentiometer after establishing serial communication between your Arduino and your computer. Hardware Required  Arduino Board  10-kilohm Potentiometer Circuit Connect the three wires from the potentiometer to your Arduino board. The first goes to ground from one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer pin of the potentiometer. The third goes from analog input 2 to the middle pin of the potentiometer. click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page By turning the shaft of the potentiometer, you change the amount of resistance on either side of the wiper which is connected to the center pin of the potentiometer. This changes the voltage at the center pin. When the resistance between the center and the side connected to 5 volts is close to zero (and the resistance on the other side is close to 10 kilohms), the voltage at the center pin nears 5 volts. When the resistances are reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog voltage that you're reading as an input. The Arduino has a circuit inside called an analog-to-digital converter that reads this changing voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned all the way in the opposite direction, there are 5 volts going to the pin and the input value is 1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin. Schematic click the image to enlarge
  • 13. Code In the program below, the only thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your Arduino and your computer with the command: Serial.begin(9600); Next, in the main loop of your code, you need to establish a variable to store the resistance value (which will be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer: int sensorValue = analogRead(A0); Finally, you need to print this information to your serial window as a decimal (DEC) value. You can do this with the command Serial.println() in your last line of code: Serial.println(sensorValue, DEC) Now, when you open your Serial Monitor in the Arduino development environment (by clicking the button directly to the right of the "Upload" button in the header of the program), you should see a steady stream of numbers ranging from 0-1023, correlating to the position of the pot. As you turn your potentiometer, these numbers will respond almost instantly. /* AnalogReadSerial Reads an analog input on pin 0, prints the result to the serial monitor. Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0);
  • 14. // print out the value you read: Serial.println(sensorValue); delay(1); // delay in between reads for stability } Fading Fading Demonstrates the use of the analogWrite() function in fading an LED off and on. AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very quickly, to create a fading effect. Hardware Required  Arduino board  Breadboard  a LED  a 220 ohm resistor Circuit Connect the anode (the longer, positive leg) of your LED to digital output pin 9 on your Arduino through a 220-ohm resistor. Connect the cathode (the shorter, negative leg) directly to ground. click the image to enlarge Schematic click the image to enlarge
  • 15. image developed using Fritzing. For more circuit examples, see the Fritzing project page Code After declaring pin 9 to be your ledPin, there is nothing to do in the setup() function of your code. The analogWrite() function that you will be using in the main loop of your code requires two arguments: One telling the function which pin to write to, and one indicating what PWM value to write. In order to fade your LED off and on, gradually increase your PWM value from 0 (all the way off) to 255 (all the way on), and then back to 0 once again to complete the cycle. In the sketch below, the PWM value is set using a variable calledbrightness. Each time through the loop, it increases by the value of the variable fadeAmount. If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it's 55, then it's set to 5. The next time through the loop, this change causesbrightness to change direction as well. analogWrite() can change the PWM value very fast, so the delay at the end of the sketch controls the speed of the fade. Try changing the value of the delay and see how it changes the program. /* Fade This example shows how to fade an LED on pin 9 using the analogWrite() function. This example code is in the public domain. */ int led = 9; int brightness = 0; int fadeAmount = 5; // the pin that the LED is attached to // how bright the LED is // how many points to fade the LED by // the setup routine runs once when you press reset: void setup() { // declare pin 9 to be an output: pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { // set the brightness of pin 9: analogWrite(led, brightness); // change the brightness for next time through the loop:
  • 16. brightness = brightness + fadeAmount; // reverse the if (brightness fadeAmount = } // wait for 30 delay(30); direction of the fading at the ends of the fade: == 0 || brightness == 255) { -fadeAmount ; milliseconds to see the dimming effect } Analog Read Voltage Analog Read Voltage This example shows you how to read an analog input on Pin 0, convert the values from analogRead() into voltage, and print it out to the serial monitor. Hardware Required  Arduino Board  a variable resistor, like a potentiometer Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect the three wires from the potentiometer to your Arduino board. The first goes to ground from one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer pin of the potentiometer. The third goes from analog input 2 to the middle pin of the potentiometer. By turning the shaft of the potentiometer, you change the amount of resistance on either side of the wiper which is connected to the center pin of the potentiometer. This changes the voltage at the center pin. When the resistance between the center and the side connected to 5 volts is close to zero (and the resistance on the other side is close to 10 kilohms), the voltage at the center pin nears 5 volts. When the
  • 17. resistances are reversed, the voltage at the center pin nears 0 volts, or ground. This voltage is the analog voltage that you're reading as an input. The Arduino has a circuit inside called an analog-to-digital converter that reads this changing voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned all the way in the opposite direction, there are 5 volts going to the pin and the input value is 1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin. Schematic Code In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your Arduino and your computer with the line: Serial.begin(9600); Next, in the main loop of your code, you need to establish a variable to store the resistance value (which will be between 0 and 1023, perfect for an int datatype) coming in from your potentiometer: int sensorValue = analogRead(A0); To change the values from 0-1023 to a range that corresponds to the voltage the pin is reading, you'll need to create another variable, a float, and do a little math. To scale the numbers between 0.0 and 5.0, divide 5.0 by 1023.0 and multiply that by sensorValue : float voltage= sensorValue * (5.0 / 1023.0); Finally, you need to print this information to your serial window as. You can do this with the command Serial.println() in your last line of code: Serial.println(voltage)
  • 18. Now, when you open your Serial Monitor in the Arduino development environment (by clicking the button directly to the right of the "Upload" button in the header of the program), you should see a steady stream of numbers ranging from 0.0 - 5.0. As you turn the pot, the values will change, corresponding to the voltage coming into pin A0. /* ReadAnalogVoltage Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor. Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. This example code is in the public domain. */ // the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V): float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println(voltage); } 2.Digital Blink Without Delay Blink Without Delay Sometimes you need to do two things at once. For example you might want to blink an LED (or some other time-sensitive function) while reading a button press or other input. In this case, you can't use delay(), or you'd stop everything else the program while the LED blinked. The program might miss the button press if it happens during the delay(). This sketch demonstrates how to blink the LED without using delay(). It keeps track of the last time the Arduino turned the LED on or off. Then, each time through loop(), it checks if a long enough interval has passed. If it has, it toggles the LED on or off. Hardware Required  Arduino Board  LED Circuit
  • 19. To build the circuit, grab an LED and attach its long, positive leg (called the anode) to pin 13. Attach the short, negative leg (called the anode) to ground. Then plug your Arduino board into your computer, start the Arduino program, and enter the code below. Schematic: click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page
  • 20. Code The code below uses the millis() function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED. /* Blink without Delay Turns on and off a light emitting diode(LED) connected to a digital pin, without using the delay() function. This means that other code can run at the same time without being interrupted by the LED code. The circuit: * LED attached from pin 13 to ground. * Note: on most Arduinos, there is already an LED on the board that's attached to pin 13, so no hardware is needed for this example. created 2005 by David A. Mellis modified 8 Feb 2010 by Paul Stoffregen This example code is in the public domain. http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay */ // constants won't change. Used here to // set pin numbers: const int ledPin = 13; // the number of the LED pin // Variables will change: int ledState = LOW; long previousMillis = 0; // ledState used to set the LED // will store last time LED was updated // the follow variables is a long because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long interval = 1000; // interval at which to blink (milliseconds) void setup() { // set the digital pin as output: pinMode(ledPin, OUTPUT); } void loop() { // here is where you'd put code that needs to be running all the time. // check to see if it's time to blink the LED; that is, if the // difference between the current time and last time you blinked // the LED is bigger than the interval at which you want to // blink the LED. unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState == LOW) ledState = HIGH; else ledState = LOW; // set the LED with the ledState of the variable: digitalWrite(ledPin, ledState); } }
  • 21. Button Button Pushbuttons or switches connect two points in a circuit when you press them. This example turns on the built-in LED on pin 13 when you press the button. Hardware  Arduino Board  momentary button or switch  10K ohm resistor  breadboard  hook-up wire Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect three wires to the Arduino board. The first two, red and black, connect to the two long vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button connects through a pulldown resistor (here 10 KOhms) to ground. The other leg of the button connects to the 5 volt supply. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts, so that we read a HIGH. You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button. If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit. Schematic: click the image to enlarge
  • 22. Code /* Button Turns on and off a light emitting diode(LED) connected to digital pin 13, when pressing a pushbutton attached to pin 2. The circuit: * LED attached from pin 13 to ground * pushbutton attached to pin 2 from +5V * 10K resistor attached to pin 2 from ground * Note: on most Arduinos there is already an LED on the board attached to pin 13. created 2005 by DojoDave <http://www.0j0.org> modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Button */ // constants won't change. They're used here to // set pin numbers: const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin // variables will change: int buttonState = 0; // variable for reading the pushbutton status void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop(){ // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); }
  • 23. else { // turn LED off: digitalWrite(ledPin, LOW); } } Debounce Debounce This example demonstrates the use of a pushbutton as a switch: each time you press the button, the LED (or whatever) is turned on (if it's off) or off (if on). It also debounces the input, which means checking twice in a short period of time to make sure it's definitely pressed. Without debouncing, pressing the button once can appear to the code as multiple presses. Makes use of the millis() function to keep track of the time when the button is pressed. Hardware Required  Arduino Board  momentary button or switch  10K ohm resistor  breadboard  hook-up wire Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Schematic click the image to enlarge
  • 24. Code The code below is based on Limor Fried's version of debounce, but the logic is inverted from her example. In her example, the switch returns LOW when closed, and HIGH when open. Here, the switch returns HIGH when pressed and LOW when not pressed. /* Debounce Each time the input pin goes from LOW to HIGH (e.g. because of a push-button press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a minimum delay between toggles to debounce the circuit (i.e. to ignore noise). The circuit: * LED attached from pin 13 to ground * pushbutton attached from pin 2 to +5V * 10K resistor attached from pin 2 to ground * Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 21 November 2006 by David A. Mellis modified 30 Aug 2011 by Limor Fried This example code is in the public domain. http://www.arduino.cc/en/Tutorial/Debounce */ // constants won't change. They're used here to // set pin numbers: const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin // Variables will change: int ledState = HIGH; // the current state of the output pin
  • 25. int buttonState; int lastButtonState = LOW; // the current reading from the input pin // the previous reading from the input pin // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); } void loop() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() // whatever // than the buttonState } - lastDebounceTime) > debounceDelay) { the reading is at, it's been there for longer debounce delay, so take it as the actual current state: = reading; // set the LED using the state of the button: digitalWrite(ledPin, buttonState); // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading; } Button State Change Detection (Edge Detection) Button State Change Detection (Edge Detection) Once you've got a pushbutton working, you often want to do some action based on how many times the button is pushed. To do this, you need to know when the button changes state from off to on, and count how many times this change of state happens. This is called state change detection or edge detection. Hardware Required  Arduino Board  momentary button or switch  10K ohm resistor  breadboard  hook-up wire Circuit
  • 26. image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect three wires to the Arduino board. The first goes from one leg of the pushbutton through a pulldown resistor (here 10 KOhms) to ground. The second goes from the corresponding leg of the pushbutton to the 5 volt supply. The third connects to a digital i/o pin (here pin 2) which reads the button's state. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a LOW. When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to voltage, so that we read a HIGH. (The pin is still connected to ground, but the resistor resists the flow of current, so the path of least resistance is to +5V.) If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, not connected to either voltage or ground. It will more or less randomly return either HIGH or LOW. That's why you need a pull-down resistor in the circuit. Schematic click the image to enlarge
  • 27. The sketch below continually reads the button's state. It then compares the button's state to its state the last time through the main loop. If the current button state is different from the last button state and the current button state is high, then the button changed from off to on. The sketch then increments a button push counter. The sketch also checks the button push counter's value, and if it's an even multiple of four, it turns the LED on pin 13 ON. Otherwise, it turns it off. Code /* State change detection (edge detection) Often, you don't need to know the state of a digital input all the time, but you just need to know when the input changes from one state to another. For example, you want to know when a button goes from OFF to ON. This is called state change detection, or edge detection. This example shows how to detect when a button or button changes from off to on and on to off. The circuit: * pushbutton attached to pin 2 from +5V * 10K resistor attached to pin 2 from ground * LED attached from pin 13 to ground (or use the built-in LED on most Arduino boards) created 27 Sep 2005 modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. http://arduino.cc/en/Tutorial/ButtonStateChange */ // this constant won't change: const int buttonPin = 2; // the pin that the pushbutton is attached to
  • 28. const int ledPin = 13; // the pin that the LED is attached to // Variables will change: int buttonPushCounter = 0; int buttonState = 0; int lastButtonState = 0; // counter for the number of button presses // current state of the button // previous state of the button void setup() { // initialize the button pin as a input: pinMode(buttonPin, INPUT); // initialize the LED as an output: pinMode(ledPin, OUTPUT); // initialize serial communication: Serial.begin(9600); } void loop() { // read the pushbutton input pin: buttonState = digitalRead(buttonPin); // compare the buttonState to its previous state if (buttonState != lastButtonState) { // if the state has changed, increment the counter if (buttonState == HIGH) { // if the current state is HIGH then the button // wend from off to on: buttonPushCounter++; Serial.println("on"); Serial.print("number of button pushes: "); Serial.println(buttonPushCounter); } else { // if the current state is LOW then the button // wend from on to off: Serial.println("off"); } } // save the current state as the last state, //for next time through the loop lastButtonState = buttonState; // turns on the LED every four button pushes by // checking the modulo of the button push counter. // the modulo function gives you the remainder of // the division of two numbers: if (buttonPushCounter % 4 == 0) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } } Input Pullup Serial Input Pullup Serial This example demonstrates the use of INPUT_PULLUP with pinMode(). It monitors the state of a switch by establishingserial communication between your Arduino and your computer over USB. Additionally, when the input is HIGH, the onboard LED attached to pin 13 will turn on; when LOW, the LED will turn off.
  • 29. Hardware Required  Arduino Board  A momentary switch, button, or toggle switch  breadboard  hook-up wire Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect two wires to the Arduino board. The black wire connects ground to one leg of the pushbutton. The second wire goes from digital pin 2 to the other leg of the pushbutton. Pushbuttons or switches connect two points in a circuit when you press them. When the pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton. Because the internal pull-up on pin 2 is active and connected to 5V, we read HIGH when the button is open. When the button is closed, the Arduino reads LOW because a connection to ground is completed. Schematic
  • 30. Code In the program below, the very first thing that you do will in the setup function is to begin serial communications, at 9600 bits of data per second, between your Arduino and your computer with the line: Serial.begin(9600); Next, initialize digital pin 2 as an input with the internal pull-up resistor enabled: pinMode(2,INPUT_PULLUP); The following line make pin 13, with the onboard LED, an output : pinMode(13, OUTPUT); Now that your setup has been completed, move into the main loop of your code. When your button not is pressed, the internal pull-up resistor connects to 5 volts. This causes the Arduino to report "1" or HIGH. When the button is pressed, the Arduino pin is pulled to ground, causing the Arduino report a "0", or LOW. The first thing you need to do in the main loop of your program is to establish a variable to hold the information coming in from your switch. Since the information coming in from the switch will be either a "1" or a "0", you can use anint datatype. Call this variable sensorValue, and set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one line of code:
  • 31. int sensorValue = digitalRead(2); Once the Arduino has read the input, make it print this information back to the computer as a decimal (DEC) value. You can do this with the command Serial.println() in our last line of code: Serial.println(sensorValue, DEC); Now, when you open your Serial Monitor in the Arduino environment, you will see a stream of "0"s if your switch is closed, or "1"s if your switch is open. The LED on pin 13 will illuminate when the switch is HIGH, and turn off when LOW. /* Input Pullup Serial This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital input on pin 2 and prints the results to the serial monitor. The circuit: * Momentary switch attached from pin 2 to ground * Built-in LED on pin 13 Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal 20K-ohm resistor is pulled to 5V. This configuration causes the input to read HIGH when the switch is open, and LOW when it is closed. created 14 March 2012 by Scott Fitzgerald http://www.arduino.cc/en/Tutorial/InputPullupSerial This example code is in the public domain */ void setup(){ //start serial connection Serial.begin(9600); //configure pin2 as an input and enable the internal pull-up resistor pinMode(2, INPUT_PULLUP); pinMode(13, OUTPUT); } void loop(){ //read the pushbutton value into a variable int sensorVal = digitalRead(2); //print out the value of the pushbutton Serial.println(sensorVal); // Keep in mind the pullup means the pushbutton's // logic is inverted. It goes HIGH when it's open, // and LOW when it's pressed. Turn on pin 13 when the // button's pressed, and off when it's not: if (sensorVal == HIGH) { digitalWrite(13, LOW); } else { digitalWrite(13, HIGH); } } Play a Melody using the tone() function
  • 32. Play a Melody using the tone() function This example shows how to use the tone() command to generate notes. It plays a little melody you may have heard before. Hardware Required  Arduino board  8 ohm small speaker  100 ohm resistor  hook-up wire Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect one terminal of your speaker to digital pin 8 through a 100 ohm resistor. Connect the other terminal to ground. Schematic click the image to enlarge
  • 33. Code The code below uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful for whenever you want to make musical notes. The main sketch is as follows: /* Melody Plays a melody circuit: * 8-ohm speaker on digital pin 8 created 21 Jan 2010 modified 30 Aug 2011 by Tom Igoe This example code is in the public domain. http://arduino.cc/en/Tutorial/Tone */ #include "pitches.h" // notes in the melody: int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4}; // note durations: 4 = quarter note, 8 = eighth note, etc.: int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 }; void setup() { // iterate over the notes of the melody: for (int thisNote = 0; thisNote < 8; thisNote++) { // to calculate the note duration, take one second // divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000/noteDurations[thisNote]; tone(8, melody[thisNote],noteDuration);
  • 34. // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: noTone(8); } } void loop() { // no need to repeat the melody. } [Get Code] To make the pitches.h file, click on the "new Tab" button in the upper right hand corner of the window. It looks like this: The paste in the following code: /************************************************* * Public Constants *************************************************/ #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define NOTE_B0 NOTE_C1 NOTE_CS1 NOTE_D1 NOTE_DS1 NOTE_E1 NOTE_F1 NOTE_FS1 NOTE_G1 NOTE_GS1 NOTE_A1 NOTE_AS1 NOTE_B1 NOTE_C2 NOTE_CS2 NOTE_D2 NOTE_DS2 NOTE_E2 NOTE_F2 NOTE_FS2 NOTE_G2 NOTE_GS2 NOTE_A2 NOTE_AS2 NOTE_B2 NOTE_C3 NOTE_CS3 NOTE_D3 NOTE_DS3 NOTE_E3 NOTE_F3 NOTE_FS3 NOTE_G3 NOTE_GS3 NOTE_A3 NOTE_AS3 NOTE_B3 NOTE_C4 NOTE_CS4 NOTE_D4 NOTE_DS4 NOTE_E4 NOTE_F4 NOTE_FS4 NOTE_G4 NOTE_GS4 NOTE_A4 NOTE_AS4 NOTE_B4 NOTE_C5 NOTE_CS5 NOTE_D5 NOTE_DS5 NOTE_E5 31 33 35 37 39 41 44 46 49 52 55 58 62 65 69 73 78 82 87 93 98 104 110 117 123 131 139 147 156 165 175 185 196 208 220 233 247 262 277 294 311 330 349 370 392 415 440 466 494 523 554 587 622 659
  • 35. #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define NOTE_F5 NOTE_FS5 NOTE_G5 NOTE_GS5 NOTE_A5 NOTE_AS5 NOTE_B5 NOTE_C6 NOTE_CS6 NOTE_D6 NOTE_DS6 NOTE_E6 NOTE_F6 NOTE_FS6 NOTE_G6 NOTE_GS6 NOTE_A6 NOTE_AS6 NOTE_B6 NOTE_C7 NOTE_CS7 NOTE_D7 NOTE_DS7 NOTE_E7 NOTE_F7 NOTE_FS7 NOTE_G7 NOTE_GS7 NOTE_A7 NOTE_AS7 NOTE_B7 NOTE_C8 NOTE_CS8 NOTE_D8 NOTE_DS8 698 740 784 831 880 932 988 1047 1109 1175 1245 1319 1397 1480 1568 1661 1760 1865 1976 2093 2217 2349 2489 2637 2794 2960 3136 3322 3520 3729 3951 4186 4435 4699 4978 Pitch follower using the tone() function Pitch follower using the tone() function This example shows how to use the tone() command to generate a pitch that follows the values of an analog input Hardware Required  8-ohm speaker  1 photocell  4.7K ohm resistor  100 ohm resistor  breadboard  hook up wire Circuit
  • 36. image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect one terminal of your speaker to digital pin 9 through a 100 ohm resistor, and its other terminal to ground. Power your photoresistor with 5V, and connect it to analog 0 with the addition of a 4.7K resistor to ground. Schematic click the image to enlarge Code The code for this example is very simple. Just take an analog input and map its values to a range of audible pitches. Humans can hear from 20 - 20,000Hz, but 120 - 1500 usually works pretty well for this sketch. You'll need to get the actual range of your analog input for the mapping. In the circuit shown, the analog input value ranged from about 400 to about 1000. Change the values in the map() command to match the range for your sensor. The sketch is as follows:
  • 37. /* Pitch follower Plays a pitch that changes based on a changing analog input circuit: * 8-ohm speaker on digital pin 8 * photoresistor on analog 0 to 5V * 4.7K resistor on analog 0 to ground created 21 Jan 2010 modified 31 May 2012 by Tom Igoe, with suggestion from Michael Flynn This example code is in the public domain. http://arduino.cc/en/Tutorial/Tone2 */ void setup() { // initialize serial communications (for debugging only): Serial.begin(9600); } void loop() { // read the sensor: int sensorReading = analogRead(A0); // print the sensor reading so you know its range Serial.println(sensorReading); // map the analog input range (in this case, 400 - 1000 from the photoresistor) // to the output pitch range (120 - 1500Hz) // change the minimum and maximum input numbers below // depending on the range your sensor's giving: int thisPitch = map(sensorReading, 400, 1000, 120, 1500); // play the pitch: tone(9, thisPitch, 10); delay(1); // delay in between reads for stability } Simple keyboard using the tone() function Simple keyboard using the tone() function This example shows how to use the tone() command to generate different pitches depending on which sensor is pressed. Hardware Required  8-ohm speaker  (3) force sensing resistors  (3) 10k ohm resistors  (1) 100 ohm resistor  breadboard  hook up wire Circuit
  • 38. Connect one terminal of your speaker to digital pin 8 through a 100 ohm resistor, and its other terminal to ground. Power your three FSRs (or any other analog sensor) with 5V in parallel. Connect each sensor to analog pins 0-2, using a 10K resistor as a reference to groud on each input line. click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page Schematic click the image to enlarge
  • 39. Code The sketch below reads three analog sensors. Each corresponds to a note value in an array of notes. IF any of the sensors is above a given threshold, the corresponding note is played. Here's the main sketch: /* keyboard Plays a pitch that changes based on a changing analog input circuit: * 3 force-sensing resistors from +5V to analog in 0 through 5 * 3 10K resistors from analog in 0 through 5 to ground * 8-ohm speaker on digital pin 8 created 21 Jan 2010 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. http://arduino.cc/en/Tutorial/Tone3 */ #include "pitches.h" const int threshold = 10; // minimum reading of the sensors that generates a note // notes to play, corresponding to the 3 sensors: int notes[] = { NOTE_A4, NOTE_B4,NOTE_C3 }; void setup() { } void loop() { for (int thisSensor = 0; thisSensor < 3; thisSensor++) { // get a sensor reading:
  • 40. int sensorReading = analogRead(thisSensor); // if the sensor is pressed hard enough: if (sensorReading > threshold) { // play the note corresponding to this sensor: tone(8, notes[thisSensor], 20); } } } [Get Code] The sketch uses an extra file, pitches.h. This file contains all the pitch values for typical notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note table was originally written by Brett Hagman, on whose work the tone() command was based. You may find it useful for whenever you want to make musical notes. To make this file, click on the "new Tab" button in the upper right hand corner of the window. It looks like this: The paste in the following code: /************************************************* * Public Constants *************************************************/ #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define NOTE_B0 NOTE_C1 NOTE_CS1 NOTE_D1 NOTE_DS1 NOTE_E1 NOTE_F1 NOTE_FS1 NOTE_G1 NOTE_GS1 NOTE_A1 NOTE_AS1 NOTE_B1 NOTE_C2 NOTE_CS2 NOTE_D2 NOTE_DS2 NOTE_E2 NOTE_F2 NOTE_FS2 NOTE_G2 NOTE_GS2 NOTE_A2 NOTE_AS2 NOTE_B2 NOTE_C3 NOTE_CS3 NOTE_D3 NOTE_DS3 NOTE_E3 NOTE_F3 NOTE_FS3 NOTE_G3 NOTE_GS3 NOTE_A3 NOTE_AS3 NOTE_B3 NOTE_C4 NOTE_CS4 NOTE_D4 NOTE_DS4 NOTE_E4 NOTE_F4 NOTE_FS4 NOTE_G4 NOTE_GS4 NOTE_A4 NOTE_AS4 NOTE_B4 NOTE_C5 NOTE_CS5 31 33 35 37 39 41 44 46 49 52 55 58 62 65 69 73 78 82 87 93 98 104 110 117 123 131 139 147 156 165 175 185 196 208 220 233 247 262 277 294 311 330 349 370 392 415 440 466 494 523 554
  • 41. #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define NOTE_D5 NOTE_DS5 NOTE_E5 NOTE_F5 NOTE_FS5 NOTE_G5 NOTE_GS5 NOTE_A5 NOTE_AS5 NOTE_B5 NOTE_C6 NOTE_CS6 NOTE_D6 NOTE_DS6 NOTE_E6 NOTE_F6 NOTE_FS6 NOTE_G6 NOTE_GS6 NOTE_A6 NOTE_AS6 NOTE_B6 NOTE_C7 NOTE_CS7 NOTE_D7 NOTE_DS7 NOTE_E7 NOTE_F7 NOTE_FS7 NOTE_G7 NOTE_GS7 NOTE_A7 NOTE_AS7 NOTE_B7 NOTE_C8 NOTE_CS8 NOTE_D8 NOTE_DS8 587 622 659 698 740 784 831 880 932 988 1047 1109 1175 1245 1319 1397 1480 1568 1661 1760 1865 1976 2093 2217 2349 2489 2637 2794 2960 3136 3322 3520 3729 3951 4186 4435 4699 4978 SPlaying tones on Multiple outputs using the tone() function SPlay ing tones on Multiple outputs using the tone() function This example shows how to use the tone() command to play different notes on multiple outputs. The tone() command works by taking over one of the Atmega's internal timers, setting it to the frequency you want, and using the timer to pulse an output pin. Since it's only using one timer, you can only play one note at a time. You can, however, play notes on multiple pins sequentially. To do this, you need to turn the timer off for one pin before moving on to the next. Thanks to Greg Borenstein for clarifying this. Hardware Required  (3) 8-ohm speakers  (3) 100 ohm resistor  breadboard  hook up wire
  • 42. Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page Schematic click the image to enlarge Code The sketch below plays a tone on each of the speakers in sequence, turning off the previous speaker first. Note that the duration of each tone is the same as the delay that follows it. Here's the main sketch: /* Multiple tone player Plays multiple tones on multiple pins in sequence circuit: * 3 8-ohm speaker on digital pins 6, 7, and 11 created 8 March 2010 by Tom Igoe
  • 43. based on a snippet from Greg Borenstein This example code is in the public domain. http://arduino.cc/en/Tutorial/Tone4 */ void setup() { } void loop() { // turn off tone function for pin 11: noTone(11); // play a note on pin 6 for 200 ms: tone(6, 440, 200); delay(200); // turn off tone function for pin 6: noTone(6); // play a note on pin 7 for 500 ms: tone(7, 494, 500); delay(500); // turn off tone function for pin 7: noTone(7); // play a note on pin 11 for 500 ms: tone(11, 523, 300); delay(300); } 3.Analog Analog In, Out Serial Analog In, Out Serial This example shows how to read an analog input pin, map the result to a range from 0 to 255, and then use that result to set the pulsewidth modulation (PWM) of an output pin to dim or brighten an LED. Hardware Required  Arduino Board  Potentiometer  LED  220 ohm resistor Circuit
  • 44. image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect one pin from your pot to 5V, the center pin to analog pin 0, and the remaining pin to ground. Next, connect a 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. Schematic Code In the program below, after declaring two pin assignments (analog 0 for your potentiometer and digital 9 for your LED) and two variables, sensorValue and outputValue, the only thing that you do will in the setup function is to begin serial communication.
  • 45. Next, in the main loop of the code, sensorValue is assigned to store the raw analog value coming in from the potentiometer. Because the Arduino has an analogRead resolution of 0-1023, and an analogWrite resolution of only 0-255, this raw data from the potentiometer needs to be scaled before using it to dim the LED. In order to scale this value, use a function called map() outputValue = map(sensorValue, 0, 1023, 0, 255); [Get Code] outputValue is assigned to equal the scaled value from the potentiometer. map() accepts five arguments: The value to be mapped, the low range and high range of the raw data, and the low and high values for that data to be scaled too. In this case, the sensor data is mapped down from its original range of 0 to 1023 to 0 to 255. The newly mapped sensor data is then output to the analogOutPin dimming or brightening the LED as the potentiometer is turned. Finally, both the raw and scaled sensor values are sent to the Arduino serial window in a steady stream of data. /* Analog input, analog output, serial output Reads an analog input pin, maps the result to a range from 0 to 255 and uses the result to set the pulsewidth modulation (PWM) of an output pin. Also prints the results to the serial monitor. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 9 to ground created 29 Dec. 2008 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. */ // These constants won't change. They're used to give names // to the pins used: const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int analogOutPin = 9; // Analog output pin that the LED is attached to int sensorValue = 0; int outputValue = 0; // value read from the pot // value output to the PWM (analog out) void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600); } void loop() { // read the analog in value: sensorValue = analogRead(analogInPin); // map it to the range of the analog out: outputValue = map(sensorValue, 0, 1023, 0, 255); // change the analog out value: analogWrite(analogOutPin, outputValue); // print the results to the serial monitor: Serial.print("sensor = " ); Serial.print(sensorValue); Serial.print("t output = "); Serial.println(outputValue); // wait 2 milliseconds before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(2); }
  • 46. Analog Input Analog Input A potentiometer is a simple knob that provides a variable resistance, which you can read into the Arduino board as an analog value. In this example, you'll connect a poterntiometer to one of the Arduino's analog inputs to control the rate at which the built-in LED on pin 13 blinks. Hardware Required  Arduino Board  Potentiometer  built-in LED on pin 13 Circuit click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect three wires to the Arduino board. The first goes to ground from one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer pin of the potentiometer. The third goes from analog input 0 to the middle pin of the potentiometer. For this example, it is possible to use the Arduino board's built in LED attached to pin 13. To use an additional LED, attach its longer leg (the positive leg, or anode), to digital pin 13, and it's shorter leg (the
  • 47. negative leg, or cathode) to the ground (gnd) pin next to pin 13. Because of the low amount of current coming from digital pin 13, it is not necessary to use a current limiting resistor in this particular case. Schematic click the image to enlarge Code In the beginning of this program, the variable sensorPin is set to to analog pin 0, where your potentiometer is attached, and ledPin is set to digital pin 13. You'll also create another variable, sensorValue i to store the values read from your sensor. The analogRead() command converts the input voltage range, 0 to 5 volts, to a digital value between 0 and 1023. This is done by a circuit inside the Arduino called an analog-to-digital converter or ADC. By turning the shaft of the potentiometer, you change the amount of resistance on either side of the center pin (or wiper) of the potentiometer. This changes the relative resistances between the center pin and the two outside pins, giving you a different voltage at the analog input. When the shaft is turned all the way in one direction, there is no resistance between the center pin and the pin connected to ground. The voltage at the center pin then is 0 volts, and analogRead() returns 0. When the shaft is turned all the way in the other direction, there is no resistance between the center pin and the pin connected to +5 volts. The voltage at the center pin then is 5 volts, and analogRead() returns 1023. In between,analogRead() returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin. That value, stored in sensorValue, is used to set a delay() for your blink cycle. The higher the value, the longer the cycle, the smaller the value, the shorter the cycle. /* Analog Input Demonstrates analog input by reading an analog sensor on analog pin 0 and turning on and off a light emitting diode(LED) connected to digital pin 13. The amount of time the LED will be on and off depends on the value obtained by analogRead().
  • 48. The circuit: * Potentiometer attached to analog input 0 * center pin of the potentiometer to the analog pin * one side pin (either one) to ground * the other side pin to +5V * LED anode (long leg) attached to digital output 13 * LED cathode (short leg) attached to ground * Note: because most Arduinos have a built-in LED attached to pin 13 on the board, the LED is optional. Created by David Cuartielles modified 30 Aug 2011 By Tom Igoe This example code is in the public domain. http://arduino.cc/en/Tutorial/AnalogInput */ int sensorPin = A0; int ledPin = 13; int sensorValue = 0; // select the input pin for the potentiometer // select the pin for the LED // variable to store the value coming from the sensor void setup() { // declare the ledPin as an OUTPUT: pinMode(ledPin, OUTPUT); } void loop() { // read the value from the sensor: sensorValue = analogRead(sensorPin); // turn the ledPin on digitalWrite(ledPin, HIGH); // stop the program for <sensorValue> milliseconds: delay(sensorValue); // turn the ledPin off: digitalWrite(ledPin, LOW); // stop the program for for <sensorValue> milliseconds: delay(sensorValue); } Analog Write with 12 LEDs on an Arduino Mega Analog Write with 12 LEDs on an Arduino Mega This example fades 12 LEDs up and the down, one by one, on an Arduino Mega board. Hardware Required  Arduino Mega Board  (12) LEDs  (12) 220 ohm resistors  hook up wire  breadboard Circuit
  • 49. image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect the longer, positive legs of (anodes) 12 LEDs to digital pins 2-13 through 220 ohm current limiting resistors. Connect the shorter, negative legs (cathodes) to ground. Schematic
  • 50. Code In the setup() function of the code below, a for() loop is used to assign digital pins 2-13 of the Mega as outputs. Next, in the loop() function of the program below, a trio of nested for() loops are used. The first of these loops, for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) [Get Code] moves through each of the LEDS one by one, from the lowest pin to the highest. Before this loop is allowed to move from one pin to the next, two things must be accomplished. First, you brighten the individual LED through these lines of code: for (int brightness = 0; brightness < 255; brightness++) { analogWrite(thisPin, brightness); delay(2); } [Get Code] With each pass through the loop above, the variable brightness increases by one point, and that value is written to the pin currently selected to the main loop. One that pin reaches the maximum PWM value (255), the following loop kicks in: for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(thisPin, brightness); delay(2); } [Get Code] This loop subtracts a point from the brightness variable, dimming the LED back down to 0. Once zero is reached, the mainfor() loop kicks in, and the program moves on to the next LED pin, repeating all the steps mentioned above. /* Mega analogWrite() test This sketch fades LEDs up and down one at a time on digital pins 2 through 13. This sketch was written for the Arduino Mega, and will not work on previous boards. The circuit: * LEDs attached from pins 2 through 13 to ground. created 8 Feb 2009 by Tom Igoe This example code is in the public domain. */ // These constants won't change. // to the pins used: const int lowestPin = 2; const int highestPin = 13; They're used to give names void setup() { // set pins 2 through 13 as outputs: for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) { pinMode(thisPin, OUTPUT); } } void loop() { // iterate over the pins: for (int thisPin =lowestPin; thisPin <= highestPin; thisPin++) { // fade the LED on thisPin from off to brightest: for (int brightness = 0; brightness < 255; brightness++) { analogWrite(thisPin, brightness); delay(2); } // fade the LED on thisPin from brithstest to off: for (int brightness = 255; brightness >= 0; brightness--) { analogWrite(thisPin, brightness); delay(2); }
  • 51. // pause between LEDs: delay(100); } } Calibration Calibration This example demonstrates one techinque for calibrating sensor input. The Arduino takes sensor readings for five seconds during the startup, and tracks the highest and lowest values it gets. These sensor readings during the first five seconds of the sketch execution define the minimum and maximum of expected values for the readings taken during the loop. Hardware Required  Arduino board  (1) LED  (1) analog sensor (a photocell will do)  (1) 10K ohm resistor  (1) 220 ohm resistor  breadboard  hook-up wire Circuit Analog sensor (e.g. potentiometer, light sensor) on analog input 2. LED on digital pin 9. click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect an LED to digital pin 9 with a 220 ohm current limiting resistor. Connect a photocell to 5V and then to analog pin 0 with a 10K ohm resistor as a reference to ground. Schematic click the image to enlarge
  • 52. Code Before the setup, you set initial values for the minimum and maximum like so: int sensorMin = 1023; int sensorMax = 0; // minimum sensor value // maximum sensor value [Get Code] These may seem backwards. Initially, you set the minimum high and read for anything lower than that, saving it as the new minimum. Likewise, you set the maximum low and read for anything higher as the new maximum, like so: // calibrate during the first five seconds while (millis() < 5000) { sensorValue = analogRead(sensorPin); // record the maximum sensor value if (sensorValue > sensorMax) { sensorMax = sensorValue; } // record the minimum sensor value if (sensorValue < sensorMin) { sensorMin = sensorValue; } } [Get Code] This way, any further readings you take can be mapped to the range between this minimum and maximum like so: // apply the calibration to the sensor reading sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); [Get Code] Here's the whole program: /* Calibration Demonstrates one technique for calibrating sensor input. The sensor readings during the first five seconds of the sketch execution define the minimum and maximum of expected values
  • 53. attached to the sensor pin. The sensor minimum and maximum initial values may seem backwards. Initially, you set the minimum high and listen for anything lower, saving it as the new minimum. Likewise, you set the maximum low and listen for anything higher as the new maximum. The circuit: * Analog sensor (potentiometer will do) attached to analog input 0 * LED attached from digital pin 9 to ground created 29 Oct 2008 By David A Mellis modified 30 Aug 2011 By Tom Igoe http://arduino.cc/en/Tutorial/Calibration This example code is in the public domain. */ // These constants won't change: const int sensorPin = A0; // pin that the sensor is attached to const int ledPin = 9; // pin that the LED is attached to // variables: int sensorValue = 0; int sensorMin = 1023; int sensorMax = 0; // the sensor value // minimum sensor value // maximum sensor value void setup() { // turn on LED to signal the start of the calibration period: pinMode(13, OUTPUT); digitalWrite(13, HIGH); // calibrate during the first five seconds while (millis() < 5000) { sensorValue = analogRead(sensorPin); // record the maximum sensor value if (sensorValue > sensorMax) { sensorMax = sensorValue; } // record the minimum sensor value if (sensorValue < sensorMin) { sensorMin = sensorValue; } } // signal the end of the calibration period digitalWrite(13, LOW); } void loop() { // read the sensor: sensorValue = analogRead(sensorPin); // apply the calibration to the sensor reading sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); // in case the sensor value is outside the range seen during calibration sensorValue = constrain(sensorValue, 0, 255); // fade the LED using the calibrated value: analogWrite(ledPin, sensorValue); }
  • 54. Fading Fading Demonstrates the use of analog output (Pulse Width Modulation (PWM)) to fade an LED. PWM is a technique for getting an analog-like behavior from a digital output by switching it off and on very fast. Circuit An LED connected to digital output pin 9 through a 220-ohm resistor. click the image to enlarge Schematic click the image to enlarge
  • 55. image developed using Fritzing. For more circuit examples, see the Fritzing project page Code /* Fading This example shows how to fade an LED using the analogWrite() function. The circuit: * LED attached from digital pin 9 to ground. Created 1 Nov 2008 By David A. Mellis modified 30 Aug 2011 By Tom Igoe http://arduino.cc/en/Tutorial/Fading This example code is in the public domain. */ int ledPin = 9; // LED connected to digital pin 9 void setup() { // nothing happens in setup } void loop() { // fade in from min to max in increments of 5 points: for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) { // sets the value (range from 0 to 255): analogWrite(ledPin, fadeValue); // wait for 30 milliseconds to see the dimming effect delay(30); } // fade out from max to min in increments of 5 points: for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) { // sets the value (range from 0 to 255): analogWrite(ledPin, fadeValue); // wait for 30 milliseconds to see the dimming effect delay(30);
  • 56. } } Smoothing Smoothing This sketch reads repeatedly from an analog input, calculating a running average and printing it to the computer. This example is useful for smoothing out the values from jumpy or erratic sensors, and also demonstrates the use of arrays to store data. Hardware  Arduino Board  Potentiometer Circuit click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page Connect one pin of a potentiometer to 5V, the center pin to analog pin 0, and the the last pin to ground. Schematic click the image to enlarge
  • 57. Code The code below sequentially stores 10 readings from your analog sensor into an arrays, one by one. With each new value, the sum of all the numbers is generated and divided, producing an average value which then be used to smooth outlying data. Because this averaging takes place each time a new value is added to the array (rather then waiting for 10 new values, for instance) there is no lag time in calculating this running average. Altering the size of the array used, by changing numReadings to a larger value will smooth the data collected even further. /* Smoothing Reads repeatedly from an analog input, calculating a running average and printing it to the computer. Keeps ten readings in an array and continually averages them. The circuit: * Analog sensor (potentiometer will do) attached to analog input 0 Created 22 April 2007 By David A. Mellis <dam@mellis.org> modified 9 Apr 2012 by Tom Igoe http://www.arduino.cc/en/Tutorial/Smoothing This example code is in the public domain. */ // Define the number of samples to keep track of. The higher the number, // the more the readings will be smoothed, but the slower the output will // respond to the input. Using a constant rather than a normal variable lets // use this value to determine the size of the readings array. const int numReadings = 10; int readings[numReadings]; // the readings from the analog input
  • 58. int index = 0; int total = 0; int average = 0; // the index of the current reading // the running total // the average int inputPin = A0; void setup() { // initialize serial communication with computer: Serial.begin(9600); // initialize all the readings to 0: for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; } void loop() { // subtract the last reading: total= total - readings[index]; // read from the sensor: readings[index] = analogRead(inputPin); // add the reading to the total: total= total + readings[index]; // advance to the next position in the array: index = index + 1; // if we're at the end of the array... if (index >= numReadings) // ...wrap around to the beginning: index = 0; // calculate the average: average = total / numReadings; // send it to the computer as ASCII digits Serial.println(average); delay(1); // delay in between reads for stability } 4.Communication Read ASCII String 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), but other characters like a space or a period will work too.
  • 59. The values are parsed into ints and used to determine the color of a RGB LED. You'll use the serial monitor to send strings like "5,220,70" to the Arduino to change the lights. Hardware Required  Arduino Board  Breadboard  Hookup wire  Common anode RGB LED  Three 220-ohm resistors Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page You'll need five wires to make the circuit above. Connect a red wire to one of the long vertical rows on your breadboard. Connect the other end to the 5V pin on your Arduino. Place an RGB LED on your breadboard. Check the datasheet for your specific LED to verify the pins. Connect the power rail you just created to the common anode on the LED. 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 Arduino 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:
  • 60. 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 Arduino 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. UsingSerial.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 Arduino: 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 Arduino, open your Serial minitor. 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 Arduino, the attached LED will turn the color you specified, and you will receive 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.
  • 61. It parses them into ints, and uses those to fade an RGB LED. Circuit: Common-anode RGB LED wired like so: * Red cathode: digital pin 3 * Green cathode: digital pin 5 * blue cathode: digital pin 6 * anode: +5V created 13 Apr 2012 by Tom Igoe 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); } } } ASCII Table ASCII Table
  • 62. Demonstrates the advanced serial printing functions by generating a table of characters and their ASCII values in decimal, hexadecimal, octal, and binary. For more on ASCII, see asciitable.com Hardware Required  Arduino Board Circuit image developed using Fritzing. For more circuit examples, see the Fritzing project page None, but the Arduino has to be connected to the computer. Code /* ASCII table Prints out byte values in all possible formats: * as raw binary values * as ASCII-encoded decimal, hex, octal, and binary values For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII The circuit: No external hardware needed. created 2006 by Nicholas Zambetti modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. <http://www.zambetti.com> */ void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // prints title with ending line break Serial.println("ASCII Table ~ Character Map"); } // first visible ASCIIcharacter '!' is number 33: int thisByte = 33; // you can also write ASCII characters in single quotes. // for example. '!' is the same as 33, so you could also use this: //int thisByte = '!'; void loop() { // prints value unaltered, i.e. the raw binary version of the // byte. The serial monitor interprets all bytes as // ASCII, so 33, the first number, will show up as '!' Serial.write(thisByte); Serial.print(", dec: "); // prints value as string as an ASCII-encoded decimal (base 10). // Decimal is the default format for Serial.print() and Serial.println(),
  • 63. // so no modifier is needed: Serial.print(thisByte); // But you can declare the modifier for decimal if you want to. //this also works if you uncomment it: // Serial.print(thisByte, DEC); Serial.print(", hex: "); // prints value as string in hexadecimal (base 16): Serial.print(thisByte, HEX); Serial.print(", oct: "); // prints value as string in octal (base 8); Serial.print(thisByte, OCT); Serial.print(", bin: "); // prints value as string in binary (base 2) // also prints ending line break: Serial.println(thisByte, BIN); // if printed last visible character '~' or 126, stop: if(thisByte == 126) { // you could also use if (thisByte == '~') { // This loop loops forever and does nothing while(true) { continue; } } // go on to the next character thisByte++; } [Get Code] Output ASCII Table ~ Character Map !, dec: 33, hex: 21, oct: 41, bin 4, decúASCII Table ~ Character Map !, dec: 33, hex: 21, oct: 41, bin: 100001 ", dec: 34, hex: 22, oct: 42, bin: 100010 #, dec: 35, hex: 23, oct: 43, bin: 100011 $, dec: 36, hex: 24, oct: 44, bin: 100100 %, dec: 37, hex: 25, oct: 45, bin: 100101 &, dec: 38, hex: 26, oct: 46, bin: 100110 ', dec: 39, hex: 27, oct: 47, bin: 100111 (, dec: 40, hex: 28, oct: 50, bin: 101000 ), dec: 41, hex: 29, oct: 51, bin: 101001 *, dec: 42, hex: 2A, oct: 52, bin: 101010 +, dec: 43, hex: 2B, oct: 53, bin: 101011 ,, dec: 44, hex: 2C, oct: 54, bin: 101100 -, dec: 45, hex: 2D, oct: 55, bin: 101101 ., dec: 46, hex: 2E, oct: 56, bin: 101110 /, dec: 47, hex: 2F, oct: 57, bin: 101111 0, dec: 48, hex: 30, oct: 60, bin: 110000 1, dec: 49, hex: 31, oct: 61, bin: 110001 2, dec: 50, hex: 32, oct: 62, bin: 110010 3, dec: 51, hex: 33, oct: 63, bin: 110011 4, dec: 52, hex: 34, oct: 64, bin: 110100 5, dec: 53, hex: 35, oct: 65, bin: 110101 6, dec: 54, hex: 36, oct: 66, bin: 110110 7, dec: 55, hex: 37, oct: 67, bin: 110111 8, dec: 56, hex: 38, oct: 70, bin: 111000 9, dec: 57, hex: 39, oct: 71, bin: 111001 :, dec: 58, hex: 3A, oct: 72, bin: 111010 ;, dec: 59, hex: 3B, oct: 73, bin: 111011 <, dec: 60, hex: 3C, oct: 74, bin: 111100 =, dec: 61, hex: 3D, oct: 75, bin: 111101 >, dec: 62, hex: 3E, oct: 76, bin: 111110 ?, dec: 63, hex: 3F, oct: 77, bin: 111111 @, dec: 64, hex: 40, oct: 100, bin: 1000000 A, dec: 65, hex: 41, oct: 101, bin: 1000001 B, dec: 66, hex: 42, oct: 102, bin: 1000010 C, dec: 67, hex: 43, oct: 103, bin: 1000011 D, dec: 68, hex: 44, oct: 104, bin: 1000100 E, dec: 69, hex: 45, oct: 105, bin: 1000101 ...
  • 64. Dimmer Dimmer This example shows how to send data from a personal computer to an Arduino 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. Arduino reads these bytes and uses them to set the brightness of the LED. You can send bytes to the Arduino from any software that can access the computer serial port. Examples for Processingand Max/MSP version 5 are shown below. Hardware Required  Arduino Board  LED  220 ohm resistor Software Required  Processing or  Max/MSP version 5 Circuit An LED connected to pin 9. Use an appropriate resistor as needed. For most common LEDs, you can usually do without the resistor, as the current output of the digital I/O pins is limited. click the image to enlarge image developed using Fritzing. For more circuit examples, see the Fritzing project page Schematic click the image to enlarge
  • 65. % Code /* Dimmer Demonstrates the 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
  • 66. // 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:"); 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); } */ /* Max/MSP v5 patch for this example ----------begin_max5_patcher---------1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2 uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA 4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6 WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9 FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7 3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ +wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8 ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS xqZqbd3ZLdera1iPqYxOm++v7SUSz -----------end_max5_patcher----------*/ [Get Code] Processing Code The Processing sketch in the code sample above will send bytes out the serial port to the Arduino to dim the LED. Max code The Max/MSP patch in the code sample above looks like the image below. Copy it and paste it into a new patch window.
  • 67. Graph Graph This example shows you how to send a byte of data from the Arduino to a personal computer and graph the result. This is called 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. You can use the Arduino serial monitor to view the sent data, or it can be read by Processing (see code below), Flash, PD, Max/MSP, etc. Hardware Required  Arduino Board  Analog Sensor (potentiometer, photocell, FSR, etc.) Software Required
  • 68.  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
  • 69. 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 is 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