Sunteți pe pagina 1din 27

Arduino

Guide to the Arduino Leonardo and Micro


To connect the Arduino Leonardo or Micro to your computer, you'll need a Micro-B USB
cable. This USB cable provides power and data to the board. When programming the
Leonardo, you must choose Arduino Leonardo" or "Arduino Micro from the Tools >
Board menu in the Arduino IDE.

Differences from the Arduino Uno


o

Single processor for sketches and USB communication.

Serial re-enumeration on reset.

No reset when you open the serial port.

Keyboard and mouse emulation.

Separation of USB and serial communication.

Differences in pin capabilities.

Installing Drivers for the Leonardo and Micro


o

OSX

Instructions for Windows


o

Linux

Uploading Code to the Leonardo and Micro

Good Coding Practice With the Leonardo and Micro

Differences from the Arduino Uno

In general, you program and use the Leonardo and Micro as you would other Arduino boards.
There are, however, a few important differences.
Single processor for sketches and USB communication.

The Leonardo and Micro differ from other Arduino boards in that they use a single
microcontroller to both run your sketches and for USB communication with the computer.
The Uno and other boards use separate microcontrollers for these two functions, meaning that
the USB connection to the computer remains established regardless of the state of the main
microcontroller. By combining these two functions onto a single processor, the Leonardo
allows for more flexibility in its communication with the computer. It also helps to lower the
cost of the board by removing the need for an additional processor.

Serial re-enumeration on reset.

Since the boards do not have a dedicated chip to handle serial communication, it means that
the serial port is virtual -- it's a software routine, both on your operating system, and on the
board itself. Just as your computer creates an instance of the serial port driver when you plug
in any Arduino, the Leonardo/Micro creates a serial instance whenever it runs its bootloader.
The board is an instance of USB's Connected Device Class (CDC) driver.
This means that every time you reset the board, the USB serial connection will be broken and
re-established. The board will disappear from the list of serial ports, and the list will reenumerate. Any program that has an open serial connection to the Leonardo will lose its
connection. This is in contrast to the Arduino Uno, with which you can reset the main
processor (the ATmega328P) without closing the USB connection (which is maintained by
the secondary ATmega8U2 or ATmega16U2 processor). This difference has implications for
driver installation, uploading, and communication; these are discussed below.
No reset when you open the serial port.

Unlike the Arduino Uno, the Leonardo and Micro won't restart your sketch when you open a
serial port on the computer. That means you won't see serial data that's already been sent to
the computer by the board, including, for example, most data sent in the setup() function.
This change means that if you're using any Serial print(), println() or write() statments in your
setup, they won't show up when you open the serial monitor. To work around this, you can
check to see if the serial port is open after calling Serial.begin() like so:
Serial.begin(9600);
// while the serial stream is not open, do nothing:
while (!Serial) ;
[Get Code]
Keyboard and mouse emulation.

One advantage of using a single chip for your sketches and for USB is increased flexibility in
the communication with the computer. While the board appears as a virtual serial port to your
operating system (also called CDC) for programming and communication (as with the
Arduino Uno), it can also behave as a (HID) keyboard or mouse. See the "Good Coding
Practice" section below for a warning about using this functionality.
Separation of USB and serial communication.

On the Leonardo and Micro, the main Serial class refers to the virtual serial driver on the
board for connection to your computer over USB. It's not connected to the physical pins 0
and 1 as it is on the Uno and earlier boards. To use the hardware serial port (pins 0 and 1, RX
and TX), use Serial1. (See the Serial reference pages for more information.)
Differences in pin capabilities.

The Leonardo has some slight differences in the capabilities and assignments of various pins
(especially for SPI and TWI). These are detailed on the hardware page.

Installing Drivers for the Leonardo and Micro


OSX

The first time you plug a Leonardo or Micro into a Mac, the "Keyboard
Setup Assistant" will launch. There's nothing to configure with the
Leonardo, so you can close this dialogue by clicking the red button in the
top left of the window.

Instructions for Windows

The following instructions are for Windows 7. They are valid also for Windows XP, with
small differences in the dialog windows.

Plug in your board and wait for Windows to begin its driver installation
process. If the installer does not launch automatically, navigate to the
Windows Device Manager (Start>Control Panel>Hardware) and find the
Arduino Leonardo listing. Right click and choose Update driver.

