0% found this document useful (0 votes)
109 views57 pages

Pratica 01 PDF

Uploaded by

Denise Araújo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views57 pages

Pratica 01 PDF

Uploaded by

Denise Araújo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

!

Prática 1
(atividades retiradas do tutorial padrão para Arduino em http://arduino.cc)

Atividade 1:
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 the loop() 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:

Atividade 2:
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.

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

Schematic
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.
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}

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
}
Atividade 3:
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 pull-down 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 an int 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.
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}

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
}

Atividade 4:
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 0
to the middle pin of the potentiometer.

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
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.
void setup() {
Serial.begin(9600);
}

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
}

Atividade 5:
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.

Schematic
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 called
brightness. 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 -5, then it's set to 5. The next time through the loop, this change
causes brightness 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.
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

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 direction of the fading at the ends of the fade:


if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

Atividade 6:
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.

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

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);
}

Atividade 7:
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 cathode) to ground. Then plug
your Arduino board into your computer, start the Arduino program, and enter the
code below.

Schematic

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.
// 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; // ledState used to set the LED
long previousMillis = 0; // 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()
{
// 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);
}
}

Atividade 8:
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 pull-down 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
Code
// 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);
}
}

Atividade 9:
Debounce
This example demonstrates how to debounce an 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

Code
/*
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
modified 28 Dec 2012
by Mike Walters

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; // the current reading from the input pin
int lastButtonState = LOW; // 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);

// set initial LED state


digitalWrite(ledPin, ledState);
}

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() - lastDebounceTime) > debounceDelay) {


// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:

// if the button state has changed:


if (reading != buttonState) {
buttonState = reading;

// only toggle the LED if the new button state is HIGH


if (buttonState == HIGH) {
ledState = !ledState;
}
}
}

// set the LED:


digitalWrite(ledPin, ledState);

// save the reading. Next time through the loop,


// it'll be the lastButtonState:
lastButtonState = reading;
}

Atividade 10:
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 pull-down 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
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
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; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // 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);
}

Atividade 11:
Input Pullup Serial
This example demonstrates the use of INPUT_PULLUP with pinMode(). It monitors
the state of a switch by establishing serial 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 is not 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 an int 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.
void setup(){
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);
}
}

Atividade 12:
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
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:

#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.
}

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 NOTE_B0 31
#define NOTE_C1 33
#define NOTE_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTE_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTE_B3 247
#define NOTE_C4 262
#define NOTE_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978

Atividade 13:
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
!
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:
void setup() {
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
}

Atividade 14:
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.

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

Schematic
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:
#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);
}
}
}
Atividade 15:
SPlaying 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.

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
!
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:
void setup() {

void loop() {
// turn off tone function for pin 8:
noTone(8);
// 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 8 for 500 ms:
tone(8, 523, 300);
delay(300);
}

Atividade 16:
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);

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.
// 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; // value read from the pot
int outputValue = 0; // 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);
}

Atividade 17:
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 (or another variable resistor like a photosensitive resistor and 10K
resistor)
built-in LED on pin 13

Circuit
With potentiometer
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
Potentiometer
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.
int sensorPin = A0; // select the input pin for the
potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // 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);
}

Atividade 18:
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

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
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.
// 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; // the index of the current
reading
int total = 0; // the running total
int average = 0; // 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
}

Atividade 19:
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. Using Serial.parseInt() to separate the data by commas, read
the information into your variables:
int red = Serial.parseInt();
int green = Serial.parseInt();
int blue = Serial.parseInt();

Once you've read the data into your variables, check for the newline character to
proceed:
if (Serial.read() == '\n') {
Using constrain(), you can keep the values in an acceptable range for PWM control.
This way, if the value was outside the range of what PWM can send, it will be limited
to a valid number. By subtracting this value from 255 you will be formatting the
value to use with a common anode LED. As explained above, these LEDs will
illuminate when there is a voltage difference between the anode and the pin
connected to the 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.
// 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);
}
}
}

Atividade 20:
ASCII Table
Demonstrates the advanced serial printing functions by generating a table of
characters and their ASCII values in decimal, hexadecimal, octal, and binary.

Hardware Required
Arduino Board
Circuit
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++;
}

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

Atividade 21:
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. An example for Processing is shown below.

Hardware Required
Arduino Board
LED
220 ohm resistor

Software Required
Processing

Circuit
An LED connected to pin 9. Use an appropriate resistor as needed. For most common
LEDs, a 220 or 330 ohm resistor will work.

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

Schematic

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
The Processing sketch in the code sample below will send bytes out the serial port to
the Arduino to dim the LED.

// 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);
}

Atividade 22:
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).

Hardware Required
Arduino Board
Analog Sensor (potentiometer, photocell, FSR, etc.)
Software Required
Processing

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

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

Schematic

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

// Graphing sketch

// This program takes ASCII-encoded strings


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

// Created 20 Apr 2005


// Updated 18 Jan 2008
// by Tom Igoe
// This example code is in the public domain.

import processing.serial.*;

Serial myPort; // The serial port


int xPos = 1; // horizontal position of the graph

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

// List all the available serial ports


println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {


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

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

// draw the line:


stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

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


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

*/

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

You might also like