Arduino - Arduino User Guide For Operating System
Arduino - Arduino User Guide For Operating System
This document is geared towards providing exact and reliable information in regards to the
topic and issue covered. The publication is sold with the idea that the publisher is not required to
render accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal
From a Declaration of Principles which was accepted and approved equally by a Committee of
the American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either
electronic means or in printed format. Recording of this publication is strictly prohibited and any
storage of this document is not allowed unless with written permission from the publisher. All rights
reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in
terms of inattention or otherwise, by any usage or abuse of any policies, processes, or directions
contained within is the solitary and utter responsibility of the recipient reader. Under no
circumstances will any legal responsibility or blame be held against the publisher for any reparation,
damages, or monetary loss due to the information herein, either directly or indirectly.
The information herein is offered for informational purposes solely, and is universal as so. The
The trademarks that are used are without any consent, and the publication of the trademark is
without permission or backing by the trademark owner. All trademarks and brands within this book
are for clarifying purposes only and are the owned by the owners themselves, not affiliated with this
document
Contents
Introduction
Chapter.1: USE ARDUINO TO INTERACT AND RUN CODE
Chapter 2: ARDUINO PRODUCTS
Chapter 3: USING THE IMAGECRAFT IDE
Chapter.4: BUILD THE IN-SYSTEM PROGRAMMER USING
ARDUINO
Chapter 5: WORK WITH ARDUINO
Chapter 6: ARDUINO IN HARDWARE INTERFACE
Chapter 7: SOME MORE SPECIAL INFORMATION
Other Recommendations
Free Bonus: Get My Latest Kindle E-Book for Free ($9.99)
Introduction
I want to thank you and congratulate you for purchasing the book,
“Arduino Board Pin Code Examples”.
This book contains proven steps and strategies on how to get your
Arduino board and compile code for projects. You learn how to use the
Arduino for creating interactive devices around the house and build an in-
system programmer. You can work with Arduino and become familiar with
it.
Learn the basics for operating the Arduino board. You can work with
prearranged boards if you are not too good with handling and assembling
electronic components. You also have information on various Arduino hot
selling products that you may use for your personal projects.
Thanks again for purchasing this book, I hope you enjoy it!
Chapter 1
ARDUINO PRODUCTS
Arduino produces boards, accessories, kits and shields. Currently
they have 21 boards, 8 shields, 2 kits and 5 accessories. The boards are
named Arduino Uno, Arduino Yun, Arduino Tre, Arduino Esplora, Arduino
Mega ADK, Arduino Robot, Arduino Mini, LilyPad Arduino Simple, Fio,
Leonardo, LilyPad Arduino, Zero, Micro, Due, Arduino Ethernet, Mega
2560, LilyPad Arduino USB, Gemma, Nano, Arduino Pro Mini and Arduino
Pro.
The shields are Arduino GSM Shield, Arduino WiFi Shield, Arduino
USB Host shield, Arduino Wireless Proto shield, Arduino Ethernet shield,
Arduino Wireless SD shield, Arduino Motor shield and LilyPad Arduino
SimpleSnap.
The kits are the Arduino Starter kit and the Arduino Materia 101.
Accessories available are USB/Serial Light adapter, mini USB/Serial
adapter, TFT LCD screen, Arduino ISP and Arduino Proto shield.
Primo
Primo is an Arduino AtHeart product aimed at teaching children in the
learning phase the basics of programming. This physical interface
programming device teaches children in the age group 4 – 7 years
programming logic. Children will guide a smiling robot to a prescribed
destination by passing on instructions. These instructions are delivered in
the form of colorful blocks with messages. It makes children involve in a
developmental experience that is both exciting and challenging. Children
learn through playing with their Cubetto Playset.
Tsunami
Tsunami is an Arduino AtHeart product signal generator powerful
yet flexible and gives users a way to experiment with projects using analog
signals. It is amazingly straightforward since it combines the Direct Digital
Synthesis chip with Arduino Leonardo. When combined with a software
library that is easy to use and an input-output circuitry that is incredibly
flexible, working with analog signals becomes a snip. Arachnid Labs
designed the Tsunami and is currently in use in over a thousand projects
covering fields like music, design dance, publishing, theater, technology,
photography and fashion. To preorder the Tsunami go here.
Get the individual parts and begin to solder them. You can order your
kit from online stores. You can solder the individual parts on the board and
test it with DM-USB2Serial. Upload the program for the DM-USTYLE
V1.0 DIY version board from the sketch software. Plug the board in and
click on Program Compile and Upload menu.
For those who wish to use the board as an AVR board, you have a
choice of compilers ranging from WINAVR and IAR to CodeVision AVR
and ICC AVR. Normally, users will employ the board ISP to download the
output generated by the compiler. You can use the AD-ISPRO or the AD-
USBISP for doing the download. The former is useful for parallel port type
STK200/300 while the latter proves useful for USB type STK500.
Chapter 3
Compiler
Go to the compiler page in the dialog box and choose the option. In
the list box, click on Output Format and click on Intel HEX. Keep the
box next to the “Accept C++ Comments” checked.
Target
Next click on the target tab. Here you can make options specific to
the target. In this particular tutorial, you have to click on Device
Configuration tab and select 2313. This ImageCraft IDE becomes very
simplified as it as it shows the options that are required alone for the entire
tool chain in the compiler. This will include linker, assembler and compiler.
A simple program will be in use by the application note to increment
PORTB where you have the 8 LEDs attached. One 8-bit timer will generate
delay for each increment. You will now be able to see the lights flashing.
Begin by creating a new file and type:
#include <io2313.h>
void initialization (void);
void delay (void);
Save this file as “avrc031.c” under the File. In addition, you can also
save it to project folder “c:\icctest\First” but this is optional.
For those who need to download the Arduino software go here or use
the links below.
Windows OS Mac OS (10.7
Mountain Lion or later)
Linux 32 bits Release notes
Linux 64 bits
Source Codes Checksums
Check the heartbeat () function. You will see that it says delay
(40). Make it delay (20).
According to the board you use, select items in Serial Port and
Use the figure shown below to wire the Arduino board. (Please
MISO = - VTG
SCK - - MOSI
RST - - GND
ISP6PIN
When you next select the Board under the Tools, it actually
means you are selecting the board on which you intend to burn
the bootloader. It does not mean the board you are currently
(This eBook is written under the Creative Commons Attribution-ShareAlike 3.0 license)
Arduino Yun has slot for micro-SD card, another for micro-USB-connectivity,
then 3 reset-buttons and the UCSP header. The Atheros processor in your Yun
supports Linux distribution OpenWrt-Yun. This allows the users good degree of
computer networking power along with working ease brought by Arduino.
void setup () {
Serial.begin (9600);
while (!Serial)
Serial.println("Starting bridge...\n");
pinMode(13,OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready
delay(2000);
}
New process is initialized in loop (). This will run the check script for the
WiFi. Script is run when you call runShellCommand () after setting path to script.
void loop () {
Process wifiCheck;
wifiCheck.runShellCommand ("/usr/bin/pretty-wifi-info.lua");
Check the characters returned to serial monitor by the script. After a few
seconds, run it again.
Serial.println();
delay(5000);
}
/*
Status of WiFi
#include <Process.h>
void setup() {
Serial.begin(9600); // initialize serial communication
while(!Serial); // do nothing until the serial monitor is opened
Serial.println("Starting bridge...\n");
pinMode(13,OUTPUT);
digitalWrite(13, LOW);
Bridge.begin(); // make contact with the Linux processor
digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready
void loop() {
Process wifiCheck; // initialize a new process
wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // command
you want to run
Serial.println();
delay(5000);
}
This example tells you how to use FileIO classes to write to some file within
filesystem of Yun. First in /tmp a shell script file will be created. Then you
execute it.
FileSystem.begin();
uploadScript ();
}
One more custom function will run your script. This runScript () will execute
every 5 seconds.
void loop () {
runScript ();
delay (5000);
}
Create a file with uploadScript () function. The shell script is created inside
Linux file system. This will check your WiFi interface network traffic. After you
have finished creating the file, you may open it by creating instance of File@
class. You call it by invoking FileSystem.open ()@ the precise location where you
create the script is indicated by @. Put the script in /tmp inside RAM. This will
preserve the cycles of read/write that are limited in FLASH memory.
void uploadScript() {
File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE);
script.print("#!/bin/sh\n");
script.print("ifconfig wlan0 | grep 'RX bytes'\n");
script.close(); // close the file
In order to make script executable, you must instantiate some Process.
Now, chmod@ command changes file modes; send chmod@ with filepath and
command. Shell script now will run like an application.
Process chmod;
chmod.begin("chmod"); // chmod: change mode
chmod.addParameter("+x"); // x stays for executable
chmod.addParameter("/tmp/wlan-stats.sh");
chmod.run();
}
Create Process through runScript () function. This will run your script and
then print the result to Serial Monitor. Start the script after creating it by calling
the two functions Process.begin (filepath) along with Process.run ().
void runScript() {
Process myscript;
myscript.begin("/tmp/wlan-stats.sh");
myscript.run();
Now use String function to read and hold output.
while (myscript.available()) {
output += (char)myscript.read();
}
Now get rid of blank spaces that precede or are present at the string end and
then print the output to serial monitor.
output.trim();
Serial.println(output);
Serial.flush();
}
This sketch demonstrates how to write file into the Yún filesystem.
A shell script file is created in /tmp, and it is executed afterwards.
#include <FileIO.h>
void setup() {
// Setup Bridge (needed every time we communicate with the Arduino Yún)
Bridge.begin();
// Initialize the Serial
Serial.begin(9600);
// Setup File IO
FileSystem.begin();
void loop() {
// Run stats script every 5 secs.
runScript();
delay(5000);
}
// this function creates a file into the Linux processor that contains a shell
script
// to check the network traffic of the WiFi interface
void uploadScript() {
// Write our shell script in /tmp
// Using /tmp stores the script in RAM this way we can preserve
// the limited amount of FLASH erase/write cycles
File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE);
// Shell script header
script.print("#!/bin/sh\n");
// shell commands:
// ifconfig: is a command line utility for controlling the network interfaces.
// wlan0 is the interface we want to query
// grep: search inside the output of the ifconfig command the "RX bytes"
keyword
// and extract the line that contains it
script.print("ifconfig wlan0 | grep 'RX bytes'\n");
script.close(); // close the file
// this function run the script and read the output data
void runScript() {
// Run the script and show results on the Serial
Process myscript;
myscript.begin("/tmp/wlan-stats.sh");
myscript.run();
String output = "";
C) HTTP CLIENT
This tutorial will show how to use the Arduino Yun for creating HTTP client.
Using this you can go online and download content. In our example we go to
Arduino website to download any one version of Arduino logo in the form of
ASCII characters.
Code
#include <Bridge.h>
#include <HttpClient.h>
Start Bridge in setup () and ensure serial connection has been made. Then you
can begin the loop ().
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
Serial.begin(9600);
while(!Serial);
}
Create an instance of HTTPClient in loop (). Call the URL of your choice
with client.get (URL) function.
void loop() {
HttpClient client;
client.get("http://arduino.cc/asciilogo.txt");
Check the memory of client buffer server and read bytes to print them in your
serial monitor. Use a cycle of 5 seconds.
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.flush();
delay(5000);
}
The entire code for sketch is given here.
#include <Bridge.h>
#include <HttpClient.h>
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
Serial.begin(9600);
while(!Serial);
}
void loop() {
HttpClient client;
client.get("http://arduino.cc/asciilogo.txt");
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.flush();
delay(5000);
}
II) EXAMPLES FROM COMMUNICATION
In this sketch, we see how to use the Serial.parseInt () function. This helps
you locate values that have alphanumeric character separation. One common
method of representation is the comma-separated-value where comma is made
use of to separate the different pieces of information. You can also use other
characters like period or space for this purpose. You will change the RGB LED
color when you pass strings having values such as “15, 140, 220”. The color
changes because of the parsed values of ints.
Arduino Board
Three 220-ohm resistors
Breadboard
Common anode RGB LED
Hookup wire
To make the circuit shown above, take 5 wires. Use a red wire to connect the
5V pin to one end of one of the long vertical rows present on your breadboard.
Take an RGB LED and check the datasheet in order to identify the pins. To the
LED common anode, connect power rail you created now.
Now use the wires that remain to make connection to pin 5 and green cathode,
pin 3 and red cathode and pin 6 with blue cathode along with resistors. All RGB
LEDs share power pin that is common if they have a common cathode.
Now, make a pin LOW instead of HIGH and across that diode, some voltage
difference will happen. Now, if you send 255 using analogWrite () he LED will
turn off, while the value 0 will turn it on full brightness. In effect, you will call
analogWrite (pin, 255-brightness) instead of analogWrite (pin, 255). There is
nothing complicated in the mathematics.
Serial communication will begin between your computer and Arduino in setup
() at 9600 bits per second. Also, configure the pins to be outputs.
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
You need to make sure that every data present in serial buffer is read. For this
we use while function.
Now you come to the main portion where you note the brightness of the LED,
which is the main serial information. Declare any local variable and use it to store
the value. You separate every value by commas using the Serial.parseInt (). Then
you read information into variables.
if (Serial.read() == '\n') {
In order to maintain PWM control, try to keep values within acceptable range
through constrain (). So, whenever the value lies outside your accepted PWM
range, it will be limited to some particular valid number. If you subtract this from
255 you will format value for use with LED with common anode. You already
know that the LED will light up when there is a difference of voltage between pin
connected for Arduino and anode.
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
Make the entire set of value of LED into one string and send back to serial
monitor.
Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
Lastly, you have to close those brackets from your while statement, if
statement and main loop.
}
}
}
Now that Arduino has been programmed, go back to Serial monitor. Start your
message in a newline and send values for lights between 0 and 255 as: Red,
Green, Blue. Once this is done, LEDs connected will turn to the specified color
and you can read HEX values from Serial monitor.
/*
Reading a serial ASCII-encoded string.
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();
In this example, we see how we send different values from your Arduino
board to the computer. Background color of Max/MSP patch or processing sketch
gives the readings. The potentiometers set blue, green or red components.
Hardware Required
Arduino Board
Breadboard
(3) Analog Sensors (potentiometer,
photocell, FSR, etc.)
Hook-up wire
(3) 10K ohm resistors
Software Required
Processor
Max/MSP version 5
Circuit
Here we have a circuit comprising of force-sensing
resistors. Three sub-circuits that are voltage dividers
generate analog voltages. Analog-Input pins 0, 1, and 2
are connected to the analog sensors. Voltage dividers have
resistors connected in series and according to their value,
they have voltage in each.
Code
Sensor values pass from Arduino to computer as decimal numbers that are
ASCII-encoded. ASCII characters for each number from 0 to 9 are used to pass
the number. For instance, you would get the ASCII bytes value 51, 52 and 56 for
the number 348. (3 has the byte value of 51,…and so on).
/*
This example reads three analog sensors (potentiometers are easiest)
and sends their values serially. The Processing and Max/MSP programs at
the bottom
take those three values and use them to change the background color of the
screen.
The circuit:
* potentiometers attached to analog inputs 0, 1, and 2
http://www.arduino.cc/en/Tutorial/VirtualColorMixer
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(redPin));
Serial.print(",");
Serial.print(analogRead(greenPin));
Serial.print(",");
Serial.println(analogRead(bluePin));
}
import processing.serial.*;
Serial myPort;
void setup() {
size(200, 200);
if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// split the string on the commas and convert the
// resulting substrings into an integer array:
float[] colors = float(split(inString, ","));
// if the array has at least three elements, you know
// you got the whole thing. Put the numbers in the
// color variables:
if (colors.length >=3) {
// map them to the range 0-255:
redValue = map(colors[0], 0, 1023, 0, 255);
greenValue = map(colors[1], 0, 1023, 0, 255);
blueValue = map(colors[2], 0, 1023, 0, 255);
}
}
}
*/
*/
Processing Code
Use code sample above to copy your Processing sketch. When you change the
analog sensor values, the background color will keep changing.
Max Code
You Max Patch will resemble this. Using code sample above, copy its text and
paste to new Max window.
C) DIMMER
Here in this project you will learn what to do to control how bright the LED
shines. You send data as individual bytes in the range 0 to 255. When the Arduino
reads these values, it sets the LED brightness. Arduino takes values from any
software that can communicate with the Arduino through serial port of the
computer. Here we see how it done using Max/MSP version 5 and Processing.
Software Required
Max/MSP version 5 or
Processing
Circuit
Using a suitable resistor connect pin 9 to an LED. For most cases, a 220 to
330 resistor will do fine.
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
http://www.arduino.cc/en/Tutorial/Dimmer
*/
void setup()
{
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness;
import processing.serial.*;
Serial port;
void setup() {
size(256, 150);
// 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);
}
----------begin_max5_patcher----------
1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M
YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjU
vrC
ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBL
XiP
xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK
rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.
W
sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui
FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+ow
v
AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK
z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu
xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqu
eG2
uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j
1Ykj
jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKd
A
4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn9
5Izr
TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS
xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5
KTa6
WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG
2v9
FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ
+zS7
3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo
8qHc
cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ
+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR
7x
D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6J
OZ8
ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS
xqZqbd3ZLdera1iPqYxOm++v7SUSz
-----------end_max5_patcher-----------
*/
Processing Code
Use the connection shown in code sample. This will send the bytes that dim
the LED. Connection is through serial port to Arduino.
Max Code
The Max/MSP patch is shown of the above code sample. You have to copy
and paste it to new window.
LED SHOW
In this tutorial, we learn how to get the values directly
from joystick. The Serial monitor displays output in terms
of RGB LED color.
You can move the joystick along two perpendicular
axes X or Y. Each one of the axes controls one color that
the RGB LED displays – X- axis depicts red while Y –
axis depicts green. Blue element will have its control by
relative position of linear potentiometer.
Arduino Esplora
Circuit
You will not need any circuit for this example.
Code
The brightness of the RGB LED light may be controlled individually through
the Esplora Library functions. The light consists of three colors Red, Green, and
Blue.
writeRed ();
writeBlue ();
writeGreen ();
You may also control all of the colors with one single command using
writeRGB (); Values generated will differ when the joystick moves. You can also
shift the position of the linear potentiometer to create new outputs. One output is
by the serial monitor while the other you see as the RGB LED light.
/*
Esplora LED Show
Makes the RGB LED bright and glow as the joystick or the
slider are moved.
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
// read the sensors into variables:
int xAxis = Esplora.readJoystickX();
int yAxis = Esplora.readJoystickY();
int slider = Esplora.readSlider();
This is a fun filled project where you can race your robot against others. The
means of controlling your robot is by a line drawn on a large paper. Your robot
will search for the line and then it will follow it. Think of the fun you can have
when you have more robots!
Procedure
1. Make tracks for the robot. These tracks will go winding on a piece of
paper. They have to be 1 inch (about 2 ½ cm) thick. The line must not
intersect and the end of the line must join the starting point. Join
several pieces of paper if the track area is not big enough.
2. Not fix the paper to the ground with some tape. This will prevent it
from slipping when the robot runs around on it. Try to keep the surface
light in color.
3. Upload the code, unplug the USB and switch on power.
4. Put the robot on the ground such that it is facing the line.
5. For the first few trials (starting screen), the robot will make the
calibrations required and then it will orient itself to detect the line.
6. Once the robot detects the line, it will carry on following it without
stop. For more details on calibration check up lineFollowConfig.
Try to run it
Now your robot is ready to race!
Code
/* Robot Line Follow
This sketch demonstrates the line following capabilities of the Arduino Robot.
On the floor, place some black electrical tape along the path you wish the robot to
follow. To indicate a stopping point, place another piece of tape perpendicular to
the path.
Circuit:
* Arduino Robot
void setup() {
// initialize the Robot, SD card, display, and speaker
Robot.begin();
Robot.beginTFT();
Robot.beginSD();
Robot.beginSpeaker();
// These are some general values that work for line following
// uncomment one or the other to see the different behaviors of the robot
//Robot.lineFollowConfig(14, 9, 50, 10);
Robot.lineFollowConfig(11, 7, 60, 5);
// start
Robot.fill(255, 255, 255);
Robot.stroke(255, 255, 255);
Robot.rect(0, 0, 128, 80); // erase the previous text
Robot.stroke(0, 0, 0);
Robot.text("Start", 5, 5);
Robot.stroke(0, 0, 0);
Robot.text("Done!", 5, 45);
}
void loop() {
//nothing here, the program only runs once. Reset the robot
//to do it again!
}
Working Principle
Robot senses the ground beneath it with five sensors. Light reflects back to
the sensors. In order to detect the line, the wheels of the robot must turn. This it
does when it does not detect any line and all five sensors produce white light.
Stopping
When the robot detects black in all five sensors, it will stop. This is the
method to stop the robot.
In this tutorial, we will see what goes into the creation of an Arduino library.
First, we write a sketch that will flash Morse code and then use the function to
create the library. This way, people can easily use your code and update it. It will
help the library to improve. You will get more information in API Style Guide.
Let us begin with the simple sketch that does the Morse code.
void setup()
{
pinMode(pin, OUTPUT);
}
void loop()
{
dot(); dot(); dot();
dash(); dash(); dash();
dot(); dot(); dot();
delay(3000);
}
void dot()
{
digitalWrite(pin, HIGH);
delay(250);
digitalWrite(pin, LOW);
delay(250);
}
void dash()
{
digitalWrite(pin, HIGH);
delay(1000);
digitalWrite(pin, LOW);
delay(250);
}
The code above when run will flash the distress code SOS through pin 13. The
sketch does not have any significantly different parts other than the functions dot
() and dash (), which of course do the actual blinking. Now, the functions use the
ledPin () variable that will tell functions, which pin to use. Finally, one has the
pinMode () a call to initialize pin as output. You have started your library from the
sketch!
Every library has at least two files – the header file that has extension .h and
source file having extension .cpp. Header file comprises of definitions stating
everything that the library contains. Source file comprises of the actual code. Let
us name our library Morse. This will make our header file Morse.h…should be
interesting to see its contents. You will find it difficult to understand it all at the
beginning, but it will get easier as you go along.
Header file core will be made of one line representation for every function in
the library. It is represented in class together with any variables you might need.
class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
To understand class, you need to think of it as function collection alongside
variables where you can easily access it. When this agglomeration can be
accessed by anyone using the library, it is termed public. When it is private, it can
only be accessed from within that class alone.
Special function constructor exists within a class to help create instance of the
class. Name of the constructor will remain the same as the class name but it will
not have return value.
To complete the header file, you will also need #include statement in order to
let you access constants and standard types in Arduino language. In sketches, this
is normally included but it is not in libraries. This is how you write it.
#include "Arduino.h"
#ifndef Morse_h
#define Morse_h
#endif
This helps you avert problems like repetition as it happens with two #includes.
You round up your library by putting a comment on top of it. This will tell what is
present, the library name, name of author, the date and license.
/*
Morse.h - Library for flashing Morse code.
Created by David A. Mellis, November 2, 2007.
Released into the public domain.
*/
#ifndef Morse_h
#define Morse_h
#include "Arduino.h"
class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
#endif
Let us now see what goes into the making of the source file – the Morse.cpp.
You begin with include statements that give the code you write access to Arduino
standard functions as defined inside in the library.
#include "Arduino.h"
#include "Morse.h"
After this, you make constructors. This lets users choose specific instances of
classes. They do this by choosing a pin that is configured as an output.
In these lines of code, you will notice that there is a slightly different
convention of naming. One is the :: operator, which is the scope operator. It gives
a global visibility to the chosen variable. Another change you see is the
underscore that is assigned before the pin class. Adding underscore helps you
name a class or variable without breaking the naming convention. You get a
clearer view of your code and help you group all those classes you want with
underscore so that you can work easier. For instance, you may need some group
to be private. You can add underscore in front of their class names. Now, proceed
with the code for the library.
void Morse::dot()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
void Morse::dash()
{
digitalWrite(_pin, HIGH);
delay(1000);
digitalWrite(_pin, LOW);
delay(250);
}
You then round off your code by writing the comment on top. It helps you
understand what you have written.
/*
Morse.cpp - Library for flashing Morse code.
Created by David A. Mellis, November 2, 2007.
Released into the public domain.
*/
#include "Arduino.h"
#include "Morse.h"
Morse::Morse(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
}
void Morse::dot()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
void Morse::dash()
{
digitalWrite(_pin, HIGH);
delay(1000);
digitalWrite(_pin, LOW);
delay(250);
}
Now that you have written the code, you must know how to access and use it.
Begin by making a Morse directory in the library subdirectory in your sketch.
Copy Morse.h along with Morse.cpp files and do the Arduino environment
launch. It means just open the Arduino and then go to Sketch>Import Library
menu. Here you will find Morse inside.
#include <Morse.h>
Morse morse(13);
void setup()
{
}
void loop()
{
morse.dot(); morse.dot(); morse.dot();
morse.dash(); morse.dash(); morse.dash();
morse.dot(); morse.dot(); morse.dot();
delay(3000);
}
Let us see what differences exist after we made the duplication. First thing to
notice is the #include statement at the top. Doing this includes this sketch in code
that will be sent to the board and make the library accessible to the sketch. You do
not have to include library. Delete the #include statement for library to save space.
Next, you can see a new instance of Morse class has been created named morse.
During the execution process, the constructor class is called even before setup
() function and it will be given an argument, 13 in this example. The setup () will
not have anything because the call taking place to the pinMode () occurs within
the library.
In a similar fashion, we need to prefix morse in order to call the functions dot
() and dash (). For each instance of Morse class, you can add the pin and store it
in the private variable _pin. When we call some particular instance of any
function, we are specifying exactly what the variable should be for that instance
for the duration of the call. So, if we had:
Morse morse(13);
Morse morse2(12);
a call to morse2.dot () would have the value 12. You might notice too that
Arduino does not automatically recognize your definitions in the library and
update the environment and color. In order to do this, you make use of
keywords.txt file that you create within that Morse directory.
Morse KEYWORD1
dash KEYWORD2
dot KEYWORD2
Each class you mention is written in this way. Name of the class and the
keyword you assign to it. Then use a tab without space to go to next class. Here
again you write the next keyword and so on. KEYWORD1 will all have orange
color while the KEYWOR2 will take up brown color. Restart Arduino
environment and the new keywords will take effect.
Now if you plan to include working examples within your sketch, do place
example directory within Morse directory. Now, move the sketch (say SOS) to the
examples directory. It is easy to negotiate to this by pulling down Sketch>Show
Sketch Folder.
Again restart Arduino and you will see Library-Morse inside
File>Sketchbook>Examples. You can use comments to explain what your
example does. You can download Arduino for your operating system.
Circuit
Piezos have polarized structures. This allows current to pass through them in
one direction only. Make a connection with the black wire (lower voltage) to the
ground and the higher voltage red wire to the 0 analog pin. In order to limit
voltage/current produced by piezo, use a 1-megohm resistor in parallel. If
possible, get piezo elements that do not have plastic coverings. Now tape the bare
metallic body to the surface you want to take the reading from.
(Fritzing develops these images.)
Schematic
1-Megohm resistor connected to piezo at pin 0
Code
User sets a threshold and studies data generated by the piezo element. One can
change the threshold value to modify the sensitivity of the element.
/* Knock Sensor
You can use this sketch to detect knocking sound with a piezo element.
Reading from the analog pin compares results that user predetermines for some
threshold. When the result shows bigger value, ‘knock’ will be written to serial
port and the pin 13 LED will be toggled.
Details of circuit:
In analog at 0 piezo positive connection is attached
Ground attaches to – piezo connection
1-megohm connected between ground and 0 in analog
http://www.arduino.cc/en/Tutorial/Knock
*/
void loop() {
// read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor);
Here millis () returns long integer, which may be added to any string. You can
write the code like this too.
In the last, analogRead () returns integer that can be added to string. This kind
of concatenation proves useful in situations where you need to display more than
one value as in LCD displays for advertising products. They need to display the
price and details including the name and packaging weight.
This will give you some sensor value output. However, if you run the code
below, it will not give you any valid output.
The result will be unpredictable since you have not initially given value to
stringThird. Check another kind of improper initialization here.
The operator precedence is wrong and so the code will not compile. The
following example will compile but the results will not be what are expected.
The reason for the error is again clear. The stringThird never was initialized.
Code
Here is the code for several examples of concatenation types.
/*
Adding Strings together
http://arduino.cc/en/Tutorial/StringAdditionOperator
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
}
void loop() {
// adding a constant integer to a string:
stringThree = stringOne + 123;
Serial.println(stringThree); // prints "stringThree = 123"
You can make comparisons between various strings using operators for String
comparison such as equals () or equalIgnoresCase () and ==, <=, >, !=, >=, <.
Sorting and sequencing are important activities when creating databases.
Many functions are interchangeable such as equals () and == operators. You
may use either one since the answer will be the same. That is why you will that:
if (stringOne.equals(stringTwo)) {
if (stringOne ==stringTwo) {
Greater than and less than operators will check the first alphabet or number in
the string. This is why you get "a" < "b" and "1" < "2", but "999"> "1000"
because 9 comes after 1.
Take note: When you use operators for string comparison, do not think the
strings as numbers. If you want mathematical values, you have to use variable
such as floats, ints.
/*
Comparing Strings
by Tom Igoe
http://arduino.cc/en/Tutorial/StringComparisonOperators
*/
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
stringOne = String("this");
stringTwo = String("that");
// send an intro:
Serial.println("\n\nComparing Strings:");
Serial.println();
void loop() {
if (stringOne == "this") {
Serial.println("StringOne == \"this\"");
stringOne = "This";
stringTwo = "this";
if (stringOne != stringTwo) {
// you can also use equals() to see if two strings are the same:
if (stringOne.equals(stringTwo)) {
else {
if (stringOne.equalsIgnoreCase(stringTwo)) {
}
else {
stringOne = "1";
int numberOne = 1;
if (stringOne.toInt() == numberOne) {
stringOne = "2";
stringTwo = "1";
}
// comparison operators can be used to compare strings for alphabetic sorting too:
stringOne = String("Brown");
stringOne = "Cucumber";
stringTwo = "Cucuracha";
if (stringOne.compareTo(stringTwo) < 0 ) {
else {
}
delay(10000); // because the next part is a loop:
// compareTo() is handy when you've got strings with numbers in them too:
while (true) {
stringOne += analogRead(A0);
stringTwo += analogRead(A5);
if (stringOne.compareTo(stringTwo) < 0 ) {
else {
}
Chapter 6
ARDUINO IN HARDWARE
INTERFACE
Arduino comes into play for interfacing devices that are used as
input, output or user interfaces. They also help devices used in
communication and an ISP programmer. In order to use the kit or assemble
it, you have to be aware of the full capabilities of this revolutionary
computing device.
See all that is possible and begin a project that interests you. They
help in governing physical systems and in regulating the audio systems.
You can use them in multiplexing and controlling and distributing electrical
power. They are used as input devices in power, audio and automobiles.
Specific examples for each of these are given here. Scientists use
them in environmental sciences and distance sensing devices. Other uses
include their use in human interfacing, game controllers, keypads and light
sensors. Here we are going to see how to use the Arduino for some basic
functions.
Arduino board
An LED
Select the 9 pin of your Arduino and solder a 220 ohm resistor to it.
Connect the other end of the resistor to anode the positive leg of your LED.
The shorter cathode leg in the LED should be directly connected to the
ground. Now to write the code.
First declare the ledPin is your 9 pin. This will be all there is in your
setup () portion of the code. Next comes the analog write () function. Here
you need to pass two functions – one that tells which pin it has to write to
and one that tells what PWM value it has to write.
To make the LED fade off, you need to increase the PWM value that is
at 0 all the way to 255. Now decrease the value all the way back to 0. You
can use any variable to change the PWM value. In this example, we use
fullOrOff. For each loop, the increment is done by a variable goDark.
When the fullOrOff is at one end of the value scale, either 0 or 255, the
goDark value is changed to negative. This means that if the fullOrOff is at
10, then goDark is assigned -10 and if it reaches 250, then the goDark value
is given +10 value. The analogWrite will do the steps very fast. To control
the speed of your fade, you use delay at the sketch end. To see the
difference actually, change the delay value and check how the program
responds. Here is the program.
/*
Fade
You will see in this example how you fade the LED on the pin 9
You use the analogWrite () function
You are reading the function written in public domain.
*/
void setup () {
In this example too we use the same material as before. You can use
220 Ω to 1000 Ω resistance. You may sometimes find that the LED is
already attached to your Arduino board. Otherwise, solder the LED to the
13 pin like before.
Now the voltage in pin 13 drops back to zero and the LED light will
switch off. If you want to really appreciate the work your program does, set
the delay for 1000 milliseconds. During this period, nothing happens. Take
a look at the program:
/*
Blink
You will see a repeat of this cycle – ON for one second, OFF the other
You are reading this example code written expressly in the public domain
*/
Momentary button
Breadboard
Arduino board
10K Ω resistor
Hook-up wire
When the button is not depressed, the connection between the legs
of the button remains open. The pin has connection only to the ground and
so it returns the LOW reading. When you press the button down, the
reading now goes to 5V and so you get a HIGH reading.
/*
Button
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
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
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);
D) Simple Keyboard
This example will see the use of the tone function. Tone () command
will generate sounds with different pitches. Here you will need the
following material.
3 numbers force-resisting sensors
Hook up wire
8 Ω speaker
Breadboard
http://arduino.cc/en/Tutorial/Tone3
*/
#include "pitches.h"
const int threshold = 10; // minimum reading of the sensors that generates
a note
void setup() {
}
void loop() {
for (int thisSensor = 0; thisSensor < 3; thisSensor++) {
// get a sensor reading:
int sensorReading = analogRead(thisSensor);
You will see that there is a file pitches.h that contains all the pitches
for each note. The notes are denoted by their key and a number according to
the ascending of the pitch. This table was originally made by Brett
Hagmann who is famous for his work that resulted in the tone () function.
You have to make a new tab and past the following code to make the file.
/*************************************************
* 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
void setup ()
Serial.begin(9600);
pinMode(ultraSoundSignal, OUTPUT);
}
unsigned long ping(){
return ultrasoundValue;
}
void loop()
int x = 0;
x = ping();
Serial.println(x);
#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the
ultrasonic sensor.
void setup() {
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance
and print result (0 = outside set distance range, no ping echo)
Serial.println("cm");
}
Chapter 7
files, then you are obliged to resubmit the modified files under
the same Creative Commons Attribution share-Alike license.
The GPL covers the Arduino environment and this does not limit
You can use the libraries and the Arduino core without being
under LGPL and make available object files which you use for