At the next screen, choose "Browse my computer for driver software", and
click Next.

Click the Browse... button. Another dialog appears: navigate to the folder
with the Arduino software that you just downloaded. Select the drivers
folder an click OK, then click Next.

You will receive a notification that the board has not passed Windows Logo
testing. Click on the button Continue Anyway.

After a few moments, a window will tell you the wizard has finished
installing software for Arduino Leonardo. Press the Close button.

Linux

There is no need to install drivers for Ubuntu 10.0.4


Uploading Code to the Leonardo and Micro

In general, you upload code to the Leonardo or Micro as you would with the Uno or other
Arduino boards. Click the upload button in the Arduino IDE and your sketch will be
automatically uploaded onto the board and then started. This works more or less the same
way as with the Uno: the Arduino software initiates a reset of the board, launching the
bootloader - which is responsible for receiving, storing, and starting the new sketch.
However, because the serial port is virtual, it disappears when the board resets, the Arduino
software uses a different strategy for timing the upload than with the Uno and other boards.
In particular, after initiating the auto-reset of the Leonardo or Micro (using the serial port
selected in the Tools > Serial Port menu), the Arduino software waits for a new virtual
(CDC) serial / COM port to appear - one that it assumes represents the bootloader. It then
performs the upload on this newly-appeared port.

These differences affect the way you use the physical reset button to perform an upload if the
auto-reset isn't working. Press and hold the reset button on the Leonardo or Micro, then hit
the upload button in the Arduino software. Only release the reset button after you see the
message "Uploading..." appear in the software's status bar. When you do so, the bootloader
will start, creating a new virtual (CDC) serial port on the computer. The software will see that
port appear and perform the upload using it. Again, this is only necessary if the normal
upload process (i.e. just pressing the uploading button) doesn't work. (Note that the auto-reset
is initiated when the computer opens the serial port at 1200 baud and then closes it; this won't
work if something interferes with the board's USB communication - e.g. disabling interrupts.)
Good Coding Practice With the Leonardo and Micro

A word of caution on using the USB Mouse and Keyboard Libraries: if the Mouse or
Keyboard library is constantly running, it will be difficult to program your board. Functions
such as Mouse.move() and Keyboard.print() will move your cursor or send keystrokes to a
connected computer and should only be called when you are ready to handle them. It is
recommended to use a control system to turn this functionality on, like a physical switch or
only responding to specific input you can control. When using the Mouse or Keyboard
library, it may be best to test your output first using Serial.print(). This way, you can be sure
you know what values are being reported. Refer to the Mouse and Keyboard examples for
some ways to handle this.
Using the serial monitor effectively: Since serial is going through only one processor, the
board is capable of filling your computer's serial buffer faster than the Uno or earlier boards.
You may notice that if you send serial continually, for example like this:
void loop() {
int sensorReading = analogRead(A0);
Serial.println(sensorReading);
}
[Get Code]

the Serial Monitor in the IDE slows down considerably as it tries to keep up. If you encounter
this, add a short delay to your loop so that the computer's serial buffer is not filled as fast.
Even a millisecond delay will help:
void loop() {
int sensorReading = analogRead(A0);
Serial.println(sensorReading);
delay(1);
}
[Get Code]

Serial applications using native libraries other than RXTX library read the serial buffer faster,
so you may not encounter this error much outside of the Serial Monitor, Processing, or other
RXTX-based serial applications
For more details on the Arduino Leonardo and Micro, see the Leonardo hardware page and
Micro hardware page. For additional information on the USB capabilities, see the Mouse and
Keyboard reference pages.

Language Reference
Arduino programs can be divided in three main parts: structure, values (variables and
constants), and functions.

Structure

setup()

loop()

Control Structures
if

if...else

for

switch case

while

do... while

break

Functions

Constants
HIGH | LOW

Digital I/O
pinMode()

INPUT | OUTPUT |
INPUT_PULLUP

digitalWrite()

digitalRead()

LED_BUILTIN

true | false

integer constants

analogRead()

floating point
constants

analogWrite() PWM

Data Types
void

boolean

char

unsigned char

byte

int

{} (curly braces)

unsigned int

// (single line
comment)

word

long

continue

Analog I/O
analogReference()

Due only
analogReadResolut
ion()

analogWriteResolut
ion()

return
goto

Further Syntax
; (semicolon)

Variables

/* */ (multi-line

Advanced I/O
tone()

noTone()

shiftOut()

shiftIn()

pulseIn()

Time

comment)

unsigned long

millis()

#define

short

micros()

#include

float

delay()

double

delayMicroseconds
()

string - char array

Arithmetic Operators
= (assignment
operator)

Math

+ (addition)

String - object

min()

- (subtraction)

array

max()

* (multiplication)

abs()

/ (division)

constrain()

% (modulo)

map()

pow()

sqrt()

Comparison Operators
== (equal to)

Conversion
char()

byte()

int()

word()

!= (not equal to)

long()

< (less than)

float()

> (greater than)

<= (less than or


equal to)

>= (greater than


or equal to)

Boolean Operators
&& (and)

|| (or)

! (not)

Pointer Access
Operators
* dereference
operator

& reference
operator

Variable Scope &


Qualifiers
variable scope

static

volatile

const

cos()

tan()

Random Numbers
randomSeed()

Utilities

Trigonometry
sin()

sizeof()

random()

Bits and Bytes


lowByte()

highByte()

bitRead()

bitWrite()

bitSet()

bitClear()

Bitwise Operators
& (bitwise and)

| (bitwise or)

^ (bitwise xor)

~ (bitwise not)

<< (bitshift left)

>> (bitshift right)

Compound Operators
++ (increment)

-- (decrement)

+= (compound
addition)

-= (compound
subtraction)

*= (compound
multiplication)

/= (compound
division)

&= (compound
bitwise and)

|= (compound
bitwise or)

Actionare Servomotor
Cod Sursa

#include "Servo.h"
Servo myservo;
int pos = 0;
void setup()
{

bit()

External Interrupts
attachInterrupt()

detachInterrupt()

Interrupts
interrupts()

noInterrupts()

Communication
Serial

Stream

USB (Leonardo and


Due only)
Keyboard

Mouse

myservo.attach(9);
}
void loop()
{
for(pos = 10; pos < 150; pos += 1)
{
myservo.write(pos);
delay(15);
}
for(pos = 150; pos>=10; pos-=1)
{
myservo.write(pos);
delay(15);
}
}

Processing

Getting Started. Welcome to Processing!


This tutorial is for Processing 2+. If you see any errors or have comments, please let us know. This
tutorial was adapted from the book, Getting Started with Processing, by Casey Reas and Ben Fry,
O'Reilly / Make 2010.

Start by visiting http://processing.org/download and selecting the Mac, Windows, or Linux version,
depending on what machine you have. Installation on each machine is straightforward:

On Windows, you'll have a .zip file. Double-click it, and drag the folder inside to a location on
your hard disk. It could be Program Files or simply the desktop, but the important thing is for
the processing folder to be pulled out of that .zip file. Then double-click processing.exe to
start.

The Mac OS X version is also a .zip file. Double-click it and drag the Processing icon to the
Applications folder. If you're using someone else's machine and can't modify the Applications
folder, just drag the application to the desktop. Then double-click the Processing icon to start.

The Linux version is a .tar.gz file, which should be familiar to most Linux users. Download the
file to your home directory, then open a terminal window, and type:
tar

xvfz

processing-xxxx.tgz

(Replace xxxx with the rest of the file's name, which is the version number.) This will create a
folder named processing-2.0 or something similar. Then change to that directory:
cd

and

processing-xxxx

run

it:

./processing

With any luck, the main Processing window will now be visible. Everyone's setup is different, so if the
program didn't start, or you're otherwise stuck, visit the troubleshooting page for possible solutions.

The Processing Development Environment.

Your First Program


You're now running the Processing Development Environment (or PDE). There's not much to it; the
large area is the Text Editor, and there's a row of buttons across the top; this is the toolbar. Below the
editor is the Message Area, and below that is the Console. The Message Area is used for one line
messages, and the Console is used for more technical details.
In the editor, type the following:
ellipse(50, 50, 80, 80);

This line of code means "draw an ellipse, with the center 50 pixels over from the left and 50 pixels
down from the top, with a width and height of 80 pixels." Click the Run button, which looks like this:

If you've typed everything correctly, you'll see this appear in the Display Window:

If you didn't type it correctly, the Message Area will turn red and complain about an error. If this
happens, make sure that you've copied the example code exactly: the numbers should be contained

within parentheses and have commas between each of them, and the line should end with a
semicolon.
One of the most difficult things about getting started with programming is that you have to be very
specific about the syntax. The Processing software isn't always smart enough to know what you mean,
and can be quite fussy about the placement of punctuation. You'll get used to it with a little practice.
Next, we'll skip ahead to a sketch that's a little more exciting. Delete the text from the last example,
and try this:

void setup() {

size(480, 120);

void draw() {

if (mousePressed) {

fill(0);

} else {

fill(255);

ellipse(mouseX, mouseY, 80, 80);

This program creates a window that is 480 pixels wide and 120 pixels high, and then starts drawing
white circles at the position of the mouse. When a mouse button is pressed, the circle color changes to
black. We'll explain more about the elements of this program in detail later. For now, run the code,
move the mouse, and click to experience it.

Show
So far we've covered only the Run button, though you've probably guessed what the Stop button next
to it does:

If you don't want to use the buttons, you can always use the Sketch menu, which reveals the shortcut
Ctrl-R (or Cmd-R on the Mac) for Run. Below Run in the Sketch menu is Present, which clears the rest
of the screen to present your sketch all by itself:

You can also use Present from the toolbar by holding down the Shift key as you click the Run button.

Save
The next command that's important is Save. It's the downward arrow on the toolbar:

You can also find it under the File menu. By default, your programs are saved to the "sketchbook,"
which is a folder that collects your programs for easy access. Clicking the Open button on the toolbar
(the arrow pointing up) will bring up a list of all the sketches in your sketchbook, as well as a list of
examples that are installed with the Processing software:

It's always a good idea to save your sketches often. As you try different things, keep saving with
different names, so that you can always go back to an earlier version. This is especially helpful if no,
when something breaks. You can also see where the sketch is located on the disk with Show Sketch
Folder under the Sketch menu.
You can also create a new sketch by pressing the New button on the toolbar:

Share
Another theme of Processing is sharing your work. The Export Application button on the toolbar:

will bundle your code into an application for your choice of Mac, Windows, or Linux depending on
which platform you are using. This is an easy way to make self-contained, double-clickable versions of
your projects.
You can also find Export Application under the File menu.
In addition to exporting your code as applications, you can switch to a different mode within
Processing to export to other platforms. For example, download and change to JavaScript Modeto
export HTML5 Canvas and WebGL. Change to Android mode to export application for Android
phones and tablets. These modes both need to be added before they can be used. Select "Add Mode..."
from the menu that says "Java" in the upper-right corner of the Processing Development
Environment.

Examples and Reference


Learning how to program with Processing involves exploring lots of code: running, altering, breaking,
and enhancing it until you have reshaped it into something new. With this in mind, the Processing
software download includes dozens of examples that demonstrate different features of the software.
To open an example, select Examples from the File menu or click the Open icon in the PDE. The
examples are grouped into categories based on their function, such as Form, Motion, and Image. Find
an interesting topic in the list and try an example.
If you see a part of the program you're unfamiliar with that is colored orange (this means it's a part of
Processing), select its name, and then click on "Find in Reference" from the Help menu. You can also
right-click the text (or Ctrl-click on a Mac) and choose Find in Reference from the menu that appears.
This will open the reference for the selected code element in your web browser. The reference is also
available online.
The Processing Reference explains every code element with a description and examples. The reference
programs are much shorter (usually four or five lines) and easier to follow than the longer code found
in the Examples folder. We recommend keeping the reference open while you're reading this book and
while you're programming. It can be navigated by topic or alphabetically; sometimes it's fastest to do a
text search within your browser window.
The reference was written with the beginner in mind; we hope that we've made it clear and
understandable. We're grateful to the many people who've spotted errors over the years and reported
them. If you think you can improve a reference entry or you find a mistake, please let us know by
clicking on the link at the top of each reference page.

Coordinate System and Shapes


This tutorial is for Processing version 1.1+. If you see any errors or have comments,
please let us know. This tutorial is from the book, Learning Processing, by Daniel
Shiffman, published by Morgan Kaufmann Publishers, Copyright 2008 Elsevier Inc. All
rights reserved.

Coordinate Space
Before we begin programming with Processing, we must first channel our eighth grade
selves, pull out a piece of graph paper, and draw a line. The shortest distance between
two points is a good old fashioned line, and this is where we begin, with two points on
that

graph

paper.

The above figure shows a line between point A (1,0) and point B (4,5). If you wanted to
direct a friend of yours to draw that same line, you would give them a shout and say
"draw a line from the point one-zero to the point four-five, please." Well, for the moment,
imagine your friend was a computer and you wanted to instruct this digital pal to display
that same line on its screen. The same command applies (only this time you can skip the
pleasantries and you will be required to employ a precise formatting). Here, the
instruction will look like this:
line(1,0,4,5);

Even without having studied the syntax of writing code, the above statement should
make a fair amount of sense. We are providing a command (which we will refer to as a
"function") for the machine to follow entitled "line." In addition, we are specifying some
arguments for how that line should be drawn, from point A (1,0) to point B (4,5). If you
think of that line of code as a sentence, the function is a verb and the arguments are the
objects of the sentence. The code sentence also ends with a semicolon instead of a
period.

The key here is to realize that the computer screen is nothing more than a fancier piece
of graph paper. Each pixel of the screen is a coordinate - two numbers, an "x" (horizontal)
and a "y" (vertical) - that determines the location of a point in space. And it is our job to

specify

what

shapes

and

colors

should

appear

at

these

pixel

coordinates.

Nevertheless, there is a catch here. The graph paper from eighth grade ("Cartesian
coordinate system") placed (0,0) in the center with the y-axis pointing up and the x-axis
pointing to the right (in the positive direction, negative down and to the left). The
coordinate system for pixels in a computer window, however, is reversed along the yaxis. (0,0) can be found at the top left with the positive direction to the right horizontally
and
down
vertically.

Simple Shapes
The vast majority of the programming examples you'll see with Processing are visual in
nature. These examples, at their core, involve drawing shapes and setting pixels. Let's
begin

by

looking

at

four

primitive

shapes.

For each shape, we will ask ourselves what information is required to specify the location
and size (and later color) of that shape and learn how Processing expects to receive that
information. In each of the diagrams below, we'll assume a window with a width of 10
pixels and height of 10 pixels. This isn't particularly realistic since when you really start
coding you will most likely work with much larger windows (10x10 pixels is barely a few
millimeters of screen space.) Nevertheless for demonstration purposes, it is nice to work
with smaller numbers in order to present the pixels as they might appear on graph paper
(for

now)

to

better

illustrate

the

inner

workings

of

each

line

of

code.

point() is the easiest of the shapes and a good place to start. To draw a point, we

only

need

an

and

coordinate.

line() isn't terribly difficult either and simply requires two points: (x1,y1) and (x2,y2):

Once we arrive at drawing a rect(), things become a bit more complicated. In


Processing, a rectangle is specified by the coordinate for the top left corner of the
rectangle,

as

well

as

its

width

and

height.

A second way to draw a rectangle involves specifying the centerpoint, along with width
and height. If we prefer this method, we first indicate that we want to use the "CENTER"
mode before the instruction for the rectangle itself. Note that Processing is casesensitive.

Finally, we can also draw a rectangle with two points (the top left corner and the bottom
right

corner).

The

mode

here

is

"CORNERS".

Once we have become comfortable with the concept of drawing a rectangle,


an ellipse() is a snap. In fact, it is identical to rect() with the difference being that an
ellipse is drawn where the bounding box of the rectangle would be. The default mode
for ellipse() is

"CENTER",

rather

than

"CORNER."

It is important to acknowledge that these ellipses do not look particularly circular.


Processing has a built-in methodology for selecting which pixels should be used to create
a circular shape. Zoomed in like this, we get a bunch of squares in a circle-like pattern,
but zoomed out on a computer screen, we get a nice round ellipse. Processing also gives
us the power to develop our own algorithms for coloring in individual pixels (in fact, we
can already imagine how we might do this using "point" over and over again), but for
now, we are content with allowing the "ellipse" statement to do the hard work. (For more
about pixels, start with: the pixels reference page, though be warned this is a great deal
more

advanced

than

this

tutorial.)

Now let's look at what some code with shapes in more realistic setting, with window

dimensions of 200 by 200. Note the use of the size() function to specify the width and
height

size(200,200);

rectMode(CENTER);

rect(100,100,20,100);

ellipse(100,70,60,60);

ellipse(81,70,16,32);

ellipse(119,70,16,32);

line(90,150,80,160);

line(110,150,120,160);

of

the

window.

Serial Port Communications


The Serial library is for reading and writing data to and from external devices one byte at
a time. It allows two computers to send and receive data. This library has the flexibility to
communicate with custom microcontroller devices and to use them as the input or output
to Processing programs. The serial port is a nine pin I/O port that exists on many PCs and
can be emulated through USB.
Issues with the Serial Library and specific platforms are documented on the Processing
Wiki.

Serial
Serial
available()
read()
readChar()
readBytes()
readBytesUntil()
readString()
readStringUntil()
buffer()
bufferUntil()
last()
lastChar()
write()
clear()
stop()
list()

Serial Event
serialEvent()

Using the Serial Port


All Platforms

If you're using a program to check to see if the serial port is working, then it won't be available
to Processing. That means that if you're using HyperTerminal or whatever to see if your serial device
is working, then you need to quit out of that application before using that port with Processing.

Serial.list() will only list the ports that are currently available. So if you have a program that's
using the serial port that you want to use for your Processing sketch, it's not going to be available, or
even listed.

If you get an error reading something like this:

WARNING: RXTX Version mismatch


Jar version = RXTX-2.0-4
native lib Version = RXTX-2.1-7pre17

java.lang.ClassCastException thrown while loading gnu.io.RXTXCommDriver


java.lang.UnsatisfiedLinkError: Native Library /Applications/processing0090/libraries/serial/library/librxtxSerial.jnilib
already
loaded
in
another classloader
then you probably have another copy of RXTX installed somewhere. This is a messy thing to straighten
out, because it could be anywhere in your PATH or CLASSPATH. Search your drive for RXTXcomm.jar or
simply comm.jar. Files that might cause trouble are libSerial.jnilib (on Mac OS X), libSerial.dll
(Windows), jcl.jar, and javax.comm.properties. (additional notes from stendahl)

Mac OS X

We use rxtx (formerly version 2.1_6, as of Processing 0111, we're using rxtx 2.1_7) to handle
serial I/O, which is included with the Processing release. If this is the first time you're using rxtx,
you'll need to make your way to the "libraries" folder, find "serial", and inside, and run
macosx_setup.command (double-click it and follow the instructions). This will make sure that things
are properly set up (a few permissions need to be changed). As of release 0134, running
macosx_setup.command is no longer necessary, thanks to help from the Arduino guys.
In the past, I've used a keyspan 28X dual port adapter, and Serial.list() returns things like

/dev/cu.USA28X21P1.1.
You'll probably have something similar. Don't mind the frightening names.

Tom Igoe was kind enough to note that you'll be in a world of hurt if you disconnect your serial
adapter while a sketch is runningit'll prolly freeze the machine and require a forced reboot. This
scenario may seem unlikely, but you might run into it if your adapter is plugged into a USB keyboard,
and you have the keyboard plugged into a monitor/keyboard switcher. You know, those cheap KVMs
that everyone likes to talk about in relation to the Mac Minis? The ones that actually cost ~$150 and
up?

Linux

Linux also uses rxtx-2.1_7 (just like Mac OS X). If you're having trouble getting things to run,
i.e. the port menu stays grayed out or you get error message spew to the console when starting the
application saying "Permission denied" and "No permission to create lock file", this is because you
probably need to add yourself to both the uucp or lock groups so that processing can write to
/var/lock so it doesn't get in a fight with other applications talking on the serial port.
Alan Kilian contributes this description:
1. I did an ls -l /dev/ttyS0 and saw that the group was set to uucp.
2. Then I edited /etc/groups, I found the uucp group, and I added my login ID to the uucp line.
3. I logged out, and logged back in again.
4. The "groups" command now showed I was in group uucp, and when I started processing, the
serial port menu item was not greyed-out.

It's important that you're in both groups, and that you completely log out and log back in again.

Running processing as root will often get rid of the errors, but that's obviously not a good
solution for a million reasons (among them: beta code that runs as root and handles files? yeah
great...)

S-ar putea să vă placă și