arduino language reference

300
Solti Imre: Arduino eljárásgyűjtemény Ajánlás: Ez egy aurdino és egyéb szabadon másolható oldalakról összeollózott leírás Tudom, hogy semmi új nincs benne az aurdino.cc-hez képest, de egyrészt bele- vettem pár library leírását, ami nem szerepelt az eredetiben, másrészt ez így egy- ben van, nem kell tokenenként átnyálazni...:-) Publikálásra került: 2012. november (TavIR-AVR; www.tavir.hu)

Upload: infrabatman

Post on 26-Dec-2015

211 views

Category:

Documents


9 download

DESCRIPTION

arduino

TRANSCRIPT

Page 1: Arduino Language Reference

Solti Imre:Arduino eljárásgy űjtem ény

Ajánlás:

Ez egy aurdino és egyéb szabadon másolható oldalakról összeollózott leírás Tudom, hogy semmi új nincs benne az aurdino.cc-hez képest, de egyrészt bele-vettem pár library leírását, ami nem szerepelt az eredetiben, másrészt ez így egy-ben van, nem kell tokenenként átnyálazni...:-)

Publikálásra került: 2012. november(TavIR-AVR; www.tavir.hu)

Page 2: Arduino Language Reference

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

Structure

setup()loop()

Control Structures

ifif...elseforswitch casewhiledo... whilebreakcontinuereturngoto

Further Syntax

; (semicolon){} (curly braces)// (single line comment)/* */ (multi-line comment)#define#include

Arithmetic Operators

= (assignment operator)+  (addition)- (subtraction)* (multiplication)/ (division)% (modulo)

Comparison Operators

== (equal to)!= (not equal to)< (less than)> (greater than)<= (less than or equal to)>= (greaterthanor equal to)

1

Page 3: Arduino Language Reference

Boolean Operators

&& (and)|| (or)! (not)

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)

Variables

Constants

HIGH | LOWINPUT | OUTPUT| INPUT_PULLUPtrue | falseinteger constantsfloating point constants

Data Types

voidbooleancharunsigned charbyteintunsigned intwordlongunsigned longfloat

2

Page 4: Arduino Language Reference

doublestring - char arrayString - objectarray

Conversion

char()byte()int()word()long()float()

Variable Scope & Qualifiers

variable scopestaticvolatileconst

Utilities

sizeof()

Functions

Digital I/O

pinMode() digitalWrite() digitalRead()

Analog I/O

analogReference()analogRead() analogWrite() - PWM

Advanced I/O

tone()noTone()shiftOut() shiftIn() pulseIn()

Time

millis() micros()

3

Page 5: Arduino Language Reference

delay() delayMicroseconds()

Math

min()max()abs()constrain()map()pow()sqrt()

Trigonometry

sin()cos()tan()

Random Numbers

randomSeed()random()

Bits and Bytes

lowByte()highByte()bitRead()bitWrite()bitSet()bitClear()bit()

Interrupts

attachInterrupt()detachInterrupt()interrupts()noInterrupts()

Communication

SerialStream

Leonardo Specific

KeyboardMouse

4

Page 6: Arduino Language Reference

abs(x)

Computes the absolute value of a number.

Parameters: x: the number

Returns: x: if x is greater than or equal to 0.-x: if x is less than 0.

Warning

Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.

abs(a++); // avoid this - yields incorrect resultsa++; // use this instead -abs(a); // keep other math outside the function

analogRead()

Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can be changed using analogReference().It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second.

Syntax: analogRead(pin)

Parameters: pin: the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano, 0 to 15 on the Mega)

Returns: int (0 to 1023)

Note

If the analog input pin is not connected to anything, the value returned by analogRead() will fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your hand is to the board, etc.).

Example

int analogPin = 3; // potentiometer wiper (middle terminal) connected to analog pin 3 // outside leads to ground and +5Vint val = 0; // variable to store the value read

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

5

Page 7: Arduino Language Reference

void loop(){ val = analogRead(analogPin); // read the input pin Serial.println(val); // debug value}

analogReference(type)

Configures the reference voltage used for analog input (i.e. the value used as the top of the input range). The options are:

* DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)

* INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)

* INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)

* INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)

* EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Parameters type: which type of reference to use (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56, or EXTERNAL).

Returns None.

Note After changing the analog reference, the first few readings from analogRead() may not be accurate.

WarningDon't use anything less than 0V or more than 5V for external reference voltage on the AREF pin! Ifyou're using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling analogRead(). Otherwise, you will short together the active reference voltage (internally generated) and the AREF pin, possibly damaging the microcontroller on your Arduino board.Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you to switch between external and internal reference voltages. Note that the resistor will alter the voltage that gets used as the reference because there is an internal 32K resistor on the AREF pin. The two act as a voltage divider, so, for example, 2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin.

analogWrite()

Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses ordrive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal is approximately 490 Hz.

6

Page 8: Arduino Language Reference

On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 through 13. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11. You do not need to call pinMode() to set the pin as an output before calling analogWrite().

The analogWrite function has nothing whatsoever to do with the analog pins or the analogRead function.

Syntax: analogWrite(pin, value)

Parameters: pin: the pin to write to.value: the duty cycle: between 0 (always off) and 255 (always on).

Returns: nothing

Notes and Known Issues

The PWM outputs generated on pins 5 and 6 will have higher-than-expected duty cycles. This is because of interactions with the millis() and delay() functions, which share the same internal timer used to generate those PWM outputs. This will be noticed mostly on low duty-cycle settings (e.g 0 - 10) and may result in a value of 0 not fully turning off the output on pins 5 and 6.

Example

Sets the output to the LED proportional to the value read from the potentiometer. int ledPin = 9; // LED connected to digital pin 9int analogPin = 3; // potentiometer connected to analog pin 3int val = 0; // variable to store the read value

void setup(){ pinMode(ledPin, OUTPUT); // sets the pin as output}

void loop(){ val = analogRead(analogPin); // read the input pin analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values

from 0 to 255}

Addition, Subtraction, Multiplication, & Division

These operators return the sum, difference, product, or quotient (respectively) of the two operands. The operation is conducted using the data type of the operands, so, for example, 9 / 4 gives 2 since 9 and 4 are ints. This also means that the operation can overflow if the result is larger than that which can be stored in the data type (e.g. adding 1 to an int with the value 32,767 gives -32,768). If the operands are of different types, the "larger" type is used for the calculation.

7

Page 9: Arduino Language Reference

If one of the numbers (operands) are of the type float or of type double, floating point math will be used for the calculation.

Examples

y = y + 3;x = x - 7;i = j * 6;r = r / 5;

Syntax result = value1 + value2;result = value1 - value2;result = value1 * value2;result = value1 / value2;

Parameters: value1: any variable or constantvalue2: any variable or constant

Programming Tips:

* Know that integer constants default to int, so some constant calculations may overflow (e.g. 60 * 1000 will yield a negative result).

* Choose variable sizes that are large enough to hold the largest results from your calculations * Know at what point your variable will "roll over" and also what happens in the other direction e.g. (0 - 1) OR (0 - - 32768)

* For math that requires fractions, use float variables, but be aware of their drawbacks: large size, slow computation speeds

* Use the cast operator e.g. (int)myFloat to convert one variable type to another on the fly.

Arrays

An array is a collection of variables that are accessed with an index number. Arrays in the C programming language, on which Arduino is based, can be complicated, but using simple arrays isrelatively straightforward.

Creating (Declaring) an Array

All of the methods below are valid ways to create (declare) an array.

int myInts[6]; int myPins[] = {2, 4, 8, 3, 6}; int mySensVals[6] = {2, 4, -8, 3, 2}; char message[6] = "hello";

You can declare an array without initializing it as in myInts.

In myPins we declare an array without explicitly choosing a size. The compiler counts the elements

8

Page 10: Arduino Language Reference

and creates an array of the appropriate size.Finally you can both initialize and size your array, as in mySensVals. Note that when declaring anarray of type char, one more element than your initialization is required, to hold the requirednull character.

Accessing an Array

Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence

mySensVals[0] == 2, mySensVals[1] == 4, and so forth.

It also means that in an array with ten elements, index nine is the last element. Hence:

int myArray[10]={9,3,2,4,3,2,7,8,9,11}; // myArray[9] contains 11 // myArray[10] is invalid and contains random information (other memory address)

For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down.

Unlike BASIC or JAVA, the C compiler does no checking to see if array access is within legal bounds of the array size that you have declared.

To assign a value to an array:

mySensVals[0] = 10;

To retrieve a value from an array:

x = mySensVals[4];

Arrays and FOR Loops

Arrays are often manipulated inside for loops, where the loop counter is used as the index for each array element. For example, to print the elements of an array over the serial port, you could do something like this:

int i;for (i = 0; i < 5; i = i + 1) { Serial.println(myPins[i]);}

= assignment operator (single equal sign)

Stores the value to the right of the equal sign in the variable to the left of the equal sign.

9

Page 11: Arduino Language Reference

The single equal sign in the C programming language is called the assignment operator. It has a different meaning than in algebra class where it indicated an equation or equality. The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign.

Example

int sensVal; // declare an integer variable named sensVal senVal = analogRead(0); // store the (digitized) input voltage at analog pin 0 in SensVal

Programming Tips

The variable on the left side of the assignment operator ( = sign ) needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect.

Don't confuse the assignment operator [ = ] (single equal sign) with the comparison operator [ == ] (double equal signs), which evaluates whether two expressions are equal.

attachInterrupt()

Specifies a function to call when an external interrupt occurs. Replaces any previous function that was attached to the interrupt. Most Arduino boards have two external interrupts: numbers 0 (on digital pin 2) and 1 (on digital pin 3). The Arduino Mega has an additional four: numbers 2 (pin 21), 3 (pin 20), 4 (pin 19), and 5 (pin 18).

Syntax: attachInterrupt(interrupt, function, mode)

Parameters: interrupt: the number of the interrupt (int)function: the function to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine.mode defines when the interrupt should be triggered. Four contstants are predefined as valid

values: * LOW to trigger the interrupt whenever the pin is low,* CHANGE to trigger the interrupt whenever the pin changes value* RISING to trigger when the pin goes from low to high,* FALLING for when the pin goes from high to low.

Returns: none

Note: Inside the attached function, delay() won't work and the value returned by millis() will not increment. Serial data received while in the function may be lost. You should declare as volatile any variables that you modify within the attached function.

Interrupts using

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. A good task for using an interrupt might be reading a rotary encoder, monitoring user input.

10

Page 12: Arduino Language Reference

If you wanted to insure that a program always caught the pulses from a rotary encoder, never missing a pulse, it would make it very tricky to write a program to do anything else, because the program would need to constantly poll the sensor lines for the encoder, in order to catch pulses when they occurred. Other sensors have a similar interface dynamic too, such as trying to read a sound sensor that is trying to catch a click, or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In all of these situations, using an interrupt can free the microcontroller to get some other work done while not missing the doorbell.

Example

int pin = 13;volatile int state = LOW;

void setup(){ pinMode(pin, OUTPUT); attachInterrupt(0, blink, CHANGE);}

void loop(){ digitalWrite(pin, state);}

void blink(){ state = !state;}

begin()

Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however, specify other rates - for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.

Syntax: Serial.begin(speed)

Arduino Mega only: Serial1.begin(speed)Serial2.begin(speed)Serial3.begin(speed)

Parameters: speed: in bits per second (baud) – long

Returns: nothing

Example

void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

11

Page 13: Arduino Language Reference

}void loop() {}Arduino Mega Example

// Arduino Mega using all four of its Serial ports// (Serial, Serial1, Serial2, Serial3),// with different baud rates:

void setup(){ Serial.begin(9600); Serial1.begin(38400); Serial2.begin(19200); Serial3.begin(4800);

Serial.println("Hello Computer"); Serial1.println("Hello Serial 1"); Serial2.println("Hello Serial 2"); Serial3.println("Hello Serial 3");}void loop() {}

bitClear()

Clears (writes a 0 to) a bit of a numeric variable.

Syntax: bitClear(x, n)Parameters x: the numeric variable whose bit to clear

n: which bit to clear, starting at 0 for the least-significant (rightmost) bitReturns: none

bit()

Computes the value of the specified bit (bit 0 is 1, bit 1 is 2, bit 2 is 4, etc.).

Syntax: bit(n)Parameters n: the bit whose value to computeReturns: the value of the bit

bitRead()

Description: Reads a bit of a number.Syntax: bitRead(x, n)Parameters: x: the number from which to read

n: which bit to read, starting at 0 for the least-significant (rightmost) bit

Returns: the value of the bit (0 or 1).

12

Page 14: Arduino Language Reference

bitSet()

Sets (writes a 1 to) a bit of a numeric variable.

Syntax: bitSet(x, n)Parameters: x: the numeric variable whose bit to set

n: which bit to set, starting at 0 for the least-significant (rightmost) bitReturns: none

bitshift left (<<), bitshift right (>>)

From The Bitmath Tutorial in The Playground

There are two bit shift operators in C++: the left shift operator << and the right shift operator>>. These operators cause the bits in the left operand to be shifted left or right by the numberof positions specified by the right operand.

Syntax: variable << number_of_bitsvariable >> number_of_bits

Parameters: variable - (byte, int, long) number_of_bits integer <= 32

Example

int a = 5; // binary: 0000000000000101 int b = a << 3; // binary: 0000000000101000, or 40 in decimal int c = b >> 3; // binary: 0000000000000101, or back to 5 like we started with

When you shift a value x by y bits (x << y), the leftmost y bits in x are lost, literally shiftedout of existence:

int a = 5; // binary: 0000000000000101 int b = a << 14; // binary: 0100000000000000 - the first 1 in 101 was discarded

If you are certain that none of the ones in a value are being shifted into oblivion, a simple way to think of the left-shift operator is that it multiplies the left operand by 2 raised to the right operand power. For example, to generate powers of 2, the following expressions can be employed:

1 << 0 == 1 1 << 1 == 2 1 << 2 == 4 1 << 3 == 8 ... 1 << 8 == 256 1 << 9 == 512 1 << 10 == 1024 ...

When you shift x right by y bits (x >> y), and the highest bit in x is a 1, the behavior depends on the

13

Page 15: Arduino Language Reference

exact data type of x. If x is of type int, the highest bit is the sign bit, determining whether x is negative or not, as we have discussed above. In that case, the sign bit is copied into lower bits, for esoteric historical reasons:

int x = -16; // binary: 1111111111110000 int y = x >> 3; // binary: 1111111111111110

This behavior, called sign extension, is often not the behavior you want. Instead, you may wish zeros to be shifted in from the left. It turns out that the right shift rules are different for unsigned int expressions, so you can use a typecast to suppress ones being copied from the left:

int x = -16; // binary: 1111111111110000 int y = (unsigned int)x >> 3; // binary: 0001111111111110

If you are careful to avoid sign extension, you can use the right-shift operator >> as a way to divide by powers of 2. For Example

int x = 1000; int y = x >> 3; // integer division of 1000 by 8, causing y = 125.

Bitwise AND (&), Bitwise OR (|), Bitwise XOR (^)

The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming problems. Much of the material below is from an excellent tutorial on bitwise math wihch may be found here.

Bitwise AND (&)

The bitwise AND operator in C++ is a single ampersand, &, used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0. Another way of expressing this is:

0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 0 0 1 (operand1 & operand2) - returned result

In Arduino, the type int is a 16-bit value, so using & between two int expressions causes 16 simultaneous AND operations to occur. In a code fragment like:

int a = 92; // in binary: 0000000001011100 int b = 101; // in binary: 0000000001100101 int c = a & b; // result: 0000000001000100, or 68 in decimal.

Each of the 16 bits in a and b are processed by using the bitwise AND, and all 16 resulting bits are stored in c, resulting in the value 01000100 in binary, which is 68 in decimal.

One of the most common uses of bitwise AND is to select a particular bit (or bits) from an integer value, often called masking. See below for an example

14

Page 16: Arduino Language Reference

Bitwise OR (|)

The bitwise OR operator in C++ is the vertical bar symbol, |. Like the & operator, | operates independently each bit in its two surrounding integer expressions, but what it does is different (of course). The bitwise OR of two bits is 1 if either or both of the input bits is 1, otherwise it is 0. In other words:

0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 1 1 1 (operand1 | operand2) - returned result

Here is an example of the bitwise OR used in a snippet of C++ code:

int a = 92; // in binary: 0000000001011100 int b = 101; // in binary: 0000000001100101 int c = a | b; // result: 0000000001111101, or 125 in decimal.

Example Program

A common job for the bitwise AND and OR operators is what programmers call Read-Modify-Write on a port. On microcontrollers, a port is an 8 bit number that represents something about the condition of the pins. Writing to a port controls all of the pins at once.

PORTD is a built-in constant that refers to the output states of digital pins 0,1,2,3,4,5,6,7. If there is 1 in an bit position, then that pin is HIGH. (The pins already need to be set to outputs with the pinMode() command.) So if we write PORTD = B00110001; we have made pins 2,3 & 7 HIGH. One slight hitch here is that we may also have changeed the state of Pins 0 & 1, which are used by the Arduino for serial communications so we may have interfered with serial communication.

Our algorithm for the program is:

* Get PORTD and clear out only the bits corresponding to the pins we wish to control (with bitwise AND).

* Combine the modified PORTD value with the new value for the pins under control (with biwise OR).

int i; // counter variableint j;

void setup(){DDRD = DDRD | B11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx)// same as pinMode(pin, OUTPUT) for pins 2 to 7Serial.begin(9600);}

void loop(){for (i=0; i<64; i++){

PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx)

15

Page 17: Arduino Language Reference

j = (i << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1PORTD = PORTD | j; // combine the port information with the new information for LED pinsSerial.println(PORTD, BIN); // debug to show maskingdelay(100); }}

Bitwise XOR (^)

There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. This operator is very similar to the bitwise OR operator |, only it evaluatesto 0 for a given bit position when both of the input bits for that position are 1:

0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 1 1 0 (operand1 ^ operand2) - returned result

Another way to look at bitwise XOR is that each bit in the result is a 1 if the input bits are different, or 0 if they are the same.

Here is a simple code Example

int x = 12; // binary: 1100 int y = 10; // binary: 1010 int z = x ^ y; // binary: 0110, or decimal 6

The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise OR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same. Below is a program to blink digital pin 5.

// Blink_Pin_5// demo for Exclusive ORvoid setup(){DDRD = DDRD | B00100000; // set digital pin five as OUTPUT Serial.begin(9600);}

void loop(){PORTD = PORTD ^ B00100000; // invert bit 5 (digital pin 5), leave others untoucheddelay(100);}

compound bitwise AND (&=)

The compound bitwise AND operator (&=) is often used with a variable and a constant to force particular bits in a variable to the LOW state (to 0). This is often referred to in programming guides as "clearing" or "resetting" bits.

16

Page 18: Arduino Language Reference

Syntax: x &= y; // equivalent to x = x & y;

Parameters: x: a char, int or long variabley: an integer constant or char, int, or long

Example

First, a review of the Bitwise AND (&) operator

0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 0 0 1 (operand1 & operand2) - returned result

Bits that are "bitwise ANDed" with 0 are cleared to 0 so, if myByte is a byte variable, myByte & B00000000 = 0;

Bits that are "bitwise ANDed" with 1 are unchanged so,myByte & B11111111 = myByte;

Note: because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter with constants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, B00000000 is shown for clarity, but zero in any number format is zero (hmmm something philosophical there?)

Consequently - to clear (set to zero) bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise AND operator (&=) with the constant B11111100

1 0 1 0 1 0 1 0 variable 1 1 1 1 1 1 0 0 mask ---------------------- 1 0 1 0 1 0 0 0 variable unchanged bits cleared

Here is the same representation with the variable's bits replaced with the symbol x x x x x x x x x variable 1 1 1 1 1 1 0 0 mask ---------------------- x x x x x x 0 0 variable unchanged bits cleared So if:

myByte = 10101010;

myByte &= B1111100 == B10101000;

compound bitwise OR (|=)

The compound bitwise OR operator (|=) is often used with a variable and a constant to "set" (set to 1) particular bits in a variable.

Syntax: x |= y; // equivalent to x = x | y;

17

Page 19: Arduino Language Reference

Parameters: x: a char, int or long variabley: an integer constant or char, int, or long

Example

First, a review of the Bitwise OR (|) operator

0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 1 1 1 (operand1 | operand2) - returned result

Bits that are "bitwise ORed" with 0 are unchanged, so if myByte is a byte variable,myByte | B00000000 = myByte;

Bits that are "bitwise ORed" with 1 are set to 1 so: myByte | B11111111 = B11111111;

Consequently - to set bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise OR operator (|=) with the constant B00000011

1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask ---------------------- 1 0 1 0 1 0 1 1 variable unchanged bits set

Here is the same representation with the variables bits replaced with the symbol x

x x x x x x x x variable 0 0 0 0 0 0 1 1 mask ---------------------- x x x x x x 1 1

variable unchanged bits set

So if: myByte = B10101010;myByte |= B00000011 == B10101011;

Bitwise NOT (~)

The bitwise NOT operator in C++ is the tilde character ~. Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0. For Example

0 1 operand1 ---------- 1 0 ~ operand1 int a = 103; // binary: 0000000001100111 int b = ~a; // binary: 1111111110011000 = -104

You might be surprised to see a negative number like -104 as the result of this operation. This is because the highest bit in an int variable is the so-called sign bit. If the highest bit is 1, the number is interpreted as negative. This encoding of positive and negative numbers is referred to as two's

18

Page 20: Arduino Language Reference

complement. For more information, see the Wikipedia article on two's complement.

As an aside, it is interesting to note that for any integer x, ~x is the same as -x-1.

At times, the sign bit in a signed integer expression can cause some unwanted surprises.

bitWrite()

Writes a bit of a numeric variable.

Syntax: bitWrite(x, n, b)

Parameters: x: the numeric variable to which to writen: which bit of the number to write, starting at 0 for the least-significant (rightmost) bitb: the value to write to the bit (0 or 1)

Returns: none

Boolean Operators

These can be used inside the condition of an if statement.

&& (logical and)

True only if both operands are true, e.g.

if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches // ...}

is true only if both inputs are high.

|| (logical or)

True if either operand is true, e.g.

if (x > 0 || y > 0) { // ...}

is true if either x or y is greater than 0.

! (not)

True if the operand is false, e.g.

19

Page 21: Arduino Language Reference

if (!x) { // ...}

is true if x is false (i.e. if x equals 0).

Warning!! Make sure you don't mistake the boolean AND operator, && (double ampersand) for the bitwise AND operator & (single ampersand). They are entirely different beasts. Similarly, do not confuse the boolean || (double pipe) operator with the bitwise OR operator | (single pipe). The bitwise not ~ (tilde) looks much different than the boolean not ! (exclamation point or "bang" as the programmers say) but you still have to be sure which one you want where.

Examples

if (a >= 10 && a <= 20){} // true if a is between 10 and 20

boolean

A boolean holds one of two values, true or false. (Each boolean variable occupies one byte of memory.)

Example

int LEDpin = 5; // LED on pin 5int switchPin = 13; // momentary switch on 13, other side connected to ground

boolean running = false;

void setup(){ pinMode(LEDpin, OUTPUT); pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); // turn on pullup resistor}void loop(){ if (digitalRead(switchPin) == LOW) { // switch is pressed - pullup keeps pin high normally delay(100); // delay to debounce switch running = !running; // toggle running variable digitalWrite(LEDpin, running) // indicate via LED }}

{} Curly Braces

Curly braces (also referred to as just "braces" or as "curly brackets") are a major part of the C programming language. They are used in several different constructs, outlined below, and this can sometimes be confusing for beginners.

20

Page 22: Arduino Language Reference

An opening curly brace "{" must always be followed by a closing curly brace "}". This is a condition that is often referred to as the braces being balanced. The Arduino IDE (integrated development environment) includes a convenient feature to check the balance of curly braces. Just select a brace, or even click the insertion point immediately following a brace, and its logical companion will be highlighted.

At present this feature is slightly buggy as the IDE will often find (incorrectly) a brace in text that has been "commented out."

Beginning programmers, and programmers coming to C from the BASIC language often find using braces confusing or daunting. After all, the same curly braces replace the RETURN statement in a subroutine (function), the ENDIF statement in a conditional and the NEXT statement in a FOR loop.

Because the use of the curly brace is so varied, it is good programming practice to type the closing brace immediately after typing the opening brace when inserting a construct which requires curly braces. Then insert some carriage returns between your braces and begin inserting statements. Your braces, and your attitude, will never become unbalanced.

Unbalanced braces can often lead to cryptic, impenetrable compiler errors that can sometimes be hard to track down in a large program. Because of their varied usages, braces are also incredibly important to the syntax of a program and moving a brace one or two lines will often dramatically affect the meaning of a program.

The main uses of curly braces

Functions

void myfunction(datatype argument){ statements(s) }

Loops

while (boolean expression) { statement(s) }

do { statement(s) } while (boolean expression);

for (initialisation; termination condition; incrementing expr) { statement(s) }

Conditional statements

21

Page 23: Arduino Language Reference

if (boolean expression) { statement(s) }

else if (boolean expression) { statement(s) } else { statement(s) }

break

break is used to exit from a do, for, or while loop, bypassing the normal loop condition. It is also used to exit from a switch statement.

Example

for (x = 0; x < 255; x ++){ digitalWrite(PWMpin, x); sens = analogRead(sensorPin); if (sens > threshold){ // bail out on sensor detect x = 0; break; } delay(50);}

byte()

Converts a value to the byte data type.

Syntax: byte(x)Parameters: x: a value of any typeReturns: byte

byte

A byte stores an 8-bit unsigned number, from 0 to 255.

Example

byte b = B10010; // "B" is the binary formatter (B10010 = 18 decimal)

22

Page 24: Arduino Language Reference

char()

Converts a value to the char data type.

Syntax: char(x)Parameters: x: a value of any typeReturns: char

char

A data type that takes up 1 byte of memory that stores a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").

Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See Serial.println reference for more on how characters are translated to numbers.

The char datatype is a signed type, meaning that it encodes numbers from -128 to 127. For an unsigned, one-byte (8 bit) data type, use the byte data type.

Example

char myChar = 'A'; char myChar = 65; // both are equivalent

Comments

Comments are lines in the program that are used to inform yourself or others about the way the program works. They are ignored by the compiler, and not exported to the processor, so they don't take up any space on the Atmega chip.Comments only purpose are to help you understand (or remember) how your program works or to inform others how your program works. There are two different ways of marking a line as a comment:

Example

x = 5; // This is a single line comment. Anything after the slashes is a comment // to the end of the line/* this is multiline comment - use it to comment out whole blocks of code

if (gwb == 0){ // single line comment is OK inside a multiline commentx = 3; /* but not another multiline comment - this is invalid */}

// don't forget the "closing" comment - they have to be balanced!*/

Tip: When experimenting with code, "commenting out" parts of your program is a convenient way to remove lines that may be buggy. This leaves the lines in the code, but turns them into comments, so the compiler just ignores them. This can be especially useful when trying to

23

Page 25: Arduino Language Reference

locate a problem, or when a program refuses to compile and the compiler error is cryptic or unhelpful.

Arduino/Processing Language Comparison

The Arduino language (based on Wiring) is implemented in C/C++, and therefore has some differences from the Processing language, which is based on Java.

Arrays

Arduino Processingint bar[8];bar[0] = 1; int[] bar = new int[8];bar[0] = 1;int foo[] = { 0, 1, 2 }; int foo[] = { 0, 1, 2 };orint[] foo = { 0, 1, 2 };

Loops

Arduino Processingint i;for (i = 0; i < 5; i++) { ... } for (int i = 0; i < 5; i++) { ... }

Printing

Arduino ProcessingSerial.println("hello world"); println("hello world");int i = 5;Serial.println(i); int i = 5;println(i);int i = 5;Serial.print("i = ");Serial.print(i);Serial.println(); int i = 5;println("i = " + i);

constants

Constants are predefined variables in the Arduino language. They are used to make the programs easier to read. We classify constants in groups.

Defining Logical Levels, true and false (Boolean Constants)

There are two constants used to represent truth and falsity in the Arduino language: true, and false.

false false is the easier of the two to define. false is defined as 0 (zero).

true true is often said to be defined as 1, which is correct, but true has a wider definition. Any integer which is non-zero is true, in a Boolean sense. So -1, 2 and -200 are all defined as true, too, in a Boolean sense.

24

Page 26: Arduino Language Reference

Note that the true and false constants are typed in lowercase unlike HIGH, LOW, INPUT, & OUTPUT.

Defining Pin Levels, HIGH and LOW

When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.

HIGH

The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode, and read with digitalRead, the microcontroller will report HIGH if a voltage of 3 volts or more is present at the pin.

A pin may also be configured as an INPUT with pinMode, and subsequently made HIGH with digitalWrite, this will set the internal 20K pullup resistors, which will steer the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT_PULLUP works as well

When a pin is configured to OUTPUT with pinMode, and set to HIGH with digitalWrite, the pin is at 5 volts. In this state it can source current, e.g. light an LED that is connected through a series resistor to ground, or to another pin configured as an output, and set to LOW.

LOW

The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode, and read with digitalRead, the microcontroller will report LOW if a voltage of 2 volts or less is present at the pin.

When a pin is configured to OUTPUT with pinMode, and set to LOW with digitalWrite, the pin is at 0 volts. In this state it can sink current, e.g. light an LED that is connected through a series resistor to, +5 volts, or to another pin configured as an output, and set to HIGH.

Defining Digital Pins, INPUT, INPUT_PULLUP, and OUTPUT

Digital pins can be used as INPUT, INPUT_PULLUP, or OUTPUT. Changing a pin with pinMode() changes the electrical behavior of the pin.Pins Configured as INPUT

Arduino (Atmega) pins configured as INPUT with pinMode() are said to be in a high-impedance state. Pins configured as INPUT make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 Megohms in front of the pin. This makes them useful for reading a sensor, but not powering an LED.

If you have your pin configured as an INPUT, you will want the pin to have a reference to ground, often accomplished with a pull-down resistor (a resistor going to ground) as described in the Digital Read Serial tutorial.

Pins Configured as INPUT_PULLUP

The Atmega chip on the Arduino has internal pull-up resistors (resistors that connect to power

25

Page 27: Arduino Language Reference

internally) that you can access. If you prefer to use these instead of external pull-down resistors, you can use the INPUT_PULLUP argument in pinMode(). This effectively inverts the behavior, where HIGH means the sensor is off, and LOW means the sensor is on. See the Input Pullup Serial tutorial for an example of this in use.Pins Configured as Outputs

Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits. This makes them useful for powering LED's but useless for reading sensors. Pins configured as outputs can also be damaged or destroyed if short circuited to either ground or 5 volt power rails. The amount of current provided by an Atmega pin is also not enough to power most relays or motors, and some interface circuitry will be required.

const keyword

The const keyword stands for constant. It is a variable qualifier that modifies the behavior of the variable, making a variable "read-only". This means that the variable can be used just as any other variable of its type, but its value cannot be changed. You will get a compiler error if you try to assign a value to a const variable.

Constants defined with the const keyword obey the rules of variable scoping that govern other variables. This, and the pitfalls of using#define, makes the const keyword a superior method for defining constants and is preferred over using #define.

Example

const float pi = 3.14;float x;

// ....

x = pi * 2; // it's fine to use const's in math

pi = 7; // illegal - you can't write to (modify) a constant

#define or const

You can use either const or #define for creating numeric or string constants. For arrays, you will need to use const. In general const is preferred over #define for defining constants.

constrain(x, a, b)

Constrains a number to be within a range.

Parameters x: the number to constrain, all data typesa: the lower end of the range, all data typesb: the upper end of the range, all data types

Returns x: if x is between a and b

26

Page 28: Arduino Language Reference

a: if x is less than ab: if x is greater than b

Example

sensVal = constrain(sensVal, 10, 150); // limits range of sensor values to between 10 and 150

continue

The continue statement skips the rest of the current iteration of a loop (do, for, or while). It continues by checking the conditional expression of the loop, and proceeding with any subsequent iterations.

Example

for (x = 0; x < 255; x ++){ if (x > 40 && x < 120){ // create jump in values continue; }

digitalWrite(PWMpin, x); delay(50);}

cos(rad)

Calculates the cos of an angle (in radians). The result will be between -1 and 1.

Parameters: rad: the angle in radians (float)Returns: The cos of the angle ("double")

27

Page 29: Arduino Language Reference

DCF77 Library

The DCF77 library adds the ability to read and decode the atomic time broadcasted by the DCF77 radiostation. It has been designed to work in conjunction with the Arduino Time library and allows a sketch to get the precise CET time and date as a standard C time_t. The DCF77 Library download. Example sketches have been added to 1) illustrate and debug the incoming signal 2) use the library, using the setSyncProvider callback and converting to different time zones. In order to exploit all features in the library, Both the Time and TimeZone library are included.

Functional Overview

DCF77(DCF77Pin, DCFinterrupt, OnRisingFlank); // Initializetime_t getTime(); // Returns the current time in CETtime_t getUTCTime(); // Returns the current time in UTCStart(); // Start listening to DCF77 signalStop(); // Stop listening to DCF77 sign

Example

The sketch below implements the most DCF77 basic functionality. It reads the signal from pin 2, and 2-3 minutes it will update the internal clock.

#include "DCF77.h"#include "Time.h"

#define DCF_PIN 2 // Connection pin to DCF 77 device#define DCF_INTERRUPT 0 // Interrupt number associated with pin

time_t time;// Non-inverted input on pin DCF_PINDCF77 DCF = DCF77(DCF_PIN,DCF_INTERRUPT, true);

void setup() { Serial.begin(9600); DCF.Start(); Serial.println("Waiting for DCF77 time ... "); Serial.println("It will take at least 2 minutes before a first time update.");}

void loop() { delay(1000); time_t DCFtime = DCF.getTime(); // Check if new DCF77 time is available if (DCFtime!=0) { Serial.println("Time is updated"); setTime(DCFtime); } digitalClockDisplay(); }

void digitalClockDisplay(){

28

Page 30: Arduino Language Reference

// digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); }

void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits);}

#define

#define is a useful C component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don't take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.

This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text). In general, the const keyword is preferred for defining constants and should be used instead of #define.

Syntax: #define constantName value (Note that the # is necessary.)

Example

#define ledPin 3// The compiler will replace any mention of ledPin with the value 3 at compile time.

Tip: There is no semicolon after the #define statement. If you include one, the compiler will throw cryptic errors further down the page.

#define ledPin 3; // this is an error

Similarly, including an equal sign after the #define statement will also generate a cryptic compiler error further down the page.

#define ledPin = 3 // this is also an error

29

Page 31: Arduino Language Reference

delay()

Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

Syntax: delay(ms)Parameters: ms: the number of milliseconds to pause (unsigned long)Returns: nothing

Example

int ledPin = 13; // LED connected to digital pin 13

void setup(){ pinMode(ledPin, OUTPUT); // sets the digital pin as output}

void loop(){ digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second}

Caveat

While it is easy to create a blinking LED with the delay() function, and many sketches use short delays for such tasks as switch debouncing, the use of delay() in a sketch has significant drawbacks. No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt. For alternative approaches to controlling timing see the millis() function and the sketch sited below. More knowledgeable programmers usually avoid the use of delay() for timing of events longer than 10's of milliseconds unless the Arduino sketch is very simple.

Certain things do go on while the delay() function is controlling the Atmega chip however, because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should.

delayMicroseconds()

Pauses the program for the amount of time (in microseconds) specified as parameter. There are a thousand microseconds in a millisecond, and a million microseconds in a second.

Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Syntax: delayMicroseconds(us)

30

Page 32: Arduino Language Reference

Parameters: us: the number of microseconds to pause (unsigned int)Returns: none

Example

int outPin = 8; // digital pin 8

void setup(){ pinMode(outPin, OUTPUT); // sets the digital pin as output}void loop(){ digitalWrite(outPin, HIGH); // sets the pin on delayMicroseconds(50); // pauses for 50 microseconds digitalWrite(outPin, LOW); // sets the pin off delayMicroseconds(50); // pauses for 50 microseconds }

configures pin number 8 to work as an output pin. It sends a train of pulses with 100 microseconds period.

Caveats and Known Issues

This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times.

As of Arduino 0018, delayMicroseconds() no longer disables interrupts.

detachInterrupt()

Turns off the given interrupt.

Syntax: detachInterrupt(interrupt)Parameters: interrupt: the number of interrupt to disable (0 or 1).

digitalRead()

Reads the value from a specified digital pin, either HIGH or LOW.

Syntax: digitalRead(pin)Parameters: pin: the number of the digital pin you want to read (int)Returns: HIGH or LOW

Example int ledPin = 13; // LED connected to digital pin 13int inPin = 7; // pushbutton connected to digital pin 7int val = 0; // variable to store the read valuevoid setup()

31

Page 33: Arduino Language Reference

{ pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output pinMode(inPin, INPUT); // sets the digital pin 7 as input}

void loop(){ val = digitalRead(inPin); // read the input pin digitalWrite(ledPin, val); // sets the LED to the button's value}

Sets pin 13 to the same value as the pin 7, which is an input.

Note: If the pin isn't connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).

The analog input pins can be used as digital pins, referred to as A0, A1, etc.

digitalWrite()

Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

If the pin is configured as an INPUT, writing a HIGH value with digitalWrite() will enable an internal 20K pullup resistor (see the tutorial on digital pins). Writing LOW will disable the pullup. The pullup resistor is enough to light an LED dimly, so if LEDs appear to work, but very dimly, this is a likely cause. The remedy is to set the pin to an output with the pinMode() function.

NOTE: Digital pin 13 is harder to use as a digital input than the other digital pins because it has an LED and resistor attached to it that's soldered to the board on most boards. If you enable its internal 20k pull-up resistor, it will hang at around 1.7 V instead of the expected 5V because the onboard LED and series resistor pull the voltage level down, meaning it always returns LOW. If you must use pin 13 as a digital input, use an external pull down resistor.

Syntax: digitalWrite(pin, value)

Parameters: pin: the pin numbervalue: HIGH or LOW

Returns: none

Example int ledPin = 13; // LED connected to digital pin 13

void setup(){ pinMode(ledPin, OUTPUT); // sets the digital pin as output}

32

Page 34: Arduino Language Reference

void loop(){ digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second}Sets pin 13 to HIGH, makes a one-second-long delay, and sets the pin back to LOW.

Note: The analog input pins can be used as digital pins, referred to as A0, A1, etc.

double

Double precision floating point number. Occupies 4 bytes.The double implementation on the Arduino is currently exactly the same as the float, with no gain in precision.

Tip: Users who borrow code from other sources that includes double variables may wish to examine the code to see if the implied precision is different from that actually achieved on the Arduino.

do - while

The do loop works in the same manner as the while loop, with the exception that the condition is tested at the end of the loop, so the do loop will always run at least once.

do{ // statement block} while (test condition);

Example

do{ delay(50); // wait for sensors to stabilize x = readSensors(); // check the sensors

} while (x < 100);

EEPROM Library

The microcontroller on the Arduino board has EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive). This library enables you to read and write those bytes.

The microcontrollers on the various Arduino boards have different amounts of EEPROM: 1024 bytes on the ATmega328, 512 bytes on the ATmega168 and ATmega8, 4 KB (4096 bytes) on the ATmega1280 and ATmega2560.

33

Page 35: Arduino Language Reference

EEPROM.read()

Reads a byte from the EEPROM. Locations that have never been written to have the value of 255.

Syntax: EEPROM.read(address)Parameters: address: the location to read from, starting from 0 (int)Returns: the value stored in that location (byte)

Example

#include <EEPROM.h>

int a = 0;int value;

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

void loop(){ value = EEPROM.read(a);

Serial.print(a); Serial.print("\t"); Serial.print(value); Serial.println();

a = a + 1;

if (a == 512) a = 0;

delay(500);}

EEPROM.write()

Write a byte to the EEPROM.

Syntax: EEPROM.write(address, value)

Parameters: address: the location to write to, starting from 0 (int)value: the value to write, from 0 to 255 (byte)

Returns: none

Note: An EEPROM write takes 3.3 ms to complete. The EEPROM memory has a specified life of 100,000 write/erase cycles, so you may need to be careful about how often you write to it.

34

Page 36: Arduino Language Reference

Example

#include <EEPROM.h>

void setup(){ for (int i = 0; i < 512; i++) EEPROM.write(i, i);}

void loop(){}

Ethernet library

With the Arduino Ethernet Shield, this library allows an Arduino board to connect to the internet. It can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports up to four concurrent connection (incoming or outgoing or a combination).

Arduino communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the W5100, but it must be kept as an output or the SPI interface won't work.

Ethernet class

The Ethernet class initializes the ethernet library and network settings.

* begin()* localIP()* maintain()

IPAddress class

The IPAddress class works with local and remote IP addressing.

* IPAddress()

Server class

The Server class creates servers which can send data to and receive data from connected clients(programs running on other computers or devices).

* Server

* EthernetServer()* begin()* available()* write()

35

Page 37: Arduino Language Reference

* print()* println()

Client class

The client class creates clients that can connect to servers and send and receive data.

* Client

* EthernetClient()* if (EthernetClient)* connected()* connect()* write()* print()* println()* available()* read()* flush()* stop()

EthernetUDP class

The EthernetUDP class enables UDP message to be sent and received.

* begin()* read()* write()* beginPacket()* endPacket()* parsePacket()* available()* remoteIP()* remotePort()

Ethernet.begin()

Initializes the ethernet library and network settings.

With version 1.0, the library supports DHCP. Using Ethernet.begin(mac) with the proper network setup, the Ethernet shield will automatically obtain an IP address. This increases the sketch size significantly.Syntax: Ethernet.begin(mac);

Ethernet.begin(mac, ip);Ethernet.begin(mac, ip, dns);Ethernet.begin(mac, ip, dns, gateway);Ethernet.begin(mac, ip, dns, gateway, subnet);

Parameters: mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.

36

Page 38: Arduino Language Reference

ip: the IP address of the device (array of 4 bytes)dns: the address for a DNS server.gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address with the last octet set to 1subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0

Returns: The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. The other versions don't return anything.

Example

#include <Ethernet.h>

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 };

void setup(){ Ethernet.begin(mac, ip);}

void loop () {}

EthernetClient()

Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function).

Syntax: EthernetClient()Parameters: None

Example

#include <Ethernet.h>#include <SPI.h>byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // GoogleEthernetClient client;

void setup(){ Ethernet.begin(mac, ip); Serial.begin(9600);

delay(1000);

Serial.println("connecting...");

37

Page 39: Arduino Language Reference

if (client.connect(server, 80)) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}

void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); }

if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; }}

Ethernet

client.available()

Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to). available() inherits from the Stream utility class.

Syntax: client.available()Parameters: noneReturns: The number of bytes available.

Example

#include <Ethernet.h>#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // GoogleEthernetClient client;

void setup(){ Ethernet.begin(mac, ip); Serial.begin(9600);

38

Page 40: Arduino Language Reference

delay(1000); Serial.println("connecting...");

if (client.connect(server, 80)) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}

void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); }

if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; }

Ethernet

client.connected()

Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data.

Syntax: client.connected()Parameters: noneReturns: Returns true if the client is connected, false if not.

Example

#include <Ethernet.h>#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // Google

EthernetClient client;

void setup(){

39

Page 41: Arduino Language Reference

Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000);

Serial.println("connecting...");

if (client.connect(server, 80)) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}

void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;);

Ethernet

client.connect()

Connect to the IP address and port specified in the constructor. The return value indicates success or failure.

Syntax: client.connect()Parameters: noneReturns: Returns true if the connection succeeds, false if not.

Example

#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // Google

Client client(server, 80);

void setup(){

40

Page 42: Arduino Language Reference

Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000); Serial.println("connecting...");

if (client.connect()) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}

void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; }}

Ethernet

Client()

Creates a client which can connect to the specified internet IP address and port.

Syntax: Client(ip, port)

Parameters: ip: the IP address that the client will connect to (array of 4 bytes)port: the port that the client will connect to (int)

Example

#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // Google

Client client(server, 80);

void setup(){

41

Page 43: Arduino Language Reference

Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000);

Serial.println("connecting...");

if (client.connect()) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); }

if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; }}

Ethernet

client.flush()

Discard any bytes that have been written to the client but not yet read. flush() inherits from the Stream utility class.

Syntax: client.flush()

Parameters: none

Returns: none

Ethernet

client.print()

Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

42

Page 44: Arduino Language Reference

Syntax: client.print(data)client.print(data, BASE)

Parameters: data: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte: returns the number of bytes written, though reading that number is optional

Ethernet

client.println()

Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax client.println()client.println(data)client.print(data, BASE)

Parameters data (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Ethernet

client.read()

Read the next byte received from the server the client is connected to (after the last call to read()).read() inherits from the Stream utility class.

Syntax: client.read()

Parameters: none

Returns: The next byte (or character), or -1 if none is available.

Ethernet

client.stop()

Disconnect from the server.

Syntax: client.stop()

Parameters: none

Returns: none

43

Page 45: Arduino Language Reference

Ethernet

client.write()

Write data to the server the client is connected to.

Syntax: client.write(data)

Parameters: data: the byte or char to write

Ethernet

IPAddress()

Defines an IP address. It can be used to declare both local and remote addresses.

Syntax: IPAddress(address);

Parameters: address: a comma delimited list representing the address (4 bytes, ex. 192, 168, 1, 1)

Returns: None

Example

#include <Ethernet.h>

// network configuration. gateway and subnet are optional.

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // the router's gateway address:byte gateway[] = { 10, 0, 0, 1 };// the subnet:byte subnet[] = { 255, 255, 0, 0 };

EthernetServer server = EthernetServer(23);

//the IP address is dependent on your networkIPAddress ip(192,168,1,1);void setup(){ // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

// start listening for clients server.begin();}

void loop(){ //print out the IP address

44

Page 46: Arduino Language Reference

Serial.println(myIPaddress);}

Ethernet

Ethernet.localIP()

Obtains the IP address of the Ethernet shield. Useful when the address is auto assigned through DHCP.

Syntax: Ethernet.localIP();

Parameters: none

Returns: the IP address

Example

#include <SPI.h>#include <Ethernet.h>

// Enter a MAC address for your controller below.// Newer Ethernet shields have a MAC address printed on a sticker on the shieldbyte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };

// Initialize the Ethernet client library// with the IP address and port of the server// that you want to connect to (port 80 is default for HTTP):EthernetClient client;void setup() { // start the serial library: Serial.begin(9600); // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: for(;;) ; } // print your local IP address: Serial.println(Ethernet.localIP());}

void loop() {//}

45

Page 47: Arduino Language Reference

Ethernet

Ethernet.maintain()

Allows for the renewal of DHCP leases. When assigned an IP address via DHCP, ethernet devices are given a lease on the address for an amount of time. With Ethernet.maintain(), it is possible to request a renewal from the DHCP server. Depending on the server's configuration, you may receive the same address, a new one, or none at all.

Ethernet.maintain() was added to Arduino 1.0.1.

Syntax: Ethernet.maintain();Parameters: noneReturns byte:

0: nothing happened1: renew failed2: renew success3: rebind fail4: rebind success

Ethernet : EthernetServer

EthernetServer()

Create a server that listens for incoming connections on the specified port.

Syntax: Server(port);

Parameters: port: the port to listen on (int)

Returns: None

Example

#include <SPI.h>#include <Ethernet.h>

// network configuration. gateway and subnet are optional.

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address:byte gateway[] = { 10, 0, 0, 1 };// the subnet:byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23

46

Page 48: Arduino Language Reference

EthernetServer server = EthernetServer(23);void setup(){ // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

// start listening for clients server.begin();}

void loop(){ // if an incoming client connects, there will be bytes available to read: EthernetClient client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read());

Ethernet

UDP.available()

Get the number of bytes (characters) available for reading from the buffer. This is data that's already arrived.

This function can only be successfully called after UDP.parsePacket(). available() inherits from the Stream utility class.

Syntax: UDP.available()

Parameters: None

Returns: the number of bytes available to read

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>

// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDPEthernetUDP Udp;

47

Page 49: Arduino Language Reference

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

void setup() { // start the Ethernet and UDP: Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() {

int packetSize = Udp.parsePacket(); if(Udp.available()) { Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); IPAddress remote = Udp.remoteIP(); for (int i =0; i < 4; i++) { Serial.print(remote[i], DEC); if (i < 3) { Serial.print("."); } } Serial.print(", port "); Serial.println(Udp.remotePort());

// read the packet into packetBufffer Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer);

Ethernet

UDP.begin()

Initializes the ethernet UDP library and network settings.

Syntax: EthernetUDP.begin(localPort);

Parameters: localPort: the local port to listen on (int)

Returns: None

Example #include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>

48

Page 50: Arduino Language Reference

// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;void setup() {

// start the Ethernet and UDP:

Ethernet.begin(mac,ip); Udp.begin(localPort);}void loop() {}

Ethernet

UDP.beginPacket()

Starts a connection to write UDP data to the remote connection

Syntax: UDP.beginPacket(remoteIP, remotePort);

Parameters: remoteIP: the IP address of the remote connection (4 bytes)remotePort: the port of the remote connection (int)

Returns: None

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;void setup() {

// start the Ethernet and UDP:

Ethernet.begin(mac,ip);

49

Page 51: Arduino Language Reference

Udp.begin(localPort);}void loop() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket();}

Ethernet

UDP.endPacket()

Called after writing UDP data to the remote connection.

Syntax: UDP.endPacket();

Parameters: None

Returns: None

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;void setup() {

// start the Ethernet and UDP:

Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket();}

50

Page 52: Arduino Language Reference

Ethernet

UDP.parsePacket()

Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP.read().

Syntax: UDP.parsePacket();

Parameters: None

Returns: int: the size of a received UDP packet

Example

#include <SPI.h> // needed for Arduino versions later than 0018#include <Ethernet.h>#include <EthernetUdp.h> // UDP library from: [email protected] 12/30/2008// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;void setup() {

// start the Ethernet and UDP:

Ethernet.begin(mac,ip); Udp.begin(localPort); Serial.begin(9600);}

void loop() { // if there's data available, read a packet

int packetSize = Udp.parsePacket(); if(packetSize) { Serial.print("Received packet of size "); Serial.println(packetSize); } delay(10);

51

Page 53: Arduino Language Reference

Ethernet

UDP.read()

Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer.

This function can only be successfully called after UDP.parsePacket().

Syntax: UDP.read();UDP.read(packetBuffer, MaxSize);

Parameters: packetBuffer: buffer to hold incoming packets (char)MaxSize: maximum size of the buffer (int)

Returns: char : returns the characters in the buffer

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

void setup() { // start the Ethernet and UDP: Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() { int packetSize = Udp.parsePacket(); if(packetSize) { Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); IPAddress remote = Udp.remoteIP(); for (int i =0; i < 4; i++) { Serial.print(remote[i], DEC); if (i < 3) {

52

Page 54: Arduino Language Reference

Serial.print("."); } } Serial.print(", port "); Serial.println(Udp.remotePort());

// read the packet into packetBufffer Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); }}

Ethernet

UDP.remoteIP()

Gets the IP address of the remote connection.

This function must be called after UDP.parsePacket().

Syntax: UDP.remoteIP(); Parameters: NoneReturns: 4 bytes : the IP address of the remote connection

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

void setup() { // start the Ethernet and UDP: Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() { int packetSize = Udp.parsePacket(); if(packetSize)

53

Page 55: Arduino Language Reference

{ Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From IP : "); IPAddress remote = Udp.remoteIP();

//print out the remote connection's IP address Serial.print(remote); Serial.print(" on port : ");

//print out the remote connection's port Serial.println(Udp.remotePort()); }}

Ethernet

UDP.remotePort()

Gets the port of the remote UDP connection. This function must be called after UDP.parsePacket().

Syntax: UDP.remotePort(); Parameters: NoneReturns: int : the port of the UDP connection to a remote host

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

void setup() { // start the Ethernet and UDP: Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() { int packetSize = Udp.parsePacket();

54

Page 56: Arduino Language Reference

if(packetSize) { Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); IPAddress remote = Udp.remoteIP(); for (int i =0; i < 4; i++) { Serial.print(remote[i], DEC); if (i < 3) { Serial.print("."); } } Serial.print(", port "); Serial.println(Udp.remotePort());

// read the packet into packetBufffer Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer); }}

Ethernet

UDP.write()

Writes UDP data to the remote connection. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called.

Syntax: UDP.write(message); Parameters: message: the outgoing message (char)Returns: byte : returns the number of characters sent. This does not have to be read

Example

#include <SPI.h> #include <Ethernet.h>#include <EthernetUdp.h>// Enter a MAC address and IP address for your controller below.// The IP address will be dependent on your local network:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };IPAddress ip(192, 168, 1, 177);unsigned int localPort = 8888; // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

55

Page 57: Arduino Language Reference

void setup() {

// start the Ethernet and UDP:

Ethernet.begin(mac,ip); Udp.begin(localPort);}

void loop() { Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write("hello"); Udp.endPacket();}

Ethernet

if (EthernetClient)

Indicates if the specified Ethernet client is ready.

Syntax: if (client)Parameters: noneReturns: boolean : returns true if the specified client is available.Example

#include <Ethernet.h>#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 10, 0, 0, 177 };byte server[] = { 64, 233, 187, 99 }; // GoogleEthernetClient client;

void setup(){ Ethernet.begin(mac, ip); Serial.begin(9600); delay(1000);

Serial.println("connecting..."); while(!client){ ; // wait until there is a client connected to proceed } if (client.connect(server, 80)) { Serial.println("connected"); client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } else { Serial.println("connection failed"); }}

56

Page 58: Arduino Language Reference

void loop(){ if (client.available()) { char c = client.read(); Serial.print(c); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; }}

Ethernet Server class

server.available()

Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop().

available() inherits from the Stream utility class.

Syntax: server.available()Parameters: NoneReturns: a Client object; if no Client has data available for reading, this object will evaluate to

false in an if-statement (see the example below)

Example

#include <Ethernet.h> #include <SPI.h>

// the media access control (ethernet hardware) address for the shield: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield: byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address: byte gateway[] = { 10, 0, 0, 1 }; // the subnet: byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23 EthernetServer server = EthernetServer(23);

void setup() { // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

57

Page 59: Arduino Language Reference

// start listening for clients server.begin(); }

void loop() { // if an incoming client connects, there will be bytes available to read: EthernetClient client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read()); } }

Ethernet : Server class

server.begin()

Tells the server to begin listening for incoming connections.

Syntax: server.begin()

Parameters: None

Returns: None

Example

#include <SPI.h> #include <Ethernet.h>

// the media access control (ethernet hardware) address for the shield: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield: byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address: byte gateway[] = { 10, 0, 0, 1 }; // the subnet: byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23 EthernetServer server = EthernetServer(23);

void setup() { // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

// start listening for clients server.begin();

58

Page 60: Arduino Language Reference

}

void loop() { // if an incoming client connects, there will be bytes available to read: EthernetClient client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read()); } }

Ethernet : Server class

Server()

Create a server that listens for incoming connections on the specified port.

Syntax: Server(port);

Parameters: port: the port to listen on (int)

Returns: None

Example

#include <Ethernet.h>

// network configuration. gateway and subnet are optional.

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address:byte gateway[] = { 10, 0, 0, 1 };// the subnet:byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23Server server = Server(23);

void setup(){ // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

// start listening for clients server.begin();}

59

Page 61: Arduino Language Reference

void loop(){ // if an incoming client connects, there will be bytes available to read: Client client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read()); }}

Ethernet : Server class

server.print()

Print data to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: server.print(data) server.print(data, BASE)

Parameters: data: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte print() will return the number of bytes written, though reading that number is

optional

Ethernet : Server class

server.println()

Print data, followed by a newline, to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: server.println() server.println(data) server.println(data, BASE)

Parameters: data (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Ethernet : Server class

60

Page 62: Arduino Language Reference

server.write()

Write data to all the clients connected to a server.

Syntax: server.write(data)

Parameters: data: the value to write (byte or char)

Returns: None

Example

#include <Ethernet.h>

// network configuration. gateway and subnet are optional.

// the media access control (ethernet hardware) address for the shield:byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //the IP address for the shield:byte ip[] = { 10, 0, 0, 177 }; // the router's gateway address:byte gateway[] = { 10, 0, 0, 1 };// the subnet:byte subnet[] = { 255, 255, 0, 0 };

// telnet defaults to port 23Server server = Server(23);

void setup(){ // initialize the ethernet device Ethernet.begin(mac, ip, gateway, subnet);

// start listening for clients server.begin();}

void loop(){ // if an incoming client connects, there will be bytes available to read: Client client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read()); }}

61

Page 63: Arduino Language Reference

Firmata Library

The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using.

Methods

begin()start the library

begin(long)start the library and override the default baud rate

printVersion()send the protocol version to the host computer

blinkVersion()blink the protocol version on pin 13

printFirmwareVersion()send the firmware name and version to the host computer

setFirmwareVersion(byte major, byte minor)set the firmware name and version, using the sketch's filename, minus the .pde

Sending Messages

sendAnalog(byte pin, int value)send an analog message

sendDigitalPorts(byte pin, byte firstPort, byte secondPort)send digital ports as individual bytes

sendDigitalPortPair(byte pin, int value)send digital ports as one int

sendSysex(byte command, byte bytec, byte* bytev)send a command with an arbitrary array of bytes

sendString(const char* string)send a string to the host computer

sendString(byte command, const char* string)send a string to the host computer using a custom command type

Receiving Messages

available()check to see if there are any incoming messages in the buffer

62

Page 64: Arduino Language Reference

processInput()process incoming messages from the buffer, sending the data to any registered callback functions

attach(byte command, callbackFunction myFunction)attach a function to an incoming message type

detach(byte command)detach a function from an incoming message type

Callback Functions

In order to attach your function to a message type, your function must match the standard callback function. There are currently three types of callback functions in Firmata: generic, string, and sysex.

genericvoid callbackFunction(byte pin, int value);

system_resetvoid systemResetCallbackFunction(void);

stringvoid stringCallbackFunction(char *myString);

sysexvoid sysexCallbackFunction(byte pin, byte byteCount, byte *arrayPointer);

Message TypesThese are the various message types that you can attach functions to.

ANALOG_MESSAGEthe analog value for a single pin

DIGITAL_MESSAGE8-bits of digital pin data (one port)

REPORT_ANALOGenable/disable the reporting of analog pin

REPORT_DIGITALenable/disable the reporting of a digital port

SET_PIN_MODEchange the pin mode between INPUT/OUTPUT/PWM/etc.

FIRMATA_STRINGC-style strings, uses stringCallbackFunction for the function typeSYSEX_STARTgeneric, arbitrary length messages (via MIDI SysEx protocol), uses sysexCallbackFunction for the function type

63

Page 65: Arduino Language Reference

SYSTEM_RESETmessage to reset firmware to its default state, uses systemResetCallbackFunction for the function type

Example

This example shows how to send and receive analog messages using Firmata.

#include <Firmata.h>byte analogPin;

void analogWriteCallback(byte pin, int value){ pinMode(pin,OUTPUT); analogWrite(pin, value);}

void setup(){ Firmata.setFirmwareVersion(0, 1); Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); Firmata.begin();}

void loop(){ while(Firmata.available()) { Firmata.processInput(); } for(analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { Firmata.sendAnalog(analogPin, analogRead(analogPin)); }}

float()

Converts a value to the float data type.

Syntax: float(x)Parameters: x: a value of any typeReturns: float

Notes: See the reference for float for details about the precision and limitations of floating point numbers on Arduino.

64

Page 66: Arduino Language Reference

float

Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers are often used to approximate analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information.

Floats have only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.

Floating point numbers are not exact, and may yield strange results when compared. For example 6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference between the numbers is less than some small number.

Floating point math is also much slower than integer math in performing calculations, so should be avoided if, for example, a loop has to run at top speed for a critical timing function. Programmers often go to some lengths to convert floating point calculations to integer math to increase speed.

Examples

float myfloat; float sensorCalbrate = 1.117;

Syntax: float var = val;* var - your float variable name* val - the value you assign to that variable

Example Code

int x; int y; float z;

x = 1; y = x / 2; // y now contains 0, ints can't hold fractions z = (float)x / 2.0; // z now contains .5 (you have to use 2.0, not 2)

for statements

The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.

There are three parts to the for loop header:

for (initialization; condition; increment) {//statement(s);

}

65

Page 67: Arduino Language Reference

The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it's true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.

Example

// Dim an LED using a PWM pinint PWMpin = 10; // LED in series with 470 ohm resistor on pin 10

void setup(){ // no setup needed}

void loop(){ for (int i=0; i <= 255; i++){ analogWrite(PWMpin, i); delay(10); } }

Coding Tips

The C for loop is much more flexible than for loops found in some other computer languages, including BASIC. Any or all of the three header elements may be omitted, although the semicolons are required. Also the statements for initialization, condition, and increment can be any valid C statements with unrelated variables, and use any C datatypes including floats. These types of unusual for statements may provide solutions to some rare programming problems.

For example, using a multiplication in the increment line will generate a logarithmic progression:

for(int x = 2; x < 100; x = x * 1.5){println(x);

}

Generates: 2,3,4,6,9,13,19,28,42,63,94

Another example, fade an LED up and down with one for loop:

void loop(){ int x = 1; for (int i = 0; i > -1; i = i + x){ analogWrite(PWMpin, i); if (i == 255) x = -1; // switch direction at peak delay(10); } }

floating point constants

66

Page 68: Arduino Language Reference

Similar to integer constants, floating point constants are used to make code more readable. Floating point constants are swapped at compile time for the value to which the expression evaluates.

Examples:

n = .005;

Floating point constants can also be expressed in a variety of scientific notation. 'E' and 'e' are both accepted as valid exponent indicators.

floating-point constant evaluates to: also evaluates to:

10.0 102.34E5 2.34 * 10^5 23400067e-12 67.0 * 10^-12 .000000000067

Functions

Segmenting code into functions allows a programmer to create modular pieces of code that perform a defined task and then return to the area of code from which the function was "called". The typical case for creating a function is when one needs to perform the same action multiple times in a program.

For programmers accustomed to using BASIC, functions in Arduino provide (and extend) the utilityof using subroutines (GOSUB in BASIC).

Standardizing code fragments into functions has several advantages:* Functions help the programmer stay organized. Often this helps to conceptualize the program.

* Functions codify one action in one place so that the function only has to be thought out and debugged once.

* This also reduces chances for errors in modification, if the code needs to be changed.* Functions make the whole sketch smaller and more compact because sections of code are reused many times.

* They make it easier to reuse code in other programs by making it more modular, and as a nice side effect, using functions also often makes the code more readable.

There are two required functions in an Arduino sketch, setup() and loop(). Other functions must be created outside the brackets of those two functions. As an example, we will create a simple function to multiply two numbers.

Example

To "call" our simple multiply function, we pass it parameters of the datatype that it is expecting:

void loop{int i = 2;int j = 3;

67

Page 69: Arduino Language Reference

int k;k = myMultiplyFunction(i, j); // k now contains 6

}

Our function needs to be declared outside any other function, so "myMultiplyFunction()" can go either above or below the "loop()" function.

The entire sketch would then look like this:

void setup(){ Serial.begin(9600);}void loop() { int i = 2; int j = 3; int k;

k = myMultiplyFunction(i, j); // k now contains 6 Serial.println(k); delay(500);}int myMultiplyFunction(int x, int y){ int result; result = x * y; return result;}

Another example

This function will read a sensor five times with analogRead() and calculate the average of five readings. It then scales the data to 8 bits (0-255), and inverts it, returning the inverted result.

int ReadSens_and_Condition(){ int i; int sval = 0;

for (i = 0; i < 5; i++){ sval = sval + analogRead(0); // sensor on analog pin 0 }

sval = sval / 5; // average sval = sval / 4; // scale to 8 bits (0 - 255) sval = 255 - sval; // invert output return sval;}

To call our function we just assign it to a variable.

int sens;sens = ReadSens_and_Condition();

68

Page 70: Arduino Language Reference

GLCD Library

The library is based on the excellent ks0108 graphics routines written and copyright by Fabian Maximilian Thiele. The site link in his code does not respond but you can obtain a copy of his original work in the download section at the end of this article.

The code here has been converted to an Arduino library, has more flexibility in port addressing and improvements in I/O speed. The interface has been made more Arduino friendly and some convenience functions added. The method naming is mostly unchanged to facilitate porting of code written for the original version. Some methods now have default arguments to make them easer to use.

The test sketch included in the download demonstrates many of the capabilities of the library and if you start with this and use the default Arduino pin assignments, it is a good way to make sure that everything is working before you customize your configuration. Here is a simplified version of the example sketch in the download:

GLCD example sketch

#include <ks0108.h> // library header #include <Arial14.h> // font definition for 14 point Arial font. #include "SystemFont5x7.h" // system font #include "ArduinoIcon.h" // bitmap

unsigned long startMillis; unsigned int iter = 0;

void setup() { GLCD.Init(NON_INVERTED); // initialise the library GLCD.ClearScreen(); GLCD.DrawBitmap(ArduinoIcon, 32,0, BLACK); //draw the bitmap at the x,y position delay(3000); GLCD.ClearScreen(); GLCD.SelectFont(System5x7); // select fixed width system font } void loop() { // run over and over again startMillis = millis(); while( millis() - startMillis < 1000) { // loop for one second GLCD.DrawRect(0, 0, 64, 61, BLACK); // rectangle in left side of screen GLCD.DrawRoundRect(68, 0, 58, 61, 5, BLACK); // rounded rectangle around text area for(int i=0; i < 62; i += 4) GLCD.DrawLine(1,1,63,i, BLACK); // draw lines from upper left down right side of rectangle GLCD.DrawCircle(32,31,30,BLACK); // draw circle centered in the left side of screen GLCD.FillRect(92,40,16,16, WHITE); // clear previous spinner position GLCD.CursorTo(5,5); // locate curser for printing text GLCD.PrintNumber(++iter); // print current iteration at the current cursor position } // display number of iterations in one second GLCD.ClearScreen(); // clear the screen GLCD.CursorTo(13,2); // positon cursor GLCD.Puts("FPS= "); // print a text string GLCD.PrintNumber(iter); // print a number

69

Page 71: Arduino Language Reference

}}

GLCD Functions:

This is a list of functions supported by the library. (Refer to the included HTML library documentation for the latest and most complete documentation)

GLCD.Init(invert) initialize the library for normal or inverted drawing. If invert is false, drawing sets pixels, if true pixels are cleared when drawn (see also SetInverted method)

GLCD.GotoXY(x,y) locate the graphic cursor at positions x and y, 0,0 is upper left corner

GLCD.ClearScreen() clear the LCD screen

// Graphic Drawing Functions (color WHITE clears pixels, BLACK sets pixels)

GLCD.DrawCircle(x, y, radius, color) draw circle with center at x,yGLCD.DrawLine(x1,y1,x2,y2,color) draw line from x1,y1 to x2,y2 GLCD.DrawVertLine(x, y, length, color) draw vertical line GLCD.DrawHoriLine(x, y, length, color) draw horizontal line GLCD.DrawRect(x, y, width, height, color) draw rectangle GLCD.DrawRoundRect(x, y, width, height, radius, color) as above with rounded edges GLCD.FillRect(x, y, width, height, color) draw filled rectangle GLCD.InvertRect(x, y, width, height) invert pixels within given rectangle GLCD.SetInverted(invert) set drawing mode to inverted GLCD.SetDot(x, y, color); draw a dot in the given color at the given location GLCD.DrawBitmap(bitmap, x, y, color); draw the bitmap at the given x,y position

// Font Functions GLCD.SelectFont(font, color ) select font, defaults color to black if not specifiedGLCD.PutChar(character) print given character to screen at current cursor

locationGLCD.Puts(string) print given string to screen at current cursor locationGLCD.Puts_P(string) print string from program memory to screen at current

cursor locationGLCD.PrintNumber(number) print the decimal value of the given number at current

cursor locationGLCD.CursorTo(x, y); // 0 based coordinates for fixed width fonts (i.e. the

supplied system font)

Note: valid colors are BLACK (sets pixels) or WHITE (clears pixels)

Wiring and Configuration:

In v3 there are 3 types of configuration:

Library Panel

Pin

70

Page 72: Arduino Language Reference

Each type of configuration is handled by separate configuration files.

The library configuration is handled by glcd/glcd_Config.h The library configuration determines things like panel type, as well as a few other options. It is the master configuration file. The panel configuration is used to configure things that are specific to a particular glcd panel like the geometry of the display, the chip select lines, and the low level timing for the panel. The glcd_Config.h library configuration file specifies which panel configuration file to use.

The pin configuration is used to assign pins. A given panel configuration will automatically determine which pin configuration file to use based on which board type is being used in the IDE.

Pin assignments are contained in the appropriate pin configuration header file in glcd/config for the supported controller chips. These controller types are supported in the current version:

ks0108_arduino.h <- this is for ATmega168 and ATmega328 boards ks0108_mega.h <- for the Arduino Mega (ATmega1280/2560) ks0108_Sanguino.h <- for Sanguino (ATmega644) ks0108_Teensy.h <- for Teensy/Teensy++

See the readme file, glcd/glcd_Config.h and included HTML documentation supplied with the download for more details on configuration.

It is suggested that you wire up the panel using the default pin assignments. This diagram shows how panels should be connected using the default pin assignments in the distributed library.

Connections for common GLCD panels:

GLCD Panel Pinouts

Arduino 168

Mega FunctionPinout

APinout

BPinout

C Pinout

D Comments

5V 5V +5 volts 1 !2! !2! 4

Gnd Gnd GND 2 !1! !1! 3

external externalVo (Contrast

in)3 3 3 5

Connect to Wiper of contrast pot (Middle pin)

8 22 D0 4 7 7 9

9 23 D1 5 8 8 10

10 24 D2 6 9 9 11

11 25 D3 7 10 10 12

4 26 D4 8 11 11 13

5 27 D5 9 12 12 14

6 28 D6 10 13 13 15

7 29 D7 11 14 14 16

14 (alog0) 33 CSEL1 12 15 16 1 Chip 1 select

15 (alog1) 34 CSEL2 13 16 15 2 Chip 2 select

71

Page 73: Arduino Language Reference

Reset Reset 14 17 17Connect to reset pin (see

Reset pin note below)

16 (alog2) 35 R_W 15 5 5 7 Read/write

17 (alog3) 36 D_I 16 4 4 6 Data/Instruction (aka RS)

18 (alog4) 37 EN 17 6 6 8 Enable

external externalVee

(Contrast out)

18 18 18 connect to one leg of 10k

or 20k pot

external external Backlight +5 19 19 19 100 to 330 ohm resistor to

+5v

Gnd GndBacklight

Gnd20 20 20

Gnd n/a n/a n/a n/a n/a n/aconnect other leg of contrast pot to Gnd

Reset Function Note:

If the IDE fails to upload the Arduino when the glcd module's reset line is attached to the Arduino board's reset pin, see the troubleshooting guide below for remedies.

Pinout A panels:

• HDM64GS12L-4 • Crystalfontz CFAG12864B (tested by biomed) • Sparkfun LCD-00710CM (tested by biomed) • NKC Electronics LCD-0022 (tested by NKC Electronics)

Pinout B panels:

• HDM64GS12L-5 • Lumex LCM-S12864GSF (tested by jowan) • Futurlec BLUE128X64LCD (tested by tyggerjai) • AZ Displays AGM1264F (tested by santy) • Displaytech 64128A BC (tested by Udo Klein) • Adafruit GLCD (Leave RESET pin disconnected or you may experience upload problems)

(tested by Things) • DataVision DG12864-88 (tested by wglover) • Topway LM12864LDW (tested by zandaa) • Satistronics RT12864J-1 (tested by doublet) • Digitron SG12864J4 (also appears to need RESET disconnected for uploads) • Unknown manufacturer QY-12864F (tested by SphiNx) • Unknown manufacturer TM12864L-2 (tested by frantorres) • Unknown manufacturer 12864J-1 (tested by pixelk) • Huahong Technology Ltd LMG12864 (LMG-SSC12A64DRY(-H) variant, yellow green

backlight, black on green) (tested by yxskaft) • Sure Electronics DE-LM105 (tested by imode) • Wide.hk "LCD Shield Pro + GLCD 128x64 LCD" (tested by universam) 6-way Keypad

shortens CS1 (A0) to ground!

72

Page 74: Arduino Language Reference

Pinout C panels:

• Shenzhen Jinghua Displays Co Ltd. JM12864 (tested by macpod) • Vee (pin 3) should be left disconnected. The pot on the display controls contrast • Backlight LED may already have resistors added.

Pinout D panels:

• Various 192 x 64 displays:

Brand Model Chip Contrast

Wintek- Cascades WD-G1906G KS0108B -7.5 to -10v

Wintek - GEN WD-G1906G KS0108B -7.5 to -10v

Wintek WD-G1906G S6B0108A -9.5 to -12v

TECDIS Y19061 HD61202 -7.5 to -10v

Varitronix MGLS19264 HD61202 -8.5 to -10.5v

• The contrast voltage is negative with respect to ground. • Backlight is 4.7v requiring 10-12 ohm resistor from +5v. • The ks0108_Manual_Config.h needs to be used and modified as below.

1. define DISPLAY_WIDTH 192 2. define DISPLAY_HEIGHT 64

and

1. elif glcd_CHIP_COUNT == 3 2. define glcd_CHIP0 glcdCSEL1,LOW, glcdCSEL2,LOW 3. define glcd_CHIP1 glcdCSEL1,LOW, glcdCSEL2,HIGH 4. define glcd_CHIP2 glcdCSEL1,HIGH, glcdCSEL2,LOW

(You are welcome to add other panels to the above lists that are tested and working with this library. But if you add a new panel pinout type column to the table i.e. E, F, G, etc... PLEASE, PLEASE add them to the end using the next available letter and do not shift existing letters around.)

This diagram shows wiring of the common type A panel. Check to see how your panel datasheet matches the connector assignments before wiring up. Take particular care that the +5v and ground connections are correct!

73

Page 75: Arduino Language Reference

Wiring up the external components:

Most GLCD panels require an external preset pot to set the LCD working voltage (contrast) and a fixed resistor to limit the current in the backlight. The datasheet for your panel should provide specific information on the wiring and choice of components. A suggestion for wiring these up is to use a small piece of strip-board with header pins for 5V, ground and Reset providing connection to the Arduino. See the diagram above for layout.

74

Page 76: Arduino Language Reference

Contrast Pot NOTE:

Play close attention for how to wire up the contrast pot. ks0108 modules do not wire up their contrast pot the same way as a typical hd44780 lcd. A hd44780 typically hooks its contrast pot legs to +5v and GND. On a ks0108, the pot, which is typically between 10-20k, is used to create a varying negative voltage from Vee up to GND that is used to feed to the Vo input signal. In order to do this, one leg of the pot needs to hook to ground, one leg needs to hook to the Vee negative voltage output pin and then the wiper (middle pin of the pot) will have the variable voltage output that can be fed to the Vo contrast control input pin.

Changing the Arduino pin assignments:

The KS0108 chip needs lots of pins. 8 data pins and 5 command pins are required in addition to the power connections. Ideally the command pins should all be on one port and all the data pins together on another. In practice this is not easy to do on a standard arduino.

Starting with glcd v3, pin assignment is much more flexible as any glcd function or data pin can be assigned to any Arduino pin. If you split data pins across ports the code will run slightly slower, but for all but the most speed critical graphic applications its not significant. To change pin assignments you must modify the appropriate pin configuration file in the glcd/config directory (ks0108.h when using a m328 based arduino). Find the section in the file that begins:

Configuration for assigning LCD bits to Arduino Pins

You will see the defines for the data pins and the five control pins with their default pin assignments:

Name Arduino pin number

#define glcdData0Pin 8 #define glcdData1Pin 9 #define glcdData2Pin 10 #define glcdData3Pin 11 #define glcdData4Pin 4 #define glcdData5Pin 5 #define glcdData6Pin 6 #define glcdData7Pin 7 #define glcdCSEL1 14 (Analog pin 0) #define glcdCSEL2 15 (Analog pin 1) #define glcdRW 16 (Analog pin 2) #define glcdDI 17 (Analog pin 3) #define glcdEN 18 (Analog pin 4)

Any of these data pins and glcd functions can be assigned to any pin (as long as its not used by something else) Here are the pin/port mappings for the Arduino m328 processor:

Port B 8-13 Port C 14-19 (the analog pins) Port D 0-7 (note 0 and 1 are used by hardware serial)

75

Page 77: Arduino Language Reference

While any Arduino pin can can be used for any glcd data pin, using Arduino pins that are all in the same port and that are in consecutive bit order will give slightly higher performance. The default pin assignments for the glcd data pins are assigned to take advantage of this optimization.

An example of remapping a pin might be to change glcdEN to use some other pin rather than 18 to allow using i2c on a m328 based board.

Troubleshooting

No pixels visible on the display

Check +5v and Gnd connections between Arduino and GLCD panel Check that all data and command pins are wired correctly Check contrast voltage (typically between -3 and -4 volts) on contrast-in pin of LCD panel. While the sketch is operating, try gradually adjusting the pot through its range. Some displays are very sensitive to this setting. Check sketch has compiled ok and downloaded to the arduino.

Left and right side of image reversed

swap CSEL1 and CSEL2 wires (or swap pin assignments in header file)

Display garbled

check all data and command pins are wired correctly and that these match the setting in the header file.

Sketch upload not working

Try the glcd with nothing connected to its reset line Try connecting the glcd reset line to vcc enable the library software reset functionality

GLCD reset pin NOTE:

The Arduino autoreset circuit is quit fragile. Depending on the particular Arduino board and glcd module, connecting the glcd module to the Arduino board reset line may interfere with the Arduino board's autoreset circuit. Most glcds will reset on power up so the glcd reset line can be left unconnected. Most of the remaining others will work when their reset line is connected to vcc. A small fraction of the glcds out there will need a reset pulse. For those that need a reset pulse and connecting the glcd to the arduino reset line causes the autoreset on the aruduino board to fail, the library must be used to reset the glcd which requires another Arduino pin. In order to enable this functionality edit the pin configuration file and uncomment the line that looks like this:

// Reset Bit - uncomment the next line if reset is connected to an output pin //#define glcdRES 19 // Reset Bit

And then connect the Arduino pin specified by glcdRES to the glcd module's reset pin.

Still having problems, see the forum discussion links below.

76

Page 78: Arduino Language Reference

Create your own fonts and icons

There is a free java application available that can convert any of your PC fonts for use with this library. The software is called FontCreator2 and it can produce a header file that stores font definitions in program memory when included in your sketch. See the included HTML documentation for more information about this as well as some web site links for obtaining additional fonts.

Embeding images in your firmware

A Processing sketch is provided in the download that converts bmp images to files that can be used by the library to display the image on the LCD. See the documentation in the download for more information.

Example

/** Basic test code for the Arduino KS0108 GLCD library. This code exercises a range of graphic * functions supported by the library and is an example of its use. It also gives an indication of * performance, showing the number of frames drawn per second. */

#include <ks0108.h>#include "Arial14.h" // proportional font#include "SystemFont5x7.h" // system font#include "ArduinoIcon.h" // bitmap unsigned long startMillis;unsigned int loops = 0;unsigned int iter = 0;

void setup(){ delay(500); // allow time for LCD to reset GLCD.Init(NON_INVERTED); // initialise the library, non inverted writes pixels onto a clear screen GLCD.ClearScreen(); GLCD.DrawBitmap(ArduinoIcon, 32,0, BLACK); //draw the bitmap at the given x,y position GLCD.SelectFont(System5x7); // switch to fixed width system font countdown(5); GLCD.ClearScreen(); introScreen(); // show some intro stuff GLCD.ClearScreen();}void introScreen(){ GLCD.SelectFont(Arial_14); // you can also make your own fonts, see playground for details GLCD.GotoXY(20, 2); GLCD.Puts("GLCD version "); GLCD.PrintNumber(GLCD_VERSION); GLCD.DrawRoundRect(16,0,99,18, 5, BLACK); // rounded rectangle around text area GLCD.SelectFont(System5x7); // switch to fixed width system font showCharacters(); countdown(5);}

77

Page 79: Arduino Language Reference

void showCharacters(){ byte line = 3; // start on the fourth line for(byte c = 32; c <=127; c++){ if( (c-32) % 20 == 0) GLCD.CursorTo(1,line++); // CursorTo is used for fixed width system font GLCD.PutChar(c); } }

void drawSpinner(byte pos, byte x, byte y) { // this draws an object that appears to spin switch(pos % 8) { case 0 : GLCD.DrawLine( x, y-8, x, y+8, BLACK); break; case 1 : GLCD.DrawLine( x+3, y-7, x-3, y+7, BLACK); break; case 2 : GLCD.DrawLine( x+6, y-6, x-6, y+6, BLACK); break; case 3 : GLCD.DrawLine( x+7, y-3, x-7, y+3, BLACK); break; case 4 : GLCD.DrawLine( x+8, y, x-8, y, BLACK); break; case 5 : GLCD.DrawLine( x+7, y+3, x-7, y-3, BLACK); break; case 6 : GLCD.DrawLine( x+6, y+6, x-6, y-6, BLACK); break; case 7 : GLCD.DrawLine( x+3, y+7, x-3, y-7, BLACK); break; } }

void countdown(int count){ while(count--){ // do countdown GLCD.CursorTo(0,1); // first column, second row (offset is from 0) GLCD.PutChar(count + '0'); delay(1000); } }

void loop(){ // run over and over again iter = 0; startMillis = millis(); while( millis() - startMillis < 1000){ // loop for one second GLCD.DrawRect(0, 0, 64, 61, BLACK); // rectangle in left side of screen GLCD.DrawRoundRect(68, 0, 58, 61, 5, BLACK); // rounded rectangle around text area for(int i=0; i < 62; i += 4) GLCD.DrawLine(1,1,63,i, BLACK); // draw lines from upper left down right side of rectangle GLCD.DrawCircle(32,31,30,BLACK); // draw circle centered in the left side of screen GLCD.FillRect(92,40,16,16, WHITE); // clear previous spinner position drawSpinner(loops++,100,48); // draw new spinner position //GLCD.FillRect(24,txtLINE3,14,14, WHITE); // clear text area that will be drawn below GLCD.CursorTo(5,5); // locate curser for printing text GLCD.PrintNumber(++iter); // print current iteration at the current cursor position } // display number of iterations in one second GLCD.ClearScreen(); // clear the screen GLCD.CursorTo(14,2); // positon cursor GLCD.Puts("FPS= "); // print a text string GLCD.PrintNumber(iter); // print a number }

78

Page 80: Arduino Language Reference

goto

Transfers program flow to a labeled point in the program

Syntax: label:goto label; // sends program flow to the label

Tip: The use of goto is discouraged in C programming, and some authors of C programming books claim that the goto statement is never necessary, but used judiciously, it can simplify certain programs. The reason that many programmers frown upon the use of goto is that with the unrestrained use of goto statements, it is easy to create a program with undefined program flow, which can never be debugged.

With that said, there are instances where a goto statement can come in handy, and simplify coding. One of these situations is to break out of deeply nested for loops, or if logic blocks, on a certain condition.

Example

for(byte r = 0; r < 255; r++){ for(byte g = 255; g > -1; g--){ for(byte b = 0; b < 255; b++){ if (analogRead(0) > 250){ goto bailout;} // more statements ... } }}bailout://

highByte()

Extracts the high-order (leftmost) byte of a word (or the second lowest byte of a larger data type).

Syntax: highByte(x)

Parameters: x: a value of any type

Returns: byte

if

if, which is used in conjunction with a comparison operator, tests whether a certain condition has been reached, such as an input being above a certain number. The format for an if test is:

if (someVariable > 50){ // do something here}

79

Page 81: Arduino Language Reference

The program tests to see if someVariable is greater than 50. If it is, the program takes a particular action. Put another way, if the statement in parentheses is true, the statements inside the brackets are run. If not, the program skips over the code.

The brackets may be omitted after an if statement. If this is done, the next line (defined by the semicolon) becomes the only conditional statement.

if (x > 120) digitalWrite(LEDpin, HIGH);

if (x > 120)digitalWrite(LEDpin, HIGH);

if (x > 120){ digitalWrite(LEDpin, HIGH); }

if (x > 120){ digitalWrite(LEDpin1, HIGH); digitalWrite(LEDpin2, HIGH); } // all are correct

The statements being evaluated inside the parentheses require the use of one or more operators:

Comparison Operators:

x == y (x is equal to y) x != y (x is not equal to y) x < y (x is less than y) x > y (x is greater than y) x <= y (x is less than or equal to y) x >= y (x is greater than or equal to y)

Warning: Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The single equal sign is the assignment operator, and sets x to 10 (puts the value 10 into the variable x). Instead use the double equal sign (e.g. if (x == 10) ), which is the comparison operator, and tests whether x is equal to 10 or not. The latter statement is only true if x equals 10, but the former statement will always be true. This is because C evaluates the statement if (x=10) as follows: 10 is assigned to x (remember that the single equal sign is the assignment operator), so x now contains 10. Then the 'if' conditionalevaluates 10, which always evaluates to TRUE, since any non-zero number evaluates to TRUE. Consequently, if (x = 10) will always evaluate to TRUE, which is not the desired result when using an 'if' statement. Additionally, the variable x will be set to 10, which is also not a desired action.

if can also be part of a branching control structure using the if...else] construction.

if / else

if/else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped together. For example, an analog input could be tested and one action taken if the input was less than 500, and another action taken if the input was 500 or greater. The code would look like this:

80

Page 82: Arduino Language Reference

if (pinFiveInput < 500){ // action A}else{ // action B}

else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.

Each test will proceed to the next one until a true test is encountered. When a true test is found, its associated block of code is run, and the program then skips to the line following the entire if/else construction. If no test proves to be true, the default else block is executed, if one is present, and sets the default behavior.Note that an else if block may be used with or without a terminating else block and vice versa. An unlimited number of such else if branches is allowed.

if (pinFiveInput < 500){ // do Thing A}else if (pinFiveInput >= 1000){ // do Thing B}else{ // do Thing C}

Another way to express branching, mutually exclusive tests, is with the switch case statement.

clude

#include is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C libraries (groups of pre-made functions), and also libraries written especially for Arduino.

The main reference page for AVR C libraries (AVR is a reference to the Atmel chips on which the Arduino is based) is here.

Note that #include, similar to #define, has no semicolon terminator, and the compiler will yield cryptic error messages if you add one.

Example

This example includes a library that is used to put data into the program space flash instead of ram. This saves the ram space for dynamic memory needs and makes large lookup tables more practical.

81

Page 83: Arduino Language Reference

#include <avr/pgmspace.h>

prog_uint16_t myConstants[] PROGMEM = {0, 21140, 702 , 9128, 0, 25764, 8456,0,0,0,0,0,0,0,0,29810,8968,29762,29762,4500};

+= , -= , *= , /=

Perform a mathematical operation on a variable with another constant or variable. The += (et al) operators are just a convenient shorthand for the expanded syntax, listed below.

Syntax: x += y; // equivalent to the expression x = x + y;x -= y; // equivalent to the expression x = x - y; x *= y; // equivalent to the expression x = x * y; x /= y; // equivalent to the expression x = x / y;

Parameters: x: any variable typey: any variable type or constant

Examples

x = 2;x += 4; // x now contains 6x -= 3; // x now contains 3x *= 10; // x now contains 30x /= 2; // x now contains 15

++ (increment) / -- (decrement)

Increment or decrement a variable

Syntax: x++; // increment x by one and returns the old value of x++x; // increment x by one and returns the new value of xx-- ; // decrement x by one and returns the old value of x --x ; // decrement x by one and returns the new value of x

Parameters: x: an integer or long (possibly unsigned)

Returns: The original or newly incremented / decremented value of the variable.

Examples

x = 2;y = ++x; // x now contains 3, y contains 3y = x--; // x contains 2 again, y still contains 3

82

Page 84: Arduino Language Reference

int()

Converts a value to the int data type.

Syntax: int(x)Parameters: x: a value of any typeReturns: int

Integer Constants

Integer constants are numbers used directly in a sketch, like 123. By default, these numbers are treated as int's but you can change this with the U and L modifiers (see below).

Normally, integer constants are treated as base 10 (decimal) integers, but special notation (formatters) may be used to enter numbers in other bases.

Base Example Formatter Comment

10 (decimal) 123 none

2 (binary) B1111011 leading 'B' only works with 8 bit values (0 to 255)characters 0-1 valid

8 (octal) 0173 leading "0" characters 0-7 valid

16 (hexadecimal) 0x7B leading "0x" characters 0-9, A-F, a-f valid

The binary formatter only works on bytes (8 bits) between 0 (B0) and 255 (B11111111). If it is convenient to input an int (16 bits) in binary form you can do it a two-step procedure such as:

myInt = (B11001100 * 256) + B10101010; // B11001100 is the high byte

U & L formatters

By default, an integer constant is treated as an int with the attendant limitations in values. To specify an integer constant with another data type, follow it with:

* a 'u' or 'U' to force the constant into an unsigned data format. Example 33u* a 'l' or 'L' to force the constant into a long data format. Example 100000L* a 'ul' or 'UL' to force the constant into an unsigned long constant. Example 32767ul

interrupts()

Re-enables interrupts (after they've been disabled by noInterrupts()). Interrupts allow certain important tasks to happen in the background and are enabled by default. Some functions will not work while interrupts are disabled, and incoming communication may be ignored. Interrupts can slightly disrupt the timing of code, however, and may be disabled for particularly critical sections of code.

Parameters: None

83

Page 85: Arduino Language Reference

Returns: None

Example

void setup() {}

void loop(){ noInterrupts(); // critical, time-sensitive code here interrupts(); // other code here}

int

Integers are your primary datatype for number storage, and store a 2 byte value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).

Int's store negative numbers with a technique called 2's complement math. The highest bit, sometimes refered to as the "sign" bit, flags the number as a negative number. The rest of the bits are inverted and 1 is added.

The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations work transparently in the expected manner. There can be an unexpected complication in dealing with the bitshift right operator (&gt;&gt;) however.

Example

int ledPin = 13;

Syntax: int var = val;* var - your int variable name* val - the value you assign to that variable

Coding Tip

When variables are made to exceed their maximum capacity they "roll over" back to their minimumcapacitiy, note that this happens in both directions.

int x x = -32,768; x = x - 1; // x now contains 32,767 - rolls over in neg. direction

x = 32,767; x = x + 1; // x now contains -32,768 - rolls over

84

Page 86: Arduino Language Reference

Mouse – Keyboard - Joystick (Only for Leonardo!)

Keyboard.begin()

When used with the Leonardo board, Keyboard.begin() starts emulating a keyboard connected to a computer. To end control, use Keyboard.end().

Syntax: Keyboard.begin()

Parameters: none

Returns: nothing

Example

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin();}

void loop() { //if the button is pressed if(digitalRead(2)==LOW){ //Send the message Keyboard.print("Hello!"); }}

MouseKeyboard

Keyboard.end()

Stops the Leonardo emulating a keyboard connected to the computer. To start keyboard emulation, use Keyboard.begin().

Syntax: Keyboard.end()

Parameters: none

Returns: nothing

Example

void setup() { //start keyboard communication Keyboard.begin(); //send a keystroke

85

Page 87: Arduino Language Reference

Keyboard.print("Hello!"); //end keyboard communication Keyboard.end();}

void loop() { //do nothing}

Keyboard Modifiers

The Keyboard.write() and Keyboard.press() and Keyboard.release() commands don’t work with every possible ASCII character, only those that correspond to a key on the keyboard. For example, backspace works, but many of the other non-printable characters produce unpredictable results. For capital letters (and other keys), what’s sent is shift plus the character (i.e. the equivalent of pressing both of those keys on the keyboard).

A modifier key is a special key on a computer keyboard that modifies the normal action of another key when the two are pressed in combination.

For more on ASCII values and the characters or functions they represent, see asciitable.com

For multiple key presses use Keyboard.press()

The Leonardo's definitions for modifier keys are listed below:

Key Hex Decimal valueKEY_LEFT_CTRL 0x80 128KEY_LEFT_SHIFT 0x81 129KEY_LEFT_ALT 0x82 130KEY_LEFT_GUI 0x83 131KEY_RIGHT_CTRL 0x84 132KEY_RIGHT_SHIFT 0x85 133KEY_RIGHT_ALT 0x86 134KEY_RIGHT_GUI 0x87 135KEY_UP_ARROW 0xDA 218KEY_DOWN_ARROW 0xD9 217KEY_LEFT_ARROW 0xD8 216KEY_RIGHT_ARROW 0xD7 215KEY_BACKSPACE 0xB2 178KEY_TAB 0xB3 179KEY_RETURN 0xB0 176KEY_ESC 0xB1 177KEY_INSERT 0xD1 209KEY_DELETE 0xD4 212KEY_PAGE_UP 0xD3 211KEY_PAGE_DOWN 0xD6 214KEY_HOME 0xD2 210KEY_END 0xD5 213KEY_CAPS_LOCK 0xC1 193KEY_F1 0xC2 194

86

Page 88: Arduino Language Reference

KEY_F2 0xC3 195KEY_F3 0xC4 196KEY_F4 0xC5 197KEY_F5 0xC6 198KEY_F6 0xC7 199KEY_F7 0xC8 200KEY_F8 0xC9 201KEY_F9 0xCA 202KEY_F10 0xCB 203KEY_F11 0xCC 204KEY_F12 0xCD 205

Keyboard

Keyboard.press()

When called, Keyboard.press() functions as if a key were pressed and held on your keyboard. Useful when using modifier keys. To end the key press, use Keyboard.release() or Keyboard.releaseAll().

It is necessary to call Keyboard.begin() before using press().

Syntax: Keyboard.press()

Parameters: char : the key to press

Returns: None

Example

// use this option for OSX:char ctrlKey = KEY_LEFT_GUI;// use this option for Windows and Linux:// char ctrlKey = KEY_LEFT_CTRL;

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); // initialize control over the keyboard: Keyboard.begin();}

void loop() { while (digitalRead(2) == HIGH) { // do nothing until pin 2 goes low delay(500); } delay(1000); // new document:

87

Page 89: Arduino Language Reference

Keyboard.press(ctrlKey); Keyboard.press('n'); delay(100); Keyboard.releaseAll(); // wait for new window to open: delay(1000);}

Keyboard

Keyboard.print()

Sends a keystroke to a connected computer.

Keyboard.print() must be called after initiating Keyboard.begin().

WARNING: When you use the Keyboard.print() command, the Arduino takes over your keyboard Make sure you have control before you use the command. A pushbutton to toggle the keyboard control state is effective.

Syntax: Keyboard.print(character)Keyboard.print(characters)

Parameters: character : a char or int to be sent to the computer as a keystroke characters : a string to be sent to the computer as a keystroke

Returns: int : number of bytes sent

Example

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin();}

void loop() { //if the button is pressed if(digitalRead(2)==LOW){ //Send the message Keyboard.print("Hello!"); }}

88

Page 90: Arduino Language Reference

Keyboard

Keyboard.println()

Sends a keystroke to a connected computer, followed by a newline and carriage return.

Keyboard.println() must be called after initiating Keyboard.begin().

WARNING: When you use the Keyboard.println() command, the Arduino takes over your keyboard! Make sure you have control before you use the command. A pushbutton to toggle the keyboard control state is effective.

Syntax: Keyboard.println()Keyboard.println(character)Keyboard.println(characters)

Parameters: character : a char or int to be sent to the computer as a keystroke, followed by newline and carriage return.characters : a string to be sent to the computer as a keystroke, followed by a newline and carriage return.

Returns: int : number of bytes sent

Example

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin();}

void loop() { //if the button is pressed if(digitalRead(2)==LOW){ //Send the message Keyboard.println("Hello!"); }}

Keyboard

Keyboard.releaseAll()

Lets go of all keys currently pressed. See Keyboard.press() for additional information.

Syntax: Keyboard.releaseAll()

89

Page 91: Arduino Language Reference

Parameters: None

Returns: int : the number of keys released

Example// use this option for OSX:char ctrlKey = KEY_LEFT_GUI;// use this option for Windows and Linux:// char ctrlKey = KEY_LEFT_CTRL;

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); // initialize control over the keyboard: Keyboard.begin();}

void loop() { while (digitalRead(2) == HIGH) { // do nothing until pin 2 goes low delay(500); } delay(1000); // new document: Keyboard.press(ctrlKey); Keyboard.press('n'); delay(100); Keyboard.releaseAll(); // wait for new window to open: delay(1000);}

Keyboard

Keyboard.release()

Lets go of the specified key. See Keyboard.press() for more information.

Syntax: Keyboard.release(key)

Parameters: key : the key to release. char

Returns: int : the number of keys released

Example

// use this option for OSX:char ctrlKey = KEY_LEFT_GUI;

90

Page 92: Arduino Language Reference

// use this option for Windows and Linux:// char ctrlKey = KEY_LEFT_CTRL;

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); // initialize control over the keyboard: Keyboard.begin();}

void loop() { while (digitalRead(2) == HIGH) { // do nothing until pin 2 goes low delay(500); } delay(1000); // new document: Keyboard.press(ctrlKey); Keyboard.press('n'); delay(100); Keyboard.release(ctrlKey); Keyboard.release('n'); // wait for new window to open: delay(1000);}

Keyboard

Keyboard.write()

Sends a keystroke to a connected computer. This is similar to pressing and releasing a key on your keyboard. You can send some ASCII characters or the additional keyboard modifiers and special keys.

Only ASCII characters that are on the keyboard are supported. For example, ASCII 8 (backspace) would work, but ASCII 25 (Substitution) would not. When sending capital letters, Keyboard.write() sends a shift command plus the desired character, just as if typing on a keyboard. If sending a numeric type, it sends it as an ASCII character (ex. Keyboard.write(97) will send 'a').

For a complete list of ASCII characters, see ASCIITable.com.

WARNING: When you use the Keyboard.write() command, the Arduino takes over your keyboard! Make sure you have control before you use the command. A pushbutton to toggle the keyboard control state is effective.

Syntax: Keyboard.write(character)

Parameters: character : a char or int to be sent to the computer. Can be sent in any notation that's acceptable for a char. For example, all of the below are acceptable and send the same

91

Page 93: Arduino Language Reference

value, 65 or ASCII A:Keyboard.write(65); // sends ASCII value 65, or AKeyboard.write('A'); // same thing as a quoted characterKeyboard.write(0x41); // same thing in hexadecimalKeyboard.write(0b01000001); // same thing in binary (weird choice, but it works)

Returns: int : number of bytes sent

Example

void setup() { // make pin 2 an input and turn on the // pullup resistor so it goes high unless // connected to ground: pinMode(2, INPUT_PULLUP); Keyboard.begin();}

void loop() { //if the button is pressed if(digitalRead(2)==LOW){ //Send an ASCII 'A', Keyboard.write(65); }}

92

Page 94: Arduino Language Reference

/*KeyboardAndMouseControl

Controls the mouse from five pushbuttons on an Arduino Leonardo.

Hardware: * 5 pushbuttons attached to D2, D3, D4, D5, D6

The mouse movement is always relative. This sketch reads four pushbuttons, and uses them to set the movement of the mouse.WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the mouse commands. */

// set pin numbers for the five buttons:const int upButton = 2; const int downButton = 3; const int leftButton = 4;const int rightButton = 5;const int mouseButton = 6;

void setup() { // initialize the buttons' inputs: pinMode(upButton, INPUT); pinMode(downButton, INPUT); pinMode(leftButton, INPUT); pinMode(rightButton, INPUT); pinMode(mouseButton, INPUT);

Serial.begin(9600); // initialize mouse control: Mouse.begin(); Keyboard.begin();}

void loop() { // use serial input to control the mouse: if (Serial.available() > 0) { char inChar = Serial.read();

switch (inChar) { case 'u': // move mouse up Mouse.move(0, -40); break; case 'd': // move mouse down Mouse.move(0, 40); break; case 'l': // move mouse left Mouse.move(-40, 0); break;

93

Page 95: Arduino Language Reference

case 'r': // move mouse right Mouse.move(40, 0); break; case 'm': // move mouse right Mouse.click(MOUSE_LEFT); break; } } // use the pushbuttons to control the keyboard: if (digitalRead(upButton) == HIGH) { Keyboard.write('u'); } if (digitalRead(downButton) == HIGH) { Keyboard.write('d'); } if (digitalRead(leftButton) == HIGH) { Keyboard.write('l'); } if (digitalRead(rightButton) == HIGH) { Keyboard.write('r'); } if (digitalRead(mouseButton) == HIGH) { Keyboard.write('m'); }}

94

Page 96: Arduino Language Reference

/* Keyboard Button test

Sends a text string when a button is pressed.

The circuit: * pushbutton attached from pin 2 to +5V * 10-kilohm resistor attached from pin 4 to ground*/

const int buttonPin = 2; // input pin for pushbuttonint previousButtonState = HIGH; // for checking the state of a pushButtonint counter = 0; // button push counter

void setup() { // make the pushButton pin an input: pinMode(buttonPin, INPUT);

// initialize control over the keyboard: Keyboard.begin();}

void loop() {

// read the pushbutton: int buttonState = digitalRead(buttonPin);

// if the button state has changed, if ((buttonState != previousButtonState)

// and it's currently pressed: && (buttonState == HIGH)) {

// increment the button counter counter++;

// type out a message Keyboard.print("You pressed the button "); Keyboard.print(counter); Keyboard.println(" times."); }

// save the current button state for comparison next time: previousButtonState = buttonState; }

95

Page 97: Arduino Language Reference

/* MouseContinousDrawing

Controls the mouse from two potentiometer on an Arduino Leonardo. Uses a pushbutton to turn on and off mouse control, and a second pushbutton to click the left mouse button

Hardware: * 2 potentiometers connected to pins A0 and A1 * pushbuttons connected to pin D2 and D3

The mouse movement is always relative. This sketch reads two analog inputs that range from 0 to 1023 (or less on either end) and translates them into an offset compared to the previous position. WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the command. This sketch includes a pushbutton to toggle the mouse control state, so you can turn on and off mouse control.*/

// set pin numbers for switch, joystick axes, and LED:const int switchPin = 2; // switch to turn on and off mouse controlconst int mouseButton = 3; // input pin for the mouse pushButtonconst int xAxis = A0; // joystick X axis const int yAxis = A1; // joystick Y axisconst int ledPin = 13; // Mouse control LED

96

Page 98: Arduino Language Reference

// parameters for reading the joystick:int range = 12; // output range of X or Y movementint responseDelay = 5; // response delay of the mouse, in msint threshold = range/4; // resting thresholdint center = range/2; // resting position valueint prevxVal = 0;int prevyVal = 0;

int prevXreading = 0;int prevYreading = 0;int toggle = 0;

boolean mouseIsActive = false; // whether or not to control the mouseint prevSwitchState = LOW; // previous switch stateint prevButtonState = LOW;

void setup() { pinMode(switchPin, INPUT); // the switch pin pinMode(ledPin, OUTPUT); // the LED pin // take control of the mouse: Mouse.begin();}

void loop() { // read the switch: int switchState = digitalRead(switchPin); // if it's changed and it's high, toggle the mouse state: if (switchState != prevSwitchState) { if (switchState == HIGH) { mouseIsActive = !mouseIsActive; // turn on LED to indicate mouse state: digitalWrite(ledPin, mouseIsActive); } }

// save switch state for next comparison: prevSwitchState = switchState;

// read and scale the two axes: // int xReading = readAxis(A0, xVal); // int yReading = readAxis(A1, lastyVal); int currXreading = analogRead(xAxis); int currYreading = analogRead(yAxis);

int xReading = prevXreading - currXreading; int yReading = prevYreading - currYreading;

prevXreading = currXreading; prevYreading = currYreading;

// if the mouse control state is active, move the mouse:

97

Page 99: Arduino Language Reference

if (mouseIsActive) { Mouse.move(xReading, yReading, 0); }

// read the mouse button and click or not click: // if the mouse button is pressed: int buttonState = digitalRead(mouseButton); if (buttonState == HIGH && prevButtonState == LOW) { // if the mouse is not pressed, press it: toggle++; if(toggle == 1) if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } else if(toggle == 2) { // else the mouse button is not pressed: // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } toggle = 0; }

prevButtonState = buttonState;

delay(responseDelay);}

The processing application allow you to draw on the grey screen by pressing the mouse left button and moving the cursor. To let you free to drawing only by moving the two potentiometers, when you press the pushbutton connected to the D3 input, the Leonardo will hold the left mouse click for you until you press the pushbutton another time.

/* * Continuous Lines. * Click and drag the mouse to draw a line. */

void setup() { size(640, 480); background(102);}

void draw() { stroke(255); strokeWeight(10); if(mousePressed) { line(mouseX, mouseY, pmouseX, pmouseY); }}

98

Page 100: Arduino Language Reference

Joystick Control

Example

/*JoystickMouseControlControls the mouse from a joystick on an Arduino Leonardo. Uses a pushbutton to turn on and off mouse control, and a second pushbutton to click the left mouse button

Hardware: * 2-axis joystick connected to pins A0 and A1 * pushbuttons connected to pin D2 and D3

The mouse movement is always relative. This sketch reads two analog inputs that range from 0 to 1023 (or less on either end) and translates them into ranges of -6 to 6. The sketch assumes that the joystick resting values are around the middle of the range, but that they vary within a threshold.

WARNING: When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the command. This sketch includes a pushbutton to toggle the mouse control state, so you can turn on and off mouse control. */

// set pin numbers for switch, joystick axes, and LED:const int switchPin = 2; // switch to turn on and off mouse controlconst int mouseButton = 3; // input pin for the mouse pushButtonconst int xAxis = A0; // joystick X axis const int yAxis = A1; // joystick Y axisconst int ledPin = 5; // Mouse control LED

// parameters for reading the joystick:int range = 12; // output range of X or Y movementint responseDelay = 5; // response delay of the mouse, in msint threshold = range/4; // resting threshold

99

Page 101: Arduino Language Reference

int center = range/2; // resting position value

boolean mouseIsActive = false; // whether or not to control the mouseint lastSwitchState = LOW; // previous switch state

void setup() { pinMode(switchPin, INPUT); // the switch pin pinMode(ledPin, OUTPUT); // the LED pin // take control of the mouse: Mouse.begin();}

void loop() { int switchState = digitalRead(switchPin); // read the switch if (switchState != lastSwitchState) { // if it's changed and it's high, toggle the mouse state if (switchState == HIGH) { mouseIsActive = !mouseIsActive; digitalWrite(ledPin, mouseIsActive); // turn on LED to indicate mouse state } } // save switch state for next comparison: lastSwitchState = switchState;

// read and scale the two axes: int xReading = readAxis(A0); int yReading = readAxis(A1);

// if the mouse control state is active, move the mouse: if (mouseIsActive) { Mouse.move(xReading, yReading, 0); }

// read the mouse button and click or not click: // if the mouse button is pressed: if (digitalRead(mouseButton) == HIGH) { // if the mouse is not pressed, press it: if (!Mouse.isPressed(MOUSE_LEFT)) { Mouse.press(MOUSE_LEFT); } } // else the mouse button is not pressed: else { // if the mouse is pressed, release it: if (Mouse.isPressed(MOUSE_LEFT)) { Mouse.release(MOUSE_LEFT); } }

delay(responseDelay);}

/*

100

Page 102: Arduino Language Reference

reads an axis (0 or 1 for x or y) and scales the analog input range to a range from 0 to <range> */

int readAxis(int thisAxis) { // read the analog input: int reading = analogRead(thisAxis);

// map the reading from the analog input range to the output range: reading = map(reading, 0, 1023, 0, range);

// if the output reading is outside from the // rest position threshold, use it: int distance = reading - center;

if (abs(distance) < threshold) { distance = 0; }

// return the distance for this axis: return distance;}

101

Page 103: Arduino Language Reference

Libraries

Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. To use a library in a sketch, select it from Sketch > Import Library.

Standard Libraries

* EEPROM - reading and writing to "permanent" storage* Ethernet - for connecting to the internet using the Arduino Ethernet Shield* Firmata - for communicating with applications on the computer using a standard serial protocol.* LiquidCrystal - for controlling liquid crystal displays (LCDs)* SD - for reading and writing SD cards* Servo - for controlling servo motors* SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus* SoftwareSerial - for serial communication on any digital pins. Version 1.0 and later of Arduino incorporate Mikal Hart's NewSoftSerial library as SoftwareSerial.* Stepper - for controlling stepper motors* WiFi - for connecting to the internet using the Arduino WiFi shield* Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net of devices or sensors.

The Matrix and Sprite libraries are no longer part of the core distribution.

Leonardo Only Libraries

* Keyboard - Send keystrokes to an attached computer.* Mouse - Control cursor movement on a connected computer.

Contributed Libraries

If you're using one of these libraries, you need to install it first. To do so, download the library and unzip it. It should be in a folder of its own, and will typically contain at least two files, one with a .h suffix and one with a .cpp suffix. Open your Arduino sketchbook folder. If there is already a folder there called libraries, place the library folder in there. If not, create a folder called libraries in the sketchbook folder, and drop the library folder in there. Then re-start the Arduino programming environment, and you should see your new library in the Sketch > Import Library menu.

For details, see the page on the Arduino environment.

Communication (networking and protocols):

* Messenger - for processing text-based messages from the computer* NewSoftSerial - an improved version of the SoftwareSerial library* OneWire - control devices (from Dallas Semiconductor) that use the One Wire protocol.* PS2Keyboard - read characters from a PS2 keyboard.* Simple Message System - send messages between Arduino and the computer* SSerial2Mobile - send text messages or emails using a cell phone (via AT commands over software serial)* Webduino - extensible web server library (for use with the Arduino Ethernet Shield)* X10 - Sending X10 signals over AC power lines* XBee - for communicating with XBees in API mode

102

Page 104: Arduino Language Reference

* SerialControl - Remote control other Arduinos over a serial connectionSensing:

* Capacitive Sensing - turn two or more pins into capacitive sensors* Debounce - for reading noisy digital inputs (e.g. from buttons)

Displays and LEDs:

* Improved LCD library fixes LCD initialization bugs in official Arduino LCD library* GLCD - graphics routines for LCD based on the KS0108 or equivalent chipset.* LedControl - for controlling LED matrices or seven-segment displays with a MAX7221 or

MAX7219.* LedControl - an alternative to the Matrix library for driving multiple LEDs with Maxim chips.* LedDisplay - control of a HCMS-29xx scrolling LED display.

These libraries are compatible Wiring versions, and the links below point to the (excellent)Wiring documentation.

* Matrix - Basic LED Matrix display manipulation library* Sprite - Basic image sprite manipulation library for use in animations with an LED matrix

Audio and Waveforms:

* FFT - frequency analysis of audio or other analog signals* Tone - generate audio frequency square waves in the background on any microcontroller pin

Motors and PWM:

* TLC5940 - 16 channel 12 bit PWM controller.

Timing:

* DateTime - a library for keeping track of the current date and time in software.* Metro - help you time actions at regular intervals* MsTimer2 - uses the timer 2 interrupt to trigger an action every N milliseconds.

Utilities:

* PString - a lightweight class for printing to buffers* Streaming - a method to simplify print statements

For a guide to writing your own libraries, see this tutorial. Reference Home

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

103

Page 105: Arduino Language Reference

LCD Library

This library allows an Arduino board to control LiquidCrystal displays (LCDs) based on the Hitachi HD44780 (or a compatible) chipset, which is found on most text-based LCDs. The library works with in either 4- or 8-bit mode (i.e. using 4 or 8 data lines in addition to the rs, enable, and, optionally, the rw control lines).

lcd.autoscroll()

Turns on automatic scrolling of the LCD. This causes each character output to the display to push previous characters over by one space. If the current text direction is left-to-right (the default), the display scrolls to the left; if the current direction is right-to-left, the display scrolls to the right. This has the effect of outputting each new character to the same location on the LCD.

Syntax: lcd.autoscroll()Parameters: lcd: a variable of type LiquidCrystal

Example

LiquidCrystal Library – Autoscroll

104

Page 106: Arduino Language Reference

/*Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch demonstrates the use of the autoscroll() and noAutoscroll() functions to make new text scroll or not. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() { // set up the LCD's number of columns and rows: lcd.begin(16,2);}

void loop() { // set the cursor to (0,0): lcd.setCursor(0, 0); // print from 0 to 9: for (int thisChar = 0; thisChar < 10; thisChar++) { lcd.print(thisChar); delay(500); }

// set the cursor to (16,1): lcd.setCursor(16,1); // set the display to automatically scroll: lcd.autoscroll(); // print from 0 to 9: for (int thisChar = 0; thisChar < 10; thisChar++) { lcd.print(thisChar); delay(500); } // turn off automatic scrolling

105

Page 107: Arduino Language Reference

lcd.noAutoscroll(); // clear screen for the next loop: lcd.clear();}

LiquidCrystal

lcd.begin()

Specifies the dimensions (width and height) of the display.

Syntax: lcd.begin(cols, rows)Parameters: lcd: a variable of type LiquidCrystal

cols: the number of columns that the display hasrows: the number of rows that the display has

LiquidCrystal

lcd.blink()

Display the blinking LCD cursor. If used in combination with the cursor() function, the resultwill depend on the particular display.

Syntax: lcd.blink()Parameters: lcd: a variable of type LiquidCrystalExample * blink() and noBlink()

LiquidCrystal Library - Blink

/*Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface.This sketch prints "Hello World!" to the LCD and makes the cursor block blink. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

// include the library code:

106

Page 108: Arduino Language Reference

#include <LiquidCrystal.h>// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!");}

void loop() { // Turn off the blinking cursor: lcd.noBlink(); delay(3000); // Turn on the blinking cursor: lcd.blink(); delay(3000);}

LiquidCrystal

lcd.clear()

Clears the LCD screen and positions the cursor in the upper-left corner.

Syntax: lcd.clear()

Parameters: lcd: a variable of type LiquidCrystal

LiquidCrystal

LiquidCrystal()

Creates a variable of type LiquidCrystal. The display can be controlled using 4 or 8 data lines. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters.

Syntax: LiquidCrystal(rs, enable, d4, d5, d6, d7) LiquidCrystal(rs, rw, enable, d4, d5, d6, d7) LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7) LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

Parameters: rs: the number of the Arduino pin that is connected to the RS pin on the LCDrw: the number of the Arduino pin that is connected to the RW pin on the LCD (optional)

107

Page 109: Arduino Language Reference

enable: the number of the Arduino pin that is connected to the enable pin on the LCD d0, d1, d2, d3, d4, d5, d6, d7: the numbers of the Arduino pins that are connected to the corresponding data pins on the LCD. d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

Example

#include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup(){ lcd.print("hello, world!");}

void loop() {}

LiquidCrystal

lcd.createChar()

Create a custom character (gylph) for use on the LCD. Up to eight characters of 5x8 pixels are supported (numbered 0 to 7). The appearance of each custom character is specified by an array of eight bytes, one for each row. The five least significant bits of each byte determine the pixels in that row. To display a custom character on the screen, write() its number.

Syntax: lcd.createChar(num, data)

Parameters: lcd: a variable of type LiquidCrystalnum: which character to create (0 to 7)data: the character's pixel data

Example

#include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 5, 4, 3, 2);byte smiley[8] = { B00000, B10001, B00000, B00000, B10001, B01110, B00000,};void setup() { lcd.createChar(0, smiley); lcd.begin(16, 2); lcd.write(0);}void loop() {}

108

Page 110: Arduino Language Reference

LiquidCrystal

lcd.cursor()

Display the LCD cursor: an underscore (line) at the position to which the next character will be written.

Syntax: lcd.cursor()Parameters: lcd: a variable of type LiquidCrystal

Example * cursor() and * noCursor()

/* LiquidCrystal Library - Cursor Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and uses the cursor() and noCursor() methods to turn on and off the cursor. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

#include <LiquidCrystal.h>// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); lcd.print("hello, world!");}void loop() { lcd.noCursor(); delay(500); // Turn on the cursor: lcd.cursor(); delay(500);}

109

Page 111: Arduino Language Reference

LiquidCrystal

lcd.display()

/* LiquidCrystal Library - display() and noDisplay() Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and uses the display() and noDisplay() functions to turn on and off the display. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

// include the library code:#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!");}

void loop() { // Turn off the display: lcd.noDisplay(); delay(500); // Turn on the display: lcd.display(); delay(500);}

110

Page 112: Arduino Language Reference

LiquidCrystal

lcd.home()

Positions the cursor in the upper-left of the LCD. That is, use that location in outputting subsequent text to the display. To also clear the display, use the clear() function instead.

Syntax: lcd.home()Parameters: lcd: a variable of type LiquidCrystal

LiquidCrystal

lcd.leftToRight()

Set the direction for text written to the LCD to left-to-right, the default. This means that subsequent characters written to the display will go from left to right, but does not affect previously-output text.

Syntax: lcd.leftToRight()Parameters: lcd: a variable of type LiquidCrystal

LiquidCrystal

lcd.noAutoscroll()

Turns off automatic scrolling of the LCD.

Syntax: lcd.noAutoscroll()Parameters: lcd: a variable of type LiquidCrystal

LiquidCrystal

lcd.noBlink()

Turns off the blinking LCD cursor.

Syntax: lcd.noBlink()Parameters: lcd: a variable of type LiquidCrystal

Example * blink() and noBlink()

LiquidCrystal

lcd.noCursor()

Hides the LCD cursor.

Syntax: lcd.noCursor()

111

Page 113: Arduino Language Reference

Parameters lcd: a variable of type LiquidCrystal

Example * cursor() and noCursor()

LiquidCrystal

lcd.noDisplay()

Turns off the LCD display, without losing the text currently shown on it.

Syntax: lcd.noDisplay()

Parameters: lcd: a variable of type LiquidCrystal

Example * display() and noDisplay()

LiquidCrystal

lcd.print()

Prints text to the LCD.

Syntax: lcd.print(data) lcd.print(data, BASE)

Parameters: lcd: a variable of type LiquidCrystaldata: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byteprint() will return the number of bytes written, though reading that number is optional

Example

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() { lcd.print("hello, world!"); }

void loop() {}

112

Page 114: Arduino Language Reference

LiquidCrystal

lcd.rightToLeft()

Set the direction for text written to the LCD to right-to-left (the default is left-to-right). This means that subsequent characters written to the display will go from right to left, but does not affect previously-output text.

Syntax: lcd.rightToLeft()Parameters: lcd: a variable of type LiquidCrystal

LiquidCrystal

lcd.scrollDisplayLeft()

Scrolls the contents of the display (text and cursor) one space to the left.

Syntax: lcd.scrollDisplayLeft()Parameters: lcd: a variable of type LiquidCrystalExample

/* LiquidCrystal Library - scrollDisplayLeft() and scrollDisplayRight() Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and uses the scrollDisplayLeft() and scrollDisplayRight() methods to scroll the text. The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

// include the library code:#include <LiquidCrystal.h>// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2);

113

Page 115: Arduino Language Reference

// Print a message to the LCD. lcd.print("hello, world!"); delay(1000);}

void loop() { // scroll 13 positions (string length) to the left // to move it offscreen left: for (int positionCounter = 0; positionCounter < 13; positionCounter++) { // scroll one position left: lcd.scrollDisplayLeft(); // wait a bit: delay(150); } // scroll 29 positions (string length + display length) to the right // to move it offscreen right: for (int positionCounter = 0; positionCounter < 29; positionCounter++) { // scroll one position right: lcd.scrollDisplayRight(); // wait a bit: delay(150); } // scroll 16 positions (display length + string length) to the left // to move it back to center: for (int positionCounter = 0; positionCounter < 16; positionCounter++) { // scroll one position left: lcd.scrollDisplayLeft(); // wait a bit: delay(150); } // delay at the end of the full loop: delay(1000);}

LiquidCrystal

lcd.scrollDisplayRight()

Scrolls the contents of the display (text and cursor) one space to the right.

Syntax: lcd.scrollDisplayRight()Parameters: lcd: a variable of type LiquidCrystal

Example scrollDisplayLeft() and scrollDisplayRight()

114

Page 116: Arduino Language Reference

LiquidCrystal

lcd.setCursor()

Position the LCD cursor; that is, set the location at which subsequent text written to the LCD will be displayed.

Syntax: lcd.setCursor(col, row)Parameters: lcd: a variable of type LiquidCrystal

col: the column at which to position the cursor (with 0 being the first column)row: the row at which to position the cursor (with 0 being the first row)

Example

/* LiquidCrystal Library - setCursor Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints to all the positions of the LCD using the setCursor(0 method: The circuit: * LCD RS pin to digital pin 12 * LCD Enable pin to digital pin 11 * LCD D4 pin to digital pin 5 * LCD D5 pin to digital pin 4 * LCD D6 pin to digital pin 3 * LCD D7 pin to digital pin 2 * LCD R/W pin to ground * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) */

// include the library code:#include <LiquidCrystal.h>

// these constants won't change. But you can change the size of// your LCD using them:const int numRows = 2;const int numCols = 16;

// initialize the library with the numbers of the interface pinsLiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() { // set up the LCD's number of columns and rows: lcd.begin(numCols,numRows);}

void loop() {

115

Page 117: Arduino Language Reference

// loop from ASCII 'a' to ASCII 'z': for (int thisLetter = 'a'; thisLetter <= 'z'; thisLetter++) { // loop over the columns: for (int thisCol = 0; thisCol < numRows; thisCol++) { // loop over the rows: for (int thisRow = 0; thisRow < numCols; thisRow++) { // set the cursor position: lcd.setCursor(thisRow,thisCol); // print the letter: lcd.write(thisLetter); delay(200); } } }}

LiquidCrystal

lcd.write()

Write a character to the LCD.

Syntax: lcd.write(data)

Parameters: lcd: a variable of type LiquidCrystaldata: the character to write to the display

Returns: bytewrite() will return the number of bytes written, though reading that number is optional

Example

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() { Serial.begin(9600); } void loop() { if (Serial.available()) { lcd.write(Serial.read()); } }

116

Page 118: Arduino Language Reference

long()

Converts a value to the long data type.

Syntax: long(x)

Parameters: x: a value of any type

Returns: long

long

Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.

Syntax: long var = val;o var - the long variable name

o val - the value assigned to the variable

loop()

After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.

Example

int buttonPin = 3;

// setup initializes serial and the button pinvoid setup(){ beginSerial(9600); pinMode(buttonPin, INPUT);}

// loop checks the button pin each time,// and will send serial if it is pressedvoid loop(){ if (digitalRead(buttonPin) == HIGH) serialWrite('H'); else serialWrite('L');

delay(1000);}

117

Page 119: Arduino Language Reference

lowByte()

Extracts the low-order (rightmost) byte of a variable (e.g. a word).

Syntax: lowByte(x)

Parameters: x: a value of any type

Returns: byte

map(value, fromLow, fromHigh, toLow, toHigh)

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers, for exampley = map(x, 1, 50, 50, 1);

The function also handles negative numbers well, so that this example

y = map(x, 1, 50, 50, -100);

is also valid and works well.

The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.

Parameters: value: the number to mapfromLow: the lower bound of the value's current rangefromHigh: the upper bound of the value's current rangetoLow: the lower bound of the value's target rangetoHigh: the upper bound of the value's target range

Returns: The mapped value.

Example

/* Map an analog value to 8 bits (0 to 255) */void setup() {}

void loop(){ int val = analogRead(0); val = map(val, 0, 1023, 0, 255); analogWrite(9, val);}

118

Page 120: Arduino Language Reference

Appendix

For the mathematically inclined, here's the whole function

long map(long x, long in_min, long in_max, long out_min, long out_max){ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;}

max(x, y)

Calculates the maximum of two numbers.

Parameters: x: the first number, any data typey: the second number, any data type

Returns: The larger of the two parameter values.

Example sensVal = max(senVal, 20); // assigns sensVal to the larger of sensVal or 20 // (effectively ensuring that it is at least 20)Note: Perhaps counter-intuitively, max() is often used to constrain the lower end of a

variable's range, while min() is used to constrain the upper end of the range.

Warning!! Because of the way the max() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results

max(a--, 0); // avoid this - yields incorrect resultsa--; // use this instead -max(a, 0); // keep other math outside the function

micros()

Returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.

Parameters: None

Returns: Number of microseconds since the program started (unsigned long)

Example

unsigned long time;

void setup(){ Serial.begin(9600);}void loop(){ Serial.print("Time: ");

119

Page 121: Arduino Language Reference

time = micros(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000);}

millis()

Returns the number of milliseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days.

Parameters: None

Returns: Number of milliseconds since the program started (unsigned long)

Example

unsigned long time;

void setup(){ Serial.begin(9600);}void loop(){ Serial.print("Time: "); time = millis(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000);}

Tip: Note that the parameter for millis is an unsigned long, errors may be generated if a programmer tries to do math with other datatypes such as ints.

min(x, y)

Calculates the minimum of two numbers.

Parameters: x: the first number, any data typey: the second number, any data type

Returns: The smaller of the two numbers.

Examples

sensVal = min(sensVal, 100); // assigns sensVal to the smaller of sensVal or 100 // ensuring that it never gets above 100.

Note: Perhaps counter-intuitively, max() is often used to constrain the lower end of a variable's range, while min() is used to constrain the upper end of the range.

120

Page 122: Arduino Language Reference

Warning!! Because of the way the min() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results

min(a++, 100); // avoid this - yields incorrect results a++; min(a, 100); // use this instead - keep other math outside the function

% (modulo)

Calculates the remainder when one integer is divided by another. It is useful for keeping a variable within a particular range (e.g. the size of an array).

Syntax: result = dividend % divisor

Parameters: dividend: the number to be divideddivisor: the number to divide by

Returns: the remainder

Examples

x = 7 % 5; // x now contains 2x = 9 % 5; // x now contains 4x = 5 % 5; // x now contains 0x = 4 % 5; // x now contains 4

Example Code

/* update one value in an array each time through a loop */

int values[10];int i = 0;

void setup() {}

void loop(){ values[i] = analogRead(0); i = (i + 1) % 10; // modulo operator rolls over variable }

Warning!! The modulo operator does not work on floats.

121

Page 123: Arduino Language Reference

MouseKeyboard

Mouse.begin()

Begins emulating the mouse connected to a computer. begin() must be called before controlling the computer. To end control, use Mouse.end().

Syntax: Mouse.begin()Parameters: noneReturns: nothing

Example

void setup(){ pinMode(2, INPUT); } void loop(){ //initiate the Mouse library when button is pressed if(digitalRead(2) == HIGH){ Mouse.begin(); } }

MouseKeyboard

Mouse.click()

Sends a momentary click to the computer at the location of the cursor. This is the same as pressing and immediately releasing the mouse button.

Mouse.click() defaults to the left mouse button.

WARNING: When you use the Mouse.click() command, the Arduino takes over your mouse! Make sure you have control before you use the command. A pushbutton to toggle the mouse control state is effective.

Syntax: Mouse.click(); Mouse.click(button);

Parameters: button: which mouse button to press - charo MOUSE_LEFT (default)

o MOUSE_RIGHT o MOUSE_MIDDLE

Returns: nothing

Example

void setup(){ pinMode(2,INPUT); //initiate the Mouse library

122

Page 124: Arduino Language Reference

Mouse.begin();}void loop(){ //if the button is pressed, send a Right mouse click if(digitalRead(2) == HIGH){ Mouse.click(); }}

MouseKeyboard

Mouse.end()

Stops emulating the mouse connected to a computer. To start control, use Mouse.begin().

Syntax: Mouse.end()Parameters: noneReturns: nothing

Example

void setup(){ pinMode(2,INPUT); //initiate the Mouse library Mouse.begin();}

void loop(){ //if the button is pressed, send a Right mouse click //then end the Mouse emulation if(digitalRead(2) == HIGH){ Mouse.click(); Mouse.end(); }}

Mouse

Mouse.isPressed()

Checks the current status of all mouse buttons, and reports if any are pressed or not.

Syntax: Mouse.isPressed();Mouse.isPressed(button);

Parameters: When there is no value passed, it checks the status of the left mouse button.button: which mouse button to check - charMOUSE_LEFT (default)MOUSE_RIGHTMOUSE_MIDDLE

123

Page 125: Arduino Language Reference

Returns: boolean : reports wether a button is pressed or not

Example

void setup(){ //The switch that will initiate the Mouse press pinMode(2,INPUT); //The switch that will terminate the Mouse press pinMode(3,INPUT); //Start serial communication with the computer Serial1.begin(9600); //initiate the Mouse library Mouse.begin();}

void loop(){ //a variable for checking the button's state int mouseState=0; //if the switch attached to pin 2 is closed, press and hold the right mouse button and save the state ina variable if(digitalRead(2) == HIGH){ Mouse.press(); mouseState=Mouse.isPressed(); } //if the switch attached to pin 3 is closed, release the right mouse button and save the state in a variable if(digitalRead(3) == HIGH){ Mouse.release(); mouseState=Mouse.isPressed(); } //print out the current mouse button state Serial1.println(mouseState); delay(10);}

MouseKeyboard

Mouse.move()

Moves the cursor on a connected computer. The motion onscreen is always relative to the cursor's current location. Before using Mouse.move() you must call Mouse.begin()

WARNING!!! When you use the Mouse.move() command, the Arduino takes over your mouse! Make sure you have control before you use the command. A pushbutton to toggle the mouse control state is effective.

Syntax: Mouse.move(xVal, yPos, wheel);

Parameters: xVal: amount to move along the x-axis - intyVal: amount to move along the y-axis - intwheel: amount to move scroll wheel - int

124

Page 126: Arduino Language Reference

Returns: nothing

Example

const int xAxis = A1; //analog sensor for X axis const int yAxis = A2; // analog sensor for Y axis

int range = 12; // output range of X or Y movementint responseDelay = 2; // response delay of the mouse, in msint threshold = range/4; // resting thresholdint center = range/2; // resting position valueint minima[] = {1023, 1023}; // actual analogRead minima for {x, y}int maxima[] = {0,0}; // actual analogRead maxima for {x, y}int axis[] = {xAxis, yAxis}; // pin numbers for {x, y}int mouseReading[2]; // final mouse readings for {x, y}

void setup() { Mouse.begin();}

void loop() { // read and scale the two axes: int xReading = readAxis(0); int yReading = readAxis(1);

// move the mouse: Mouse.move(xReading, yReading, 0); delay(responseDelay);}

/* reads an axis (0 or 1 for x or y) and scales the analog input range to a range from 0 to <range> */

int readAxis(int axisNumber) { int distance = 0; // distance from center of the output range

// read the analog input: int reading = analogRead(axis[axisNumber]);

// of the current reading exceeds the max or min for this axis, // reset the max or min: if (reading < minima[axisNumber]) { minima[axisNumber] = reading; } if (reading > maxima[axisNumber]) { maxima[axisNumber] = reading; }

// map the reading from the analog input range to the output range: reading = map(reading, minima[axisNumber], maxima[axisNumber], 0, range);

125

Page 127: Arduino Language Reference

// if the output reading is outside from the // rest position threshold, use it: if (abs(reading - center) > threshold) { distance = (reading - center); } // the Y axis needs to be inverted in order to // map the movemment correctly: if (axisNumber == 1) { distance = -distance; } // return the distance for this axis: return distance; }

MouseKeyboard

Mouse.press()

Sends a button press to a connected computer. A press is the equivalent of clicking and continuously holding the mouse button. A press is cancelled with Mouse.release().

Before using Mouse.press(), you need to start communication with Mouse.begin().

Mouse.press() defaults to a left button press.

WARNING! When you use the Mouse.press() command, the Arduino takes over your mouse! Make sure you have control before you use the command. A pushbutton to toggle the mouse control state is effective.

Syntax: Mouse.press(); Mouse.press(button)

Parameters: button: which mouse button to press - charMOUSE_LEFT (default)MOUSE_RIGHTMOUSE_MIDDLE

Returns: nothing

Example

void setup(){ //The switch that will initiate the Mouse press pinMode(2,INPUT); //The switch that will terminate the Mouse press pinMode(3,INPUT); //initiate the Mouse library Mouse.begin(); } void loop(){ //if the switch attached to pin 2 is closed, press and hold the right mouse button

126

Page 128: Arduino Language Reference

if(digitalRead(2) == HIGH){ Mouse.press(); } //if the switch attached to pin 3 is closed, release the right mouse button if(digitalRead(3) == HIGH){ Mouse.release(); } }

MouseKeyboard

Mouse.release()

Sends a message that a previously pressed button (invoked through Mouse.press()) is released. Mouse.release() defaults to the left button.

WARNING! When you use the Mouse.release() command, the Arduino takes over your mouse! Make sure you have control before you use the command. A pushbutton to toggle the mouse control state is effective.

Syntax: Mouse.release();Mouse.release(button);

Parameters: button: which mouse button to press - charMOUSE_LEFT (default)MOUSE_RIGHTMOUSE_MIDDLE

Returns: nothing

Example

void setup(){ //The switch that will initiate the Mouse press pinMode(2,INPUT); //The switch that will terminate the Mouse press pinMode(3,INPUT); //initiate the Mouse library Mouse.begin(); } void loop(){ //if the switch attached to pin 2 is closed, press and hold the right mouse button if(digitalRead(2) == HIGH){ Mouse.press(); } //if the switch attached to pin 3 is closed, release the right mouse button if(digitalRead(3) == HIGH){ Mouse.release(); } }

127

Page 129: Arduino Language Reference

NewPing library

Features

• Works with many different ultrasonic sensor models: SR04, SRF05, SRF06, DYP-ME007 & Parallax PING)))™.

• Interface with all but the SRF06 sensor using only one Arduino pin. • Doesn't lag for a full second if no ping/echo is received. • Ping sensors consistently and reliably at up to 30 times per second. • Timer interrupt method for event-driven sketches. • Built-in digital filter method ping_median() for easy error correction. • Uses port registers when accessing pins for faster execution and smaller code size. • Allows setting of a maximum distance where pings beyond that distance are read as no ping

"clear". • Ease of using multiple sensors (example sketch with 15 sensors). • More accurate distance calculation (cm, inches & uS). • Doesn't use pulseIn, which is slow and gives incorrect results with some ultrasonic sensor

models. • Actively developed with features being added and bugs/issues addressed.

Constructor

NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

Example:

NewPing sonar(12, 11, 200);

This initializes NewPing to use pin 12 for trigger output, pin 11 for echo input, with a maximum ping distance of 200cm. max_cm_distance is optional [default = 500cm].

Methods

sonar.ping(); Send a ping, returns the echo time in microseconds or 0 (zero) if no ping echo within set distance limit

sonar.ping_in(); Send a ping, returns the distance in inches or 0 (zero) if no ping echo within set distance limit

sonar.ping_cm(); Send a ping, returns the distance in centimeters or 0 (zero) if no ping echo within set distance limit

sonar.ping_median(iterations); Do multiple pings (default=5), discard out of range pings and return median in microseconds

sonar.convert_in(echoTime); Converts microseconds to distance in inches sonar.convert_cm(echoTime); Converts microseconds to distance in centimeters sonar.ping_timer(function); Send a ping and call function to test if ping is complete. sonar.check_timer(); Check if ping has returned within the set distance limit. timer_us(frequency, function); Call function every frequency microseconds. timer_ms(frequency, function); Call function every frequency milliseconds. timer_stop(); - Stop the timer.

128

Page 130: Arduino Language Reference

Example:

#include <NewPing.h>

#define TRIGGER_PIN 12#define ECHO_PIN 11#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {Serial.begin(115200);

}

void loop() {int uS = sonar.ping();Serial.print("Ping: ");Serial.print(uS / US_ROUNDTRIP_CM);Serial.println("cm");delay(50);

}

// ----------------------------------------------------------------------------------------------------------------------// This example code was used to successfully communicate with 15 ultrasonic sensors. You can// adjust the number of sensors in your project by changing SONAR_NUM and the number of// NewPing objects in the "sonar" array. You also need to change the pins for each sensor for the// NewPing objects. Each sensor is pinged at 33ms intervals. So, one cycle of all sensors takes// 495ms (33 * 15 = 495ms). The results are sent to the "oneSensorCycle" function which currently// just displays the distance data. Your projekt would normally process the sensor results in this// function (for example, decide if a robot needs to turn and call the turn function). Keep in mind// this example is event-driven. Your complete sketch needs to be written so there's no "delay"// commands and the loop() cycles at faster than a 33ms rate. If other processes take longer than// 33ms, you'll need to increase PING_INTERVAL so it doesn't get behind.// ----------------------------------------------------------------------------------------------------------------------

#include <NewPing.h>

#define SONAR_NUM 15 // Number or sensors.#define MAX_DISTANCE 200 // Max distance in cm.#define PING_INTERVAL 33 // Milliseconds between pings.

unsigned long pingTimer[SONAR_NUM]; // When each pings.unsigned int cm[SONAR_NUM]; // Store ping distances.uint8_t currentSensor = 0; // Which sensor is active.

NewPing sonar[SONAR_NUM] = { // Sensor object array. NewPing(41, 42, MAX_DISTANCE), NewPing(43, 44, MAX_DISTANCE), NewPing(45, 20, MAX_DISTANCE), NewPing(21, 22, MAX_DISTANCE), NewPing(23, 24, MAX_DISTANCE), NewPing(25, 26, MAX_DISTANCE),

129

Page 131: Arduino Language Reference

NewPing(27, 28, MAX_DISTANCE), NewPing(29, 30, MAX_DISTANCE), NewPing(31, 32, MAX_DISTANCE), NewPing(34, 33, MAX_DISTANCE), NewPing(35, 36, MAX_DISTANCE), NewPing(37, 38, MAX_DISTANCE), NewPing(39, 40, MAX_DISTANCE), NewPing(50, 51, MAX_DISTANCE), NewPing(52, 53, MAX_DISTANCE)};

void setup() { Serial.begin(115200); pingTimer[0] = millis() + 75; // First ping start in ms. for (uint8_t i = 1; i < SONAR_NUM; i++) pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;}

void loop() { for (uint8_t i = 0; i < SONAR_NUM; i++) { if (millis() >= pingTimer[i]) { pingTimer[i] += PING_INTERVAL * SONAR_NUM; if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Do something with results. sonar[currentSensor].timer_stop(); currentSensor = i; cm[currentSensor] = 0; sonar[currentSensor].ping_timer(echoCheck); } } // The rest of your code would go here.}

void echoCheck() { // If ping echo, set distance to array. if (sonar[currentSensor].check_timer()) cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;}

void oneSensorCycle() { // Do something with the results. for (uint8_t i = 0; i < SONAR_NUM; i++) { Serial.print(i); Serial.print("="); Serial.print(cm[i]); Serial.print("cm "); } Serial.println();}

130

Page 132: Arduino Language Reference

noInterrupts()

Disables interrupts (you can re-enable them with interrupts()). Interrupts allow certain important tasks to happen in the background and are enabled by default. Some functions will not work while interrupts are disabled, and incoming communication may be ignored. Interrupts can slightly disrupt the timing of code, however, and may be disabled for particularly critical sections of code.

Parameters: NoneReturns: None

Example

void setup() {}

void loop(){ noInterrupts(); // critical, time-sensitive code here interrupts(); // other code here}

noTone()

Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated.

NOTE: if you want to play different pitches on multiple pins, you need to call noTone() on one pin before calling tone() on the next pin.

Syntax: noTone(pin)

Parameters: pin: the pin on which to stop generating the tone

Returns: nothing

131

Page 133: Arduino Language Reference

One-Wire Protocol

(This page still needs some more generalisation to 1-Wire, as some code is specific to "using the DS1820" and a specifc LCD. It also needs a cleaning of the library paragraph that includes references to older versions of libraries.)

Dallas Semiconductor (now Maxim) produces a family of devices that are controlled through a proprietary 1-wire protocol. There are no fees for programmers using the Dallas 1-Wire (trademark) drivers.

On a 1-Wire network, which Dallas has dubbed a "MicroLan" (trademark), a single "master" device communicates with one or more 1-Wire "slave" devices over a single data line, which can also be used to provide power to the slave devices. (Devices drawing power from the 1-wire bus are said to be operating in parasitic power mode.) http://sheepdogguides.com/arduino/asw1onew1.htm Tom Boyd's guide to 1-Wire may tell you more than you want to know... but it may also answer questions and inspire interest.

The 1-wire temperature sensors have become particularly popular, because they're inexpensive and easy to use, providing calibrated digital temperature readings directly. They are more tolerant of long wires between sensor and Arduino. The sample code below demonstrates how to interface with a 1-wire device using Jim Studt's OneWire Arduino library, with the DS18S20 digital thermometer as an example. Many 1-Wire chips can operate in both parasitic and normal power modes.

MicroLans can be accessed directly by an Arduino, using the mature Arduino OneWire library. Alternatively, they can be accessed through an interface which costs a little money, but reduces the workload inside the Arduino. The interface cost $8 in kit form at 2/2010. There is a guide to using it from an independent source.

Powering OneWire devices

The chip can be powered two ways. One (the "parasitic" option) means that only two wires need go to the chip. The other may, in some cases, give more reliable operation (parasitic often works well), as an extra wire carrying the power for the chip is involved. For getting started, especially if your chip is within 20 feet of your Arduino, the parasitic option is probably fine. The code below works for either option, anyway.

Parasite power mode

When operating in parasite power mode, only two wires are required: one data wire, and ground. At the master, a 4.7k pull-up resistor must be connected to the 1-wire bus. When the line is in a "high" state, the device pulls current to charge an internal capacitor.

This current is usually very small, but may go as high as 1.5 mA when doing a temperature conversion or writing EEPROM. When a slave device is performing one these operations, the bus master must keep the bus pulled high to provide power until the operation completes; a delay of 750ms is required for a DS18S20 temperature conversion. The master can't do anything during this time, like issuing commands to other devices, or polling for the slave's operation to be completed. To support this, the OneWire library makes it possible to have the bus held high after the data is written.

Normal (external supply) mode

132

Page 134: Arduino Language Reference

With an external supply, three wires are required: the bus wire, ground, and power. The 4.7k pull-up resistor is still required on the bus wire. As the bus is free for data transfer, the microcontroller can continually poll the state of a device doing a conversion. This way, a conversion request can finish as soon as the device reports being done, as opposed to having to wait 750ms in "parasite" power mode.

Note on resistors:

For larger networks, you can try smaller resistors.The ATmega328/168 datasheet indicates starting at 1k6 and a number of users have found smaller to work better on larger networks.

Addressing a OneWire device

Each 1-Wire device contains a unique 64-bit 'rom' code, consisting of an 8-bit family code, a 48-bit serial number, and an 8-bit CRC. The CRC is used to verify the integrity of the data. For example, the sample code, below, checks if the device being addressed is a DS18S20 temperature sensor by checking for its family code, 0x10. To use the sample code with the newer DS18B20 sensor, you'd check for a family code of 0x28, instead, and for the DS1822 you'd check for 0x22.

Before sending a command to a slave device, the master must first select that device using its rom code. Alternatively, you can address a command to all slave devices by issuing a 'skip rom' command (0x, instead. This is only safe if you are sure there is only one slave device on the MicroLAN. for commands that don't elicit a response from the slave devices - data collision will occur if data is requested from more than one slave.

Example code

#include <OneWire.h>

// DS18S20 Temperature chip i/o OneWire ds(10); // on pin 10

void setup(void) { // initialize inputs/outputs // start serial port Serial.begin(9600);}

void loop(void) { byte i; byte present = 0; byte data[12]; byte addr[8];

if ( !ds.search(addr)) { Serial.print("No more addresses.\n"); ds.reset_search(); return; }

Serial.print("R=");

133

Page 135: Arduino Language Reference

for( i = 0; i < 8; i++) { Serial.print(addr[i], HEX); Serial.print(" "); }

if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.print("CRC is not valid!\n"); return; }

if ( addr[0] == 0x10) { Serial.print("Device is a DS18S20 family device.\n"); } else if ( addr[0] == 0x28) { Serial.print("Device is a DS18B20 family device.\n"); } else { Serial.print("Device family is not recognized: 0x"); Serial.println(addr[0],HEX); return; }

ds.reset(); ds.select(addr); ds.write(0x44,1); // start conversion, with parasite power on at the end

delay(1000); // maybe 750ms is enough, maybe not // we might do a ds.depower() here, but the reset will take care of it.

present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad

Serial.print("P="); Serial.print(present,HEX); Serial.print(" "); for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); Serial.print(data[i], HEX); Serial.print(" "); } Serial.print(" CRC="); Serial.print( OneWire::crc8( data, 8), HEX); Serial.println();}

Converting HEX to something meaningful (Temperature)

In order to convert the HEX code to a temperature value, first you need to identify if you are using a DS18S20, or DS18B20 series sensor. The code to read the temperature needs to be slightly different for the DS18B20 (and DS1822), because it returns a 12-bit temperature value (0.0625 deg precision), while the DS18S20 and DS1820 return 9-bit values (0.5 deg precision).

134

Page 136: Arduino Language Reference

First off, you need to define some variables, (put right under loop() above)

int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract;

Then for a DS18B20 series you will add the following code below the Serial.println(); above

LowByte = data[0]; HighByte = data[1]; TReading = (HighByte << 8) + LowByte; SignBit = TReading & 0x8000; // test most sig bit if (SignBit) // negative { TReading = (TReading ^ 0xffff) + 1; // 2's comp } Tc_100 = (6 * TReading) + TReading / 4; // multiply by (100 * 0.0625) or 6.25

Whole = Tc_100 / 100; // separate off the whole and fractional portions Fract = Tc_100 % 100;

if (SignBit) // If its negative { Serial.print("-"); } Serial.print(Whole); Serial.print("."); if (Fract < 10) { Serial.print("0"); } Serial.print(Fract);

Serial.print("\n");

This block of code converts the temperature to deg C and prints it to the Serial output.

A Code Snippet for the DS 1820 with 0.5 Degree Resolution

Above example works only for the B-type of the DS1820. Here is a code example that works with the lower resolution DS1820 and with multiple sensors diplaying their values on a LCD. Example is working with Arduino pin 9. Feel free to change that to an appropriate pin for your use. Pin 1 and 3 of the DS1820 has to be put to ground! In the example a 5k resistor is put from pin 2 of DS1820 to Vcc (+5V). See LiquidCrystal documentation for connecting the LCD to the Arduino.

#include <OneWire.h>#include <LiquidCrystal.h>// LCD=======================================================//initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2);#define LCD_WIDTH 20#define LCD_HEIGHT 2

135

Page 137: Arduino Language Reference

/* DS18S20 Temperature chip i/o */

OneWire ds(9); // on pin 9#define MAX_DS1820_SENSORS 2 byte addr[MAX_DS1820_SENSORS][8];void setup(void) { lcd.begin(LCD_WIDTH, LCD_HEIGHT,1); lcd.setCursor(0,0); lcd.print("DS1820 Test"); if (!ds.search(addr[0])) { lcd.setCursor(0,0); lcd.print("No more addresses."); ds.reset_search(); delay(250); return; } if ( !ds.search(addr[1])) { lcd.setCursor(0,0); lcd.print("No more addresses."); ds.reset_search(); delay(250); return; }}int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract;char buf[20];

void loop(void) { byte i, sensor; byte present = 0; byte data[12];

for (sensor=0;sensor<MAX_DS1820_SENSORS;sensor++) { if ( OneWire::crc8( addr[sensor], 7) != addr[sensor][7]) { lcd.setCursor(0,0); lcd.print("CRC is not valid"); return; }

if ( addr[sensor][0] != 0x10) { lcd.setCursor(0,0); lcd.print("Device is not a DS18S20 family device."); return; }

136

Page 138: Arduino Language Reference

ds.reset(); ds.select(addr[sensor]); ds.write(0x44,1); // start conversion, with parasite power on at the end

delay(1000); // maybe 750ms is enough, maybe not // we might do a ds.depower() here, but the reset will take care of it.

present = ds.reset(); ds.select(addr[sensor]); ds.write(0xBE); // Read Scratchpad

for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); }

LowByte = data[0]; HighByte = data[1]; TReading = (HighByte << 8) + LowByte; SignBit = TReading & 0x8000; // test most sig bit if (SignBit) // negative { TReading = (TReading ^ 0xffff) + 1; // 2's comp } Tc_100 = (TReading*100/2);

Whole = Tc_100 / 100; // separate off the whole and fractional portions Fract = Tc_100 % 100;

sprintf(buf, "%d:%c%d.%d\337C ",sensor,SignBit ? '-' : '+', Whole, Fract < 10 ? 0 : Fract);

lcd.setCursor(0,sensor%LCD_HEIGHT); lcd.print(buf); }}

137

Page 139: Arduino Language Reference

Ping

Ping Ultrasonic Range Finder

The Ping))) is an ultrasonic range finder from Parallax. It detects the distance of the closest object in front of the sensor (from 2 cm up to 3m). It works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. The Arduino board sends a short pulse to trigger the detection, then listens for a pulse on the same pin using the pulseIn() function. The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.

Example

/* Ping))) SensorThis sketch reads a PING))) ultrasonic rangefinder and returns the distance to the closest object in range. To do this, it sends a pulse to the sensor to initiate a reading, then listens for a pulse to return. The length of the returning pulse is proportional to the distance of the object from the sensor.*/

// this constant won't change. It's the pin number of the sensor's output:const int pingPin = 7;

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

138

Page 140: Arduino Language Reference

void loop(){ // establish variables for duration of the ping, and the distance result in inches and centimeters: long duration, inches, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW);

// The same pin is used to read the signal from the PING))): a HIGH pulse whose duration is the // time (in microseconds) from the sending of the ping to the reception of its echo off of an object. pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH);

// convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100);}

long microsecondsToInches(long microseconds){ // According to Parallax's datasheet for the PING))), there are 73.746 microseconds per inch (i.e. // sound travels at 1130 feet per second). This gives the distance travelled by the ping, outbound // and return, so we divide by 2 to get the distance of the obstacle return microseconds / 74 / 2;}

long microsecondsToCentimeters(long microseconds){ // The speed of sound is 340 m/s or 29 microseconds per centimeter. The ping travels out and back, // so to find the distance of the object we take half of the distance travelled. return microseconds / 29 / 2;}

139

Page 141: Arduino Language Reference

pinMode()

Configures the specified pin to behave either as an input or an output. See the description of digital pins for details on the functionality of the pins.

As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.

Syntax: pinMode(pin, mode)

Parameters: pin: the number of the pin whose mode you wish to setmode: INPUT, OUTPUT, or INPUT_PULLUP. (see the digital pins page for a more complete description of the functionality.)

Returns: None

Example

int ledPin = 13; // LED connected to digital pin 13

void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output }

void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second }

Note: The analog input pins can be used as digital pins, referred to as A0, A1, etc.

Pointer operators

pow(base, exponent)

Calculates the value of a number raised to a power. Pow() can be used to raise a number to a fractional power. This is useful for generating exponential mapping of values or curves.

Parameters: base: the number (float)exponent: the power to which the base is raised (float)

Returns: The result of the exponentiation (double)

Example

/* fscale

140

Page 142: Arduino Language Reference

Floating Point Autoscale Function V0.1This function will scale one set of floating point numbers (range) to another set of floating point numbers (range)It has a "curve" parameter so that it can be made to favor either the end of the output. (Logarithmic mapping)

It takes 6 parameters

originalMin - the minimum value of the original range - this MUST be less than origninalMaxoriginalMax - the maximum value of the original range - this MUST be greater than orginalMinnewBegin - the end of the new range which maps to orginalMin - it can be smaller, or larger, than newEnd, to facilitate inverting the rangesnewEnd - the end of the new range which maps to originalMax - it can be larger, or smaller, than newBegin, to facilitate inverting the ranges

inputValue - the variable for input that will mapped to the given ranges, this variable is constrained to originaMin <= inputValue <= originalMax

curve - curve is the curve which can be made to favor either end of the output scale in the mapping. Parameters are from -10 to 10 with 0 being a linear mapping (which basically takes curve out of the equation)

To understand the curve parameter do something like this:

void loop(){ for ( j=0; j < 200; j++){ scaledResult = fscale( 0, 200, 0, 200, j, -1.5);

Serial.print(j, DEC); Serial.print(" "); Serial.println(scaledResult, DEC); } }

And try some different values for the curve function - remember 0 is a neutral, linear mapping

To understand the inverting ranges, do something like this:

void loop(){ for ( j=0; j < 200; j++){ scaledResult = fscale( 0, 200, 200, 0, j, 0);

// Serial.print lines as above } }

*/#include <math.h>

int j;float scaledResult;

void setup() {

141

Page 143: Arduino Language Reference

Serial.begin(9600);}

void loop(){ for ( j=0; j < 200; j++){ scaledResult = fscale( 0, 200, 0, 200, j, -1.5);

Serial.print(j, DEC); Serial.print(" "); Serial.println(scaledResult , DEC); } }

float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve){

float OriginalRange = 0; float NewRange = 0; float zeroRefCurVal = 0; float normalizedCurVal = 0; float rangedValue = 0; boolean invFlag = 0;

// condition curve parameter // limit range

if (curve > 10) curve = 10; if (curve < -10) curve = -10;

curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

/* Serial.println(curve * 100, DEC); // multply by 100 to preserve resolution Serial.println(); */

// Check for out of range inputValues if (inputValue < originalMin) { inputValue = originalMin; } if (inputValue > originalMax) { inputValue = originalMax; }

// Zero Refference the values OriginalRange = originalMax - originalMin;

if (newEnd > newBegin){ NewRange = newEnd - newBegin; }

142

Page 144: Arduino Language Reference

else { NewRange = newBegin - newEnd; invFlag = 1; }

zeroRefCurVal = inputValue - originalMin; normalizedCurVal = zeroRefCurVal / OriginalRange; // normalize to 0 - 1 float

/* Serial.print(OriginalRange, DEC); Serial.print(" "); Serial.print(NewRange, DEC); Serial.print(" "); Serial.println(zeroRefCurVal, DEC); Serial.println(); */

// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine

if (originalMin > originalMax ) { return 0; }

if (invFlag == 0){ rangedValue = (pow(normalizedCurVal, curve) * NewRange) + newBegin;

} else // invert the ranges { rangedValue = newBegin - (pow(normalizedCurVal, curve) * NewRange); }

return rangedValue;}

PROGMEM

Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.

The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

PROGMEM is part of the pgmspace.h library. So you first need to include the library at the top your sketch, like this:

#include <avr/pgmspace.h>

143

Page 145: Arduino Language Reference

Syntax: dataType variableName[] PROGMEM = {dataInt0, dataInt1, dataInt3...}; program memory dataType - any program memory variable type (see below)

variableName - the name for your array of data

Note that because PROGMEM is a variable modifier, there is no hard and fast rule about where it should go, so the Arduino compiler accepts all of the definitions below, which are also synonymous. However experiments have indicated that, in various versions of Arduino (having to do with GCC version), PROGMEM may work in one location and not in another. The "string table" example below has been tested to work with Arduino 13. Earlier versions of the IDE may work better if PROGMEM is included after the variable name.

dataType variableName[] PROGMEM = {}; // use this formdataType PROGMEM variableName[] = {}; // not this onePROGMEM dataType variableName[] = {}; // use this form

While PROGMEM could be used on a single variable, it is really only worth the fuss if you have a larger block of data that needs to be stored, which is usually easiest in an array, (or another C data structure beyond our present discussion).

Using PROGMEM is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the pgmspace.h library, to read the data from program memory back into SRAM, so we can do something useful with it.

As mentioned above, it is important to use the datatypes outlined in pgmspace.h. Some cryptic bugs are generated by using ordinary datatypes for program memory calls. Below is a list of variable types to use. Floating point numbers in program memory do not appear to be supported.

prog_char - a signed char (1 byte) -127 to 128 prog_uchar - an unsigned char (1 byte) 0 to 255 prog_int16_t - a signed int (2 bytes) -32,767 to 32,768 prog_uint16_t - an unsigned int (2 bytes) 0 to 65,535 prog_int32_t - a signed long (4 bytes) -2,147,483,648 to * 2,147,483,647. prog_uint32_t - an unsigned long (4 bytes) 0 to 4,294,967,295

Example

The following code fragments illustrate how to read and write unsigned chars (bytes) and ints (2 bytes) to PROGMEM.

#include <avr/pgmspace.h>

// save some unsigned intsPROGMEM prog_uint16_t charSet[] = { 65000, 32796, 16843, 10, 11234};

// save some charsprog_uchar signMessage[] PROGMEM = {"I AM PREDATOR, UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"};

unsigned int displayInt;int k; // counter variablechar myChar;

144

Page 146: Arduino Language Reference

// read back a 2-byte int displayInt = pgm_read_word_near(charSet + k)

// read back a char myChar = pgm_read_byte_near(signMessage + k);

Arrays of strings

It is often convenient when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is in actually an example of a two-dimensional array.

These tend to be large structures so putting them into program memory is often desirable. The code below illustrates the idea.

/* PROGMEM string demo. How to store a table of strings in program memory (flash), and retrieve them.

Information summarized from: http://www.nongnu.org/avr-libc/user-manual/pgmspace.html

Setting up a table (array) of strings in program memory is slightly complicated, but here is a good template to follow.

Setting up the strings is a two-step process. First define the strings.

*/

#include <avr/pgmspace.h>prog_char string_0[] PROGMEM = "String 0"; // "String 0" etc are strings to store - change to suit.prog_char string_1[] PROGMEM = "String 1";prog_char string_2[] PROGMEM = "String 2";prog_char string_3[] PROGMEM = "String 3";prog_char string_4[] PROGMEM = "String 4";prog_char string_5[] PROGMEM = "String 5";

// Then set up a table to refer to your strings.

PROGMEM const char *string_table[] = // change "string_table" name to suit{ string_0, string_1, string_2, string_3, string_4, string_5 };

char buffer[30]; // make sure this is large enough for the largest string it must hold

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

145

Page 147: Arduino Language Reference

}void loop() {

/* Using the string table in program memory requires the use of special functions to retrieve the data. The strcpy_P function copies a string from program space to a string in RAM ("buffer"). Make sure your receiving string in RAM is large enough to hold whatever you are retrieving from program space. */

for (int i = 0; i < 6; i++) { strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing,

just copy. Serial.println( buffer ); delay( 500 ); }}

pulseIn()

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds. Gives up and returns 0 if no pulse starts within a specified time out.

The timing of this function has been determined empirically and will probably show errors in longer pulses. Works on pulses from 10 microseconds to 3 minutes in length.

Syntax: pulseIn(pin, value)pulseIn(pin, value, timeout)

Parameters: pin: the number of the pin on which you want to read the pulse. (int)value: type of pulse to read: either HIGH or LOW. (int)timeout (optional): the number of microseconds to wait for the pulse to start; default is one second (unsigned long)

Returns: the length of the pulse (in microseconds) or 0 if no pulse started before the timeout (unsigned long)

Example

int pin = 7;unsigned long duration;void setup(){ pinMode(pin, INPUT);}void loop(){ duration = pulseIn(pin, HIGH);}

146

Page 148: Arduino Language Reference

random()

The random function generates pseudo-random numbers.

Syntax: random(max)random(min, max)

Parameters: min - lower bound of the random value, inclusive (optional)max - upper bound of the random value, exclusive

Returns: a random number between min and max-1 (long)

Note: If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

Example

long randNumber;

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

// if analog input pin 0 is unconnected, random analog noise will cause the call to randomSeed() to // generate different seed numbers each time the sketch runs. randomSeed() will then shuffle the// random function.

randomSeed(analogRead(0));}

void loop() { // print a random number from 0 to 299 randNumber = random(300); Serial.println(randNumber);

// print a random number from 10 to 19 randNumber = random(10, 20); Serial.println(randNumber);

delay(50);}

147

Page 149: Arduino Language Reference

randomSeed(seed)

randomSeed() initializes the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same.

If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use pseudo-random sequences that repeat exactly. This can be accomplished by calling randomSeed() with a fixed number, before starting the random sequence.

Parameters: long, int - pass a number to generate the seed.Returns: no returns

Example

long randNumber;

void setup(){ Serial.begin(9600); randomSeed(analogRead(0));}

void loop(){ randNumber = random(300); Serial.println(randNumber);

delay(50);}

return

Terminate a function and return a value from a function to the calling function, if desired.

Syntax: return;return value; // both forms are valid

Parameters: value: any variable or constant type

Examples:

A function to compare a sensor input to a threshold

int checkSensor(){ if (analogRead(0) > 400) { return 1; else{ return 0; }

148

Page 150: Arduino Language Reference

}

The return keyword is handy to test a section of code without having to "comment out" large sections of possibly buggy code.

void loop(){

// brilliant code idea to test here

return;

// the rest of a dysfunctional sketch here// this code will never be executed}

Variable Scope

Variables in the C programming language, which Arduino uses, have a property called scope. This is in contrast to languages such as BASIC where every variable is a global variable.

A global variable is one that can be seen by every function in a program. Local variables are only visible to the function in which they are declared. In the Arduino environment, any variable declared outside of a function (e.g. setup(), loop(), etc. ), is a global variable.

When programs start to get larger and more complex, local variables are a useful way to insure that only one function has access to its own variables. This prevents programming errors when one function inadvertently modifies variables used by another function.

It is also sometimes handy to declare and initialize a variable inside a for loop. This creates a variable that can only be accessed from inside the for-loop brackets.

Example

int gPWMval; // any function will see this variablevoid setup(){ // ...}

void loop(){ int i; // "i" is only "visible" inside of "loop" float f; // "f" is only "visible" inside of "loop" // ...

for (int j = 0; j <100; j++){ // variable j can only be accessed inside the for-loop brackets }}

149

Page 151: Arduino Language Reference

SD

sd.begin()

Initializes the SD library and card. This begins use of the SPI bus (digital pins 11, 12, and 13 on most Arduino boards; 50, 51, and 52 on the Mega) and the chip select pin, which defaults to the hardware SS pin (pin 10 on most Arduino boards, 53 on the Mega). Note that even if you use a different chip select pin, the hardware SS pin must be kept as an output or the SD library functions will not work.

Syntax: SD.begin()SD.begin(cspin)

Parameters: cspin (optional): the pin connected to the chip select line of the SD card; defaults to the hardware SS line of the SPI bus

Returns: true on success; false on failure

Some things to keep in mind when using the SD Library

Overview

The communication between the microcontroller and the SD card uses SPI, which takes place on digital pins 11, 12, and 13 (on most Arduino boards) or 50, 51, and 52 (Arduino Mega). Additionally, another pin must be used to select the SD card. This can be the hardware SS pin - pin 10 (on most Arduino boards) or pin 53 (on the Mega) - or another pin specified in the call to SD.begin(). Note that even if you don't use the hardware SS pin, it must be left as an output or the SD library won't work. Different boards use different pins for this functionality, so be sure you’ve selected the correct pin in SD.begin().

Not all the functions are listed on the main SD library page, because they are part of the library's utility functions.

Formatting/Preparing the card

(NB : whenever referring to the SD card, it means SD and microSD sizes, as well as SD and SDHD formats)

You’ll need a SD reader and computer to format your card properly. The library supports the FAT16 and FAT32 filesystems, but use FAT16 when possible. The process to format is fairly straightforward.

File Naming

FAT file systems have a limitation when it comes to naming conventions. You must use the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8 character or fewer string, and “EXT” is a 3 character extension. People commonly use the extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or time.log), but you cannot use longer file names. Read more on the 8.3 convention.

Opening/Closing files

150

Page 152: Arduino Language Reference

When you use file.write(), it doesn't write to the card until you flush() or close(). Whenever you open a file, be sure to close it to save your data.

As of version 1.0, it is possible to have multiple files open.

Different Shields/boards

There are a number of different shields that support SD cards. This list is not exclusive, but are commonly used.

Arduino Ethernet Shield

The Ethernet Shield comes with an SD card slot onboard. The shield fits on top of your Arduino. Because the Ethernet module uses pin 10, the CS pin for the SD card has been moved to pin 4. Make sure you use SD.begin(4) to use the SD card functionality.

Adafruit Micro-SD breakout Board

This board supports Micro-SD cards, ans you’ll need to wire it up before you can use it. On the board, connect GND to ground, 5v to 5v, CLK to Pin 13 on your Arduino, DO to pin 12, DI to pin 11, and CS to pin 10. If you are already using pin 10, you can use a different pin, as long as you remember to change the pin in SD.begin().

Sparkfun SD Shield

The Sparkfun shield fits on your Arduino and uses pin 8 for CS. You will need use SD.begin(8) to use the card.NB: the Sparkfun shield was recently updated. Older versions look similar, but were lacking a connection to the 3.3V bus and did not have the onboard hex inverter.

SD

sd.exists()

Tests whether a file or directory exists on the SD card.

Syntax: SD.exists(filename)

Parameters: filename: the name of the file to test for existence, which can include directories (delimited by forward-slashes, /)

Returns: true if the file or directory exists, false if not

SD

sd.mkdir()

Create a directory on the SD card. This will also create any intermediate directories that don't already exists; e.g. SD.mkdir("a/b/c") will create a, b, and c.

151

Page 153: Arduino Language Reference

Syntax: SD.mkdir(filename)

Parameters: filename: the name of the directory to create, with sub-directories separated by forward-slashes, /

Returns: true if the creation of the directory succeeded, false if not

SD

sd.open()

Opens a file on the SD card. If the file is opened for writing, it will be created if it doesn't already exist (but the directory containing it must already exist).

WARNING! only one file can be open at a time.

Syntax: SD.open(filepath)SD.open(filepath, mode)

Parameters: filename: the name the file to open, which can include directories (delimited by forward slashes, /) - char *mode (optional): the mode in which to open the file, defaults to FILE_READ - byte. one of:FILE_READ: open the file for reading, starting at the beginning of the file.FILE_WRITE: open the file for reading and writing, starting at the end of the file.

Returns: a File object referring to the opened file; if the file couldn't be opened, this object will evaluate to false in a boolean context, i.e. you can test the return value with "if (f)".

SD

sd.remove()

Remove a file from the SD card.

Syntax: SD.remove(filename)

Parameters: filename: the name of the file to remove, which can include directories (delimited by forward-slashes, /)

Returns: true if the removal of the file succeeded, false if not. (if the file didn't exist, the return value is unspecified)

SD

sd.rmdir()

Remove a directory from the SD card. The directory must be empty.

152

Page 154: Arduino Language Reference

Syntax: SD.rmdir(filename)

Parameters: filename: the name of the directory to remove, with sub-directories separated by forward-slashes, /

Returns: true if the removal of the directory succeeded, false if not. (if the directory didn't exist, the return value is unspecified)

SD : File class

available()

Check if there are any bytes available for reading from the file. available() inherits from the Stream utility class.

Syntax: file.available()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: the number of bytes available (int)

SD : File class

close()

Close the file, and ensure that any data written to it is physically saved to the SD card.

Syntax: file.close()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: none

SD : File class

flush()

Ensures that any bytes written to the file are physically saved to the SD card. This is done automatically when the file is closed.

Syntax: file.flush()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: none

153

Page 155: Arduino Language Reference

SD : File class

isDirectory()

Directories (or folders) are special kinds of files, this function reports if the current file is a directory or not.

Syntax: file.isDirectory()

Parameters: file: an instance of the File class (returned by file.open()

Returns: boolean

Example

#include <SD.h>File root;

void setup(){ Serial.begin(9600); pinMode(10, OUTPUT); SD.begin(10); root = SD.open("/"); printDirectory(root, 0); Serial.println("done!");}

void loop(){ // nothing happens after setup finishes.}

void printDirectory(File dir, int numTabs) { while(true) { File entry = dir.openNextFile(); if (! entry) { // no more files //Serial.println("**nomorefiles**"); break; }

for (uint8_t i=0; i<numTabs; i++) { Serial.print('\t'); }

Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs+1); } else {

154

Page 156: Arduino Language Reference

// files have sizes, directories do not Serial.print("\t\t"); Serial.println(entry.size(), DEC); } }}

SD : File class

openNextFile()

Reports the next file or folder in a directory.

Syntax: file.openNextFile()

Parameters: file: an instance of the File class that is a directory

Returns: char : the next file or folder in the path

Example

#include <SD.h>File root;void setup(){ Serial.begin(9600); pinMode(10, OUTPUT); SD.begin(10); root = SD.open("/"); printDirectory(root, 0); Serial.println("done!");}

void loop(){ // nothing happens after setup finishes.}

void printDirectory(File dir, int numTabs) {

while(true) { File entry = dir.openNextFile();

if (! entry) { // no more files Serial.println("**nomorefiles**"); }

for (uint8_t i=0; i<numTabs; i++) { Serial.print('\t');

155

Page 157: Arduino Language Reference

}

Serial.print(entry.name());

if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs+1); } else {

// files have sizes, directories do notSerial.print("\t\t");Serial.println(entry.size(), DEC);

} }}

SD : File class

peek()

Read a byte from the file without advancing to the next one. That is, successive calls to peek() will return the same value, as will the next call to read(). peek() inherits from the Stream utility class.

Syntax: file.peek()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: The next byte (or character), or -1 if none is available.

SD : File class

position()

Get the current position within the file (i.e. the location to which the next byte will be read from or written to).

Syntax: file.position()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: the position within the file (unsigned long)

SD : File class

print()

Print data to the file, which must have been opened for writing. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

156

Page 158: Arduino Language Reference

Syntax: file.print(data) file.print(data, BASE)

Parameters: file: an instance of the File class (returned by SD.open())data: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byteprint() will return the number of bytes written, though reading that number is optional.

SD : File class

println()

Print data, followed by a carriage return and newline, to the File, which must have been opened for writing. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: file.println() file.println(data) file.print(data, BASE)

Parameters: file: an instance of the File class (returned by SD.open())data (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byteprintln() will return the number of bytes written, though reading that number is optional.

SD : File class

read()

Read a byte from the file. read() inherits from the Stream utility class.

Syntax: file.read()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: The next byte (or character), or -1 if none is available.

157

Page 159: Arduino Language Reference

SD : File class

rewindDirectory()

rewindDirectory() will bring you back to the first file in the directory, used in conjunction with openNextFile().

Syntax: file.rewindDirectory()

Parameters: file: an instance of the File class.

Returns: None

Example

#include <SD.h>File root;

void setup(){ Serial.begin(9600); pinMode(10, OUTPUT); SD.begin(10); root = SD.open("/"); printDirectory(root, 0); Serial.println("done!");}

void loop(){ // nothing happens after setup finishes.}

void printDirectory(File dir, int numTabs) {while(true) {

File entry = dir.openNextFile();

if (! entry) {// no more files// return to the first file in the directorydir.rewindDirectory();break;

}

for (uint8_t i=0; i<numTabs; i++) { Serial.print('\t');}

Serial.print(entry.name());if (entry.isDirectory()) {

Serial.println("/");

158

Page 160: Arduino Language Reference

printDirectory(entry, numTabs+1);} else {

// files have sizes, directories do notSerial.print("\t\t");Serial.println(entry.size(), DEC);

} }}

SD : File class

seek()

Seek to a new position in the file, which must be between 0 and the size of the file (inclusive).

Syntax: file.seek(pos)

Parameters: file: an instance of the File class (returned by SD.open())pos: the position to which to seek (unsigned long)

Returns: true for success, false for failure (boolean)

SD : File class

size()

Get the size of the file.

Syntax: file.size()

Parameters: file: an instance of the File class (returned by SD.open())

Returns: the size of the file in bytes (unsigned long)

SD : File class

write()

Write data to the file.

Syntax: file.write(data) file.write(buf, len)

Parameters: file: an instance of the File class (returned by SD.open())data: the byte, char, or string (char *) to writebuf: an array of characters or byteslen: the number of elements in buf

Returns: byte write() will return the number of bytes written, though reading that number is

159

Page 161: Arduino Language Reference

optionalExamples:

/* SD card read/write This example shows how to read and write data to and from an SD card fájl. The circuit: ** SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 */ #include <SD.h>File myFile;

void setup(){ // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

Serial.print("Initializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. pinMode(10, OUTPUT); if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. myFile = SD.open("test.txt", FILE_WRITE); // if the file opened okay, write to it: if (myFile) { Serial.print("Writing to test.txt..."); myFile.println("testing 1, 2, 3."); // close the file: myFile.close(); Serial.println("done."); } else { // if the file didn't open, print an error:

160

Page 162: Arduino Language Reference

Serial.println("error opening test.txt"); } // re-open the file for reading: myFile = SD.open("test.txt"); if (myFile) { Serial.println("test.txt:"); // read from the file until there's nothing else in it: while (myFile.available()) { Serial.write(myFile.read()); } // close the file: myFile.close(); } else { // if the file didn't open, print an error: Serial.println("error opening test.txt"); }}

void loop(){ // nothing happens after setup}

Datalogger

/*SD card datalogger This example shows how to log data from three analog sensors to an SD card using the SD library. The circuit: ** analog sensors on analog ins 0, 1, and 2 ** SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 */

#include <SD.h>

// On the Ethernet Shield, CS is pin 4. Note that even if it's not// used as the CS pin, the hardware CS pin (10 on most Arduino boards,// 53 on the Mega) must be left as an output or the SD library// functions will not work.const int chipSelect = 4;

void setup()

161

Page 163: Arduino Language Reference

{ // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

Serial.print("Initializing SD card..."); // make sure that the default chip select pin is set to // output, even if you don't use it: pinMode(10, OUTPUT); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } Serial.println("card initialized.");}

void loop(){ // make a string for assembling the data to log: String dataString = "";

// read three sensors and append to the string: for (int analogPin = 0; analogPin < 3; analogPin++) { int sensor = analogRead(analogPin); dataString += String(sensor); if (analogPin < 2) { dataString += ","; } }

// open the file. note that only one file can be open at a time, File dataFile = SD.open("datalog.txt", FILE_WRITE);

// if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } }

162

Page 164: Arduino Language Reference

DumpFile

/*SD card file dump This example shows how to read a file from the SD card using the SD library and send it over the serial port. The circuit: ** SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 */

#include <SD.h>

// On the Ethernet Shield, CS is pin 4. Note that even if it's not// used as the CS pin, the hardware CS pin (10 on most Arduino boards,// 53 on the Mega) must be left as an output or the SD library// functions will not work.const int chipSelect = 4;

void setup(){ // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

Serial.print("Initializing SD card..."); // make sure that the default chip select pin is set to // output, even if you don't use it: pinMode(10, OUTPUT); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } Serial.println("card initialized."); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("datalog.txt");

// if the file is available, write to it: if (dataFile) { while (dataFile.available()) {

163

Page 165: Arduino Language Reference

Serial.write(dataFile.read()); } dataFile.close(); } // if the file isn't open, pop up an error: else { Serial.println("error opening datalog.txt"); } }

void loop(){}

CardInfo

/*

SD card test This example shows how use the utility libraries on which the SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not. The circuit: ** SD card attached to SPI bus as follows: ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila ** CS - depends on your SD card shield or module. Pin 4 used here for consistency with other Arduino examples*/// include the SD library:#include <SD.h>

// set up variables using the SD utility library functions:Sd2Card card;SdVolume volume;SdFile root;

// change this to match your SD shield or module;// Arduino Ethernet shield: pin 4// Adafruit SD shields and modules: pin 10// Sparkfun SD shield: pin 8const int chipSelect = 4;

void setup(){ // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) {

164

Page 166: Arduino Language Reference

; // wait for serial port to connect. Needed for Leonardo only }

Serial.print("\nInitializing SD card..."); // On the Ethernet Shield, CS is pin 4. It's set as an output by default. // Note that even if it's not used as the CS pin, the hardware SS pin // (10 on most Arduino boards, 53 on the Mega) must be left as an output // or the SD library functions will not work. pinMode(10, OUTPUT); // change this to 53 on a mega

// we'll use the initialization code from the utility libraries // since we're just testing if the card is working! if (!card.init(SPI_HALF_SPEED, chipSelect)) { Serial.println("initialization failed. Things to check:"); Serial.println("* is a card is inserted?"); Serial.println("* Is your wiring correct?"); Serial.println("* did you change the chipSelect pin to match your shield or module?"); return; } else { Serial.println("Wiring is correct and a card is present."); } // print the type of card Serial.print("\nCard type: "); switch(card.type()) { case SD_CARD_TYPE_SD1: Serial.println("SD1"); break; case SD_CARD_TYPE_SD2: Serial.println("SD2"); break; case SD_CARD_TYPE_SDHC: Serial.println("SDHC"); break; default: Serial.println("Unknown"); }

// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32 if (!volume.init(card)) { Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"); return; }

// print the type and size of the first FAT-type volume uint32_t volumesize; Serial.print("\nVolume type is FAT"); Serial.println(volume.fatType(), DEC); Serial.println(); volumesize = volume.blocksPerCluster(); // clusters are collections of blocks volumesize *= volume.clusterCount(); // we'll have a lot of clusters volumesize *= 512; // SD card blocks are always 512 bytes

165

Page 167: Arduino Language Reference

Serial.print("Volume size (bytes): "); Serial.println(volumesize); Serial.print("Volume size (Kbytes): "); volumesize /= 1024; Serial.println(volumesize); Serial.print("Volume size (Mbytes): "); volumesize /= 1024; Serial.println(volumesize);

Serial.println("\nFiles found on the card (name, date and size in bytes): "); root.openRoot(volume); // list all files in the card with date and size root.ls(LS_R | LS_DATE | LS_SIZE);}

void loop(void) {}

; semicolon

Used to end a statement.

Example

int a = 13;

Tip: Forgetting to end a line in a semicolon will result in a compiler error. The error text may be obvious, and refer to a missing semicolon, or it may not. If an impenetrable or seemingly illogical compiler error comes up, one of the first things to check is a missing semicolon, in the immediate vicinity, preceding the line at which the compiler complained.

Serial

Used for communication between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port (also known as a UART or USART): Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1 for digital input or output.

You can use the Arduino environment's built-in serial monitor to communicate with an Arduino board. Click the serial monitor button in the toolbar and select the same baud rate used in the call to begin().

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

166

Page 168: Arduino Language Reference

an RS232 serial port; they operate at +/- 12V and can damage your Arduino board.)

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

Functions

o if (Serial) o available()o begin() o end()o find() o findUntil()o flush() o parseFloat()o parseInt() o peek()o print() o println()o read() o readBytes()o readBytesUntil() o setTimeout()o write() o serialEvent()

Examples

o ReadASCIIString o ASCII Table o Dimmer o Graph o Physical Pixel o Virtual Color Mixer o Serial Call Response o Serial Call Response ASCII

SerialEvent

serialEvent()

Called when data is available. Use Serial.read() to capture this data.

Syntax void serialEvent(){ //statements }

Arduino Mega only:

void serialEvent1(){//statements

}void serialEvent2(){

//statements}void serialEvent3(){

//statements }

167

Page 169: Arduino Language Reference

Parameters: statements: any valid statements

Example

/* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. */

String inputString = ""; // a string to hold incoming databoolean stringComplete = false; // whether the string is complete

void setup() { // initialize serial: Serial.begin(9600); // reserve 200 bytes for the inputString: inputString.reserve(200);}

void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // clear the string: inputString = ""; stringComplete = false; }}

/* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */

void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } }}

168

Page 170: Arduino Language Reference

Serial.parseInt()

Serial.parseInt() returns the first valid (long) integer number from the serial buffer. Characters that are not integers (or the minus sign) are skipped. Serial.parseInt() is terminated by the first character that is not a digit.

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

Syntax: Serial.parseInt()Parameters: noneReturns: int

Servo library

This library allows an Arduino board to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds.

The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note servos draw considerable power, so if you need to drive more than one or two, you'll probably need to power them from a separate supply (i.e. not the +5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together.

Functions

o attached() o attach() o detach() o read() o write() o writeMicroseconds()

Examples

// Sweep

169

Page 171: Arduino Language Reference

#include <Servo.h> Servo myservo; // create servo object to control a servo

// a maximum of eight servo objects can be created int pos = 0; // variable to store the servo position void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } }

Servo

attached()

Check whether the Servo variable is attached to a pin.

Syntax: servo.attached()Parameters: servo: a variable of type ServoReturns: true if the servo is attached to pin; false otherwise.

Servo

attach()

Attach the Servo variable to a pin. Note that in Arduino 0016 and earlier, the Servo library supports only servos on only two pins: 9 and 10.

Syntax: servo.attach(pin) servo.attach(pin, min, max)

Parameters: servo: a variable of type Servopin: the number of the pin that the servo is attached tomin (optional): the pulse width, in microseconds, corresponding to the minimum (0-

170

Page 172: Arduino Language Reference

degree) angle on the servo (defaults to 544)max (optional): the pulse width, in microseconds, corresponding to the maximum (180-degree) angle on the servo (defaults to 2400)

Example

#include <Servo.h>

Servo myservo;

void setup() { myservo.attach(9);}

void loop() {}

Servo

detach()

Detach the Servo variable from its pin. If all Servo variables are detached, then pins 9 and 10 can be used for PWM output with analogWrite().

Syntax: servo.detach()Parameters: servo: a variable of type Servo

Servo

read()

Read the current angle of the servo (the value passed to the last call to write()).

Syntax: servo.read()Parameters: servo: a variable of type ServoReturns: The angle of the servo, from 0 to 180 degrees.

Servo

write()

Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

Syntax: servo.write(angle)Parameters: servo: a variable of type Servo

angle: the value to write to the servo, from 0 to 180Example

171

Page 173: Arduino Language Reference

#include <Servo.h>

Servo myservo;

void setup() { myservo.attach(9); myservo.write(90); // set servo to mid-point}

void loop() {}

Servo

writeMicroseconds()

Writes a value in microseconds (uS) to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft. On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle.

Note that some manufactures do not follow this standard very closely so that servos often respond to values between 700 and 2300. Feel free to increase these endpoints until the servo no longer continues to increase its range. Note however that attempting to drive a servo past its endpoints (often indicated by a growling sound) is a high-current state, and should be avoided.

Continuous-rotation servos will respond to the writeMicrosecond function in an analogous manner to the write function.

Syntax: servo.writeMicroseconds(uS)

Parameters: servo: a variable of type ServouS: the value of the parameter in microseconds (int)

Example

#include <Servo.h>

Servo myservo;

void setup() { myservo.attach(9); myservo.writeMicroseconds(1500); // set servo to mid-point}

void loop() {}

172

Page 174: Arduino Language Reference

setup()

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.

Example

int buttonPin = 3;

void setup(){ Serial.begin(9600); pinMode(buttonPin, INPUT);}

void loop(){ // ...}

shiftIn()

Shifts in a byte of data one bit at a time. Starts from either the most (i.e. the leftmost) or least (rightmost) significant bit. For each bit, the clock pin is pulled high, the next bit is read from the data line, and then the clock pin is taken low.

Note: this is a software implementation; Arduino also provides an SPI library that uses the hardware implementation, which is faster but only works on specific pins.

Syntax: byte incoming = shiftIn(dataPin, clockPin, bitOrder)

Parameters: dataPin: the pin on which to input each bit (int)clockPin: the pin to toggle to signal a read from dataPinbitOrder: which order to shift in the bits; either MSBFIRST or LSBFIRST.

(Most Significant Bit First, or, Least Significant Bit First)

Returns: the value read (byte)

shiftOut()

Shifts out a byte of data one bit at a time. Starts from either the most (i.e. the leftmost) or least (rightmost) significant bit. Each bit is written in turn to a data pin, after which a clock pin is pulsed (taken high, then low) to indicate that the bit is available.

Note: if you're interfacing with a device that's clocked by rising edges, you'll need to make sure that the clock pin is low before the call to shiftOut(), e.g. with a call to digitalWrite(clockPin, LOW).

This is a software implementation; see also the SPI library, which provides a hardware

173

Page 175: Arduino Language Reference

implementation that is faster but works only on specific pins.

Syntax: shiftOut(dataPin, clockPin, bitOrder, value)

Parameters: dataPin: the pin on which to output each bit (int)clockPin: the pin to toggle once the dataPin has been set to the correct value (int)bitOrder: which order to shift out the bits; either MSBFIRST or LSBFIRST.

(Most Significant Bit First, or, Least Significant Bit First)value: the data to shift out. (byte)

Returns: None

Note: The dataPin and clockPin must already be configured as outputs by a call to pinMode().

shiftOut is currently written to output 1 byte (8 bits) so it requires a two step operation to output values larger than 255. // Do this for MSBFIRST serial int data = 500; shiftOut(dataPin, clock, MSBFIRST, (data >> 8)); // shift out highbyte shiftOut(data, clock, MSBFIRST, data); // shift out lowbyte

data = 500; // Or do this for LSBFIRST serial shiftOut(dataPin, clock, LSBFIRST, data); // shift out lowbyte shiftOut(dataPin, clock, LSBFIRST, (data >> 8)); // shift out highbyte

Example

/* Shift Register Example for two 74HC595 shift registers This sketch turns on each of the LEDs attached to two 74HC595 shift registers, in sequence from output 0 to output 15. Hardware: * 2 74HC595 shift register attached to pins 2, 3, and 4 of the Arduino, as detailed below. * LEDs attached to each of the outputs of the shift register */

const int latchPin = 8; //Pin connected to latch pin (ST_CP) of 74HC595const int clockPin = 12; //Pin connected to clock pin (SH_CP) of 74HC595const int dataPin = 11; //Pin connected to Data in (DS) of 74HC595

char inputString[2];

void setup() { //set pins to output because they are addressed in the main loop pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); Serial.begin(9600); Serial.println("reset");}

void loop() { // iterate over the 16 outputs of the two shift registers for (int thisLed = 0; thisLed < 16; thisLed++) {

174

Page 176: Arduino Language Reference

registerWrite(thisLed, HIGH); // write data to the shift registers if (thisLed > 0) { // if this is not the first LED, turn off the previous LED registerWrite(thisLed - 1, LOW); } // if this is the first LED, turn off the highest LED: else { registerWrite(15, LOW); } delay(250); // pause between LEDs }}

// This method sends bits to the shift registers:

void registerWrite(int whichPin, int whichState) { // the bits you want to send. Use an unsigned int, so you can use all 16 bits: unsigned int bitsToSend = 0;

// turn off the output so the pins don't light up while you're shifting bits: digitalWrite(latchPin, LOW);

bitWrite(bitsToSend, whichPin, whichState); // turn on the next highest bit in bitsToSend

// break the bits into two bytes, one for the first register and one for the second: byte registerOne = highByte(bitsToSend); byte registerTwo = lowByte(bitsToSend);

// shift the bytes out: shiftOut(dataPin, clockPin, MSBFIRST, registerTwo); shiftOut(dataPin, clockPin, MSBFIRST, registerOne);

digitalWrite(latchPin, HIGH); // turn on the output so the LEDs can light up}

//**************************************************************// // Notes : Code for using a 74HC595 Shift Register : to count from 0 to 255 // //****************************************************************

int latchPin = 8; //Pin connected to ST_CP of 74HC595 int clockPin = 12; //Pin connected to SH_CP of 74HC595 int dataPin = 11; //Pin connected to DS of 74HC595

void setup() { //set pins to output because they are addressed in the main loop pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); }

void loop() { //count up routine for (int j = 0; j < 256; j++) { //ground latchPin and hold low for as long as you are transmitting

175

Page 177: Arduino Language Reference

digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, j); //return the latch pin high to signal chip that it //no longer needs to listen for information digitalWrite(latchPin, HIGH); delay(1000); } }

SimpleSDAudio

Play audio files with your Arduino in decent quality from SD card, only very few additional hardware required.

Features

8-Bit PWM output - no external DAC required 62.500 kHz (fullrate) / 31.250 kHz (halfrate) sampling rate @ 16 MHz 31.250 kHz (fullrate) / 15.625 kHz (halfrate) sampling rate @ 8 Mhz PWM output is operating always at fullrate for easier filtering Mono, bridge and stereo mode RAM usage ~1.3 kByte ROM usage ~6.1 kByte Integrated SD library (minimal FAT only, optimized for low RAM usage and high performance) Works with most SD card shields that are hooked to SPI port Easy to use API: 1. init library, 2. select audio file, 3. call play, 4. call worker while audio is playing Supports SD and SDHC cards formated with FAT16 or FAT32

Restrictions

Audio file must be converted prior use Audio files must reside in root directory of card File name of audio file must be in 8.3-format Audio file must reside completely non-fragmented on card Combination of fullrate and stereo actually leads to buffer underruns Minimum controller required: ATmega168. ATmega8 is too low on RAM.

Quickstart guide

• Install library: Unzip all to your /libraries/ folder. • Copy the file /libraries/SimpleSDAudio/examples/EXAMPLE.AFM to root folder of a

freshly formated SD card (don't use quick format!). • Connect SD card to your Arduino board (using shield or whatever, SD card's chip select

should go to pin 4, all other to SPI pins). • Connect a speaker or headphone via 100 ohm resistor in series to audio output pin (pin 9 on

Arduinos with ATmega168/328, pin 44 on Arduinos with ATmega1280/2560). Connect other end of speaker to GND.

• Launch Arduino IDE and try example "BareMinimumWithDebug" first.

176

Page 178: Arduino Language Reference

• You should hear the audio (plays just a few seconds). Activate serial monitor to find some information if it does not work. Maybe you have to adjust SD cards CS pin in sketch.

Preparation of SD card and conversion of audio files

The audio library uses a very trimmed SD library that uses the FAT only to find the start sector of the files. Therefore the file must be completely non-fragmented on the SD card. The best way to ensure this is to do a fresh and full format of the card (don't use quick format!). After formating the SD card, only copy new files on it. Don't delete files and avoid rename operations that creates file names that doesn't fit into 8.3 format (see http://en.wikipedia.org/wiki/8.3_filename ). All files must placed in root directory as folders are not supported by the audio library.

To convert audio files I suggest the use of SoX from http://sox.sourceforge.net .

Linux users should compile SoX from source or use their favorite package manager to install SoX. I recommend to use the following line for conversions:

sox inputfile.wav --norm=-1 -e unsigned-integer -b 8 -r 31250 -c 1 -t raw outputfile.raw

Change the following according to your needs: For stereo change -c 1 to -c 2 For full rate use -r 62500 @ 16MHz, -r 31250 @ 8 MHz For half rate use -r 31250 @ 16MHz, -r 15625 @ 8 MHz

The option --norm=-1 is used to avoid bad sounding clipping effects.

File name conventions

Even you could choose any filename and any extension, I suggest using an extension that shows audio rate and stereo or mono mode. In the batch-files I use the following:

.AFM - Fullrate, mono

.AFS - Fullrate, stereo

.AHM - Halfrate, mono

.AHS - Halfrate, stereo

Hardware setup

The SD card should be connected to the SPI port of the controller. The chip select pin from the card can be connected to any free digital pin, but if pin 4 is used on Arduinos you don't have to adjust the source code. Many shields with SD card support like Ethernet-Shield will work. You need pegel conversion circuits from 5V to 3.3V for most Arduinos (except those that run natively on 3.3V).

According your mode configuration, one or two pins are used for audio output. This pins can not be changed and are different between different Arduino boards. For ATmega168/328 based plattforms those are pins 9 and 10. For ATmega1280/2560 those are pins 44 and 45. For other plattforms look into the file SimpleSDAudio.h.

Be careful that the audio output pins are digital ports that carry a positive voltage between 0V and 5V. It is not a good idea to have a DC voltage at line-inputs or smaller speakers as there will be a steady current flow. Therefore at least a resistor and/or a capacitor should be connected in series. For a start use at least 100 ohm or a capacitor between 100nF and 100uF. For line inputs use a voltage divider or poti to reduce the voltage.

177

Page 179: Arduino Language Reference

API reference

Constants

Here is an overview of the constants used in the library.

#define SSDA_VERSIONSTRING "1.00"

// Sound Mode Flags#define SSDA_MODE_FULLRATE 0x00 // 62.500 kHz @ 16 MHz, 31.250 kHz @ 8 MHz#define SSDA_MODE_HALFRATE 0x10 // 31.250 kHz @ 16 MHz, 15.625 kHz @ 8 MHz

#define SSDA_MODE_MONO 0x00 // Use only 1st PWM pin#define SSDA_MODE_STEREO 0x01 // Use both PWM pins for stereo output#define SSDA_MODE_MONO_BRIDGE 0x02 // Use both PWM pins for more power

// Error codes from SimpleSDAudio, see other sd_l*.h for more error codes#define SSDA_ERROR_NULL 0x80 // Null pointer#define SSDA_ERROR_BUFTOSMALL 0x81 // Buffer to small#define SSDA_ERROR_NOT_INIT 0x82 // System not initialized properly

Class name and default instance

class SdPlayClass { ... }extern SdPlayClass SdPlay;

The name of the class is SdPlayClass. One instance is already created for use and is named SdPlay.

Public class functions

init()

boolean init(uint8_t soundMode);

Call this to initialze the library and set sound mode. This function will also aquire the needed buffer (if not already set manually using setWorkBuffer), initialize SD card and sets up all used pins. A combination of the following flags must be provided as argument (combine via or-ing):

Sample rate setting flags

SSDA_MODE_FULLRATE - 62.500 kHz @ 16 MHz, 31.250 kHz @ 8 MHz SSDA_MODE_HALFRATE - 31.250 kHz @ 16 MHz, 15.625 kHz @ 8 MHz

Output channel configuration flags SSDA_MODE_MONO - Use only 1st PWM pin SSDA_MODE_STEREO - Use both PWM pins for stereo output SSDA_MODE_MONO_BRIDGE - Use both PWM pins for more power

The function return true if successfull, false if an error occured. You can use getLastError() to retrieve the error code. Typical reasons for errors are wrong SD card connection or too low RAM (1k heap required) for internal buffer available.

178

Page 180: Arduino Language Reference

setFile()

boolean setFile(char *fileName);

After init was successfull, call this to select audio file by providing the filename in 8.3 format. The function return true if successfull, false if an error occured. You can use getLastError() to retrieve the error code. Typical reasons for errors are that the file was not found.

worker()

void worker(void);

Call this continually at least as long as the audio playback is running. This function fills the internal playback buffer by reading the next sectors from SD card. You can´t call this function too often, but a buffer underrun can occur when the time between two calls are too long.

play()

void play(void);

If audio is not playing, playing will be started. If it is already playing, it will start playing from zero again.

stop()

void stop(void);

Stops playback if playing, sets playposition to zero.

pause()

void pause(void);

Pauses playing if not playing, resumes playing if was paused.

setSDCSPin()

void setSDCSPin(uint8_t csPin);

Call this before init to set SD-Cards CS-Pin to other than default.

setWorkBuffer()

void setWorkBuffer(uint8_t *pBuf, uint16_t bufSize);

Call this if you want to use your own buffer (at least 1024 bytes, must be multiple of 512). Call this before init and then init will use this buffer instead using malloc to create its own.

deInit()

void deInit(void);

179

Page 181: Arduino Language Reference

Call this to free resources like buffer, release SD card pins, audio interrupts and audio pins.

dir()

void dir(void (*callback)(char *));

Output the directory of the SD card. A pointer to a callback function must be provided. The callback function is called once for every file found in the root directory of the card. The strings contain zero-termination but no linefeeds.

Example:

...// setup global callback functionvoid dir_callback(char *buf) { Serial.println(buf);}...

// somewhere after initialization SdPlay.dir(&dir_callback);

isStopped(), isPlaying(), isPaused()

boolean isStopped(void);boolean isPlaying(void);boolean isPaused(void);

Returns the current state of the playback. The function isStopped() can be used after issuing play() to determine when the playback has finished.

isUnderrunOccured()

boolean isUnderrunOccured(void);

Returns if the internal underrun-flag is set and clears it. If audio sounds strange or has dropouts, test if underruns are the cause.

getLastError()

uint8_t getLastError(void);

Retrieve the last error code and clears it. To analyse the error reason, take a look also at the files sd_l1.h and sd_l2.h of the library to find the meaning of the code. FAQ

SdPlay.init fails Have you selected the correct CS pin for your SD-card? Uncomment the line // SdPlay.setSDCSPin(10);in the examples and enter correct pin number here.

180

Page 182: Arduino Language Reference

Your SD shield may be crap and SD communication is only possible with limited speed. Try commenting the line SPSR |= (1 << SPI2X);in function SD_L0_SpiSetHighSpeed(). If this doesn't help, comment out also the first line and try again. If then init works you have a bad SD card shield.

sin(rad)

Calculates the sine of an angle (in radians). The result will be between -1 and 1.

Parameters: rad: the angle in radians (float)

Returns: the sine of the angle (double)

sizeof

The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.

Syntax: sizeof(variable)

Parameters: variable: any variable type or array (e.g. int, float, byte)

Example

The sizeof operator is useful for dealing with arrays (such as strings) where it is convenient to be able to change the size of the array without breaking other parts of the program.

This program prints out a text string one character at a time. Try changing the text phrase.

char myStr[] = "this is a test";int i;

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

void loop() { for (i = 0; i < sizeof(myStr) - 1; i++){ Serial.print(i, DEC); Serial.print(" = "); Serial.write(myStr[i]); Serial.println(); } delay(5000); // slow down the program}

Note that sizeof returns the total number of bytes. So for larger variable types such as ints, the for loop would look something like this. Note also that a properly formatted string ends with the NULL symbol, which has ASCII value 0.

181

Page 183: Arduino Language Reference

for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) { // do something with myInts[i]}

SoftwareSerial Library

The Arduino hardware has built-in support for serial communication on pins 0 and 1 (which also goes to the computer via the USB connection). The native serial support happens via a piece of hardware (built into the chip) called a UART. This hardware allows the Atmega chip to receive serial communication even while working on other tasks, as long as there room in the 64 byte serial buffer.

The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality (hence the name "SoftwareSerial"). It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

The version of SoftwareSerial included in 1.0 and later is based on the NewSoftSerial library by Mikal Hart.

Limitations

The library has the following known limitations:

o If using multiple software serial ports, only one can receive data at a time. o Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 o Not all pins on the Leonardo support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

Example

/* Software serial multple serial test

Receives from the hardware serial, sends to software serial. Receives from software serial, sends to hardware serial.

The circuit: * RX is digital pin 10 (connect to TX of other device) * TX is digital pin 11 (connect to RX of other device)

Note: Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

Not all pins on the Leonardo support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

182

Page 184: Arduino Language Reference

created back in the mists of time modified 25 May 2012 by Tom Igoe based on Mikal Hart's example

This example code is in the public domain.

*/ #include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() { // Open serial communications and wait for port to open: Serial.begin(57600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

Serial.println("Goodnight moon!");

// set the data rate for the SoftwareSerial port mySerial.begin(4800); mySerial.println("Hello, world?"); }

void loop() // run over and over { if (mySerial.available()) Serial.write(mySerial.read()); if (Serial.available()) mySerial.write(Serial.read()); }

Functions

o SoftwareSerial() o available() o begin() o isListening() o overflow() o peek() o read() o print() o println() o listen() o write()

183

Page 185: Arduino Language Reference

SoftwareSerial: available()

Get the number of bytes (characters) available for reading from a software serial port. This is data that's already arrived and stored in the serial receive buffer.

Syntax: mySerial.available()

Parameters: none

Returns: the number of bytes available to read

Example

// include the SoftwareSerial library so you can use its functions: #include <SoftwareSerial.h>

#define rxPin 10 #define txPin 11

// set up a new serial port SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

void setup() { // define pin modes for tx, rx: pinMode(rxPin, INPUT); pinMode(txPin, OUTPUT); // set the data rate for the SoftwareSerial port mySerial.begin(9600); }

void loop() { if (mySerial.available()>0){ mySerial.read(); } }

SoftwareSerial: begin(speed)

Sets the speed (baud rate) for the serial communication. Supported baud rates are 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 31250, 38400, 57600, and 115200.

Parameters: speed: the baud rate (long)

Returns: none

Example

// include the SoftwareSerial library so you can use its functions: #include <SoftwareSerial.h>

184

Page 186: Arduino Language Reference

#define rxPin 10 #define txPin 11

// set up a new serial port SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

void setup() { // define pin modes for tx, rx: pinMode(rxPin, INPUT); pinMode(txPin, OUTPUT); // set the data rate for the SoftwareSerial port mySerial.begin(9600); }

void loop() { // ... }

SoftwareSerial(rxPin, txPin)

A call to SoftwareSerial(rxPin, txPin) creates a new SoftwareSerial object, whose name you need to provide as in the example below.

You need to call SoftwareSerial.begin() to enable communication.

Parameters: rxPin: the pin on which to receive serial datatxPin: the pin on which to transmit serial data

Example

#define rxPin 2 #define txPin 3

// set up a new serial port SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

SoftwareSerial: isListening()

Tests to see if requested software serial port is actively listening.

Syntax: mySerial.isListening()

Parameters: none

Returns: boolean

Example

#include <SoftwareSerial.h>

185

Page 187: Arduino Language Reference

// software serial : TX = digital pin 10, RX = digital pin 11 SoftwareSerial portOne(10,11);

void setup() { // Start the hardware serial port Serial.begin(9600);

// Start software serial port portOne.begin(9600); }

void loop() { if (portOne.isListening()) { Serial.println("Port One is listening!"); }

SoftwareSerial: listen()

Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).

Syntax: mySerial.listen()

Parameters: mySerial:the name of the instance to listen

Returns: None

Example

#include <SoftwareSerial.h>

// software serial : TX = digital pin 10, RX = digital pin 11 SoftwareSerial portOne(10, 11);

// software serial : TX = digital pin 8, RX = digital pin 9 SoftwareSerial portTwo(8, 9);

void setup() { // Start the hardware serial port Serial.begin(9600);

// Start both software serial ports portOne.begin(9600); portTwo.begin(9600); } void loop() {

186

Page 188: Arduino Language Reference

portOne.listen();

if (portOne.isListening()) { Serial.println("Port One is listening!"); }else{ Serial.println("Port One is not listening!"); }

if (portTwo.isListening()) { Serial.println("Port Two is listening!"); }else{ Serial.println("Port Two is not listening!"); } }

SoftwareSerial: overflow()

Tests to see if a software serial buffer overflow has occurred. Calling this function clears the overflow flag, meaning that subsequent calls will return false unless another byte of data has been received and discarded in the meantime.

The software serial buffer can hold 64 bytes.

Syntax: mySerial.overflow()

Parameters: none

Returns: boolean

Example

#include <SoftwareSerial.h>

// software serial : TX = digital pin 10, RX = digital pin 11 SoftwareSerial portOne(10,11);

void setup() { // Start the hardware serial port Serial.begin(9600);

// Start software serial port portOne.begin(9600); }

void loop() { if (portOne.overflow()) { Serial.println("SoftwareSerial overflow!"); }

187

Page 189: Arduino Language Reference

SoftwareSerial: peek

Return a character that was received on the RX pin of the software serial port. Unlike read(), however, subsequent calls to this function will return the same character.

Note that only one SoftwareSerial instance can receive incoming data at a time (select which one with the listen() function).

Parameters: none

Returns: the character read, or -1 if none is available

Example

SoftwareSerial mySerial(10,11);

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

void loop() { char c = mySerial.peek(); }

SoftwareSerial: print(data)

Prints data to the transmit pin of the software serial port. Works the same as the Serial.print() function.

Parameters: vary, see Serial.print() for details

Returns: byte print() will return the number of bytes written, though reading that number is

optionalExample

SoftwareSerial serial(10,11); int analogValue;

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

void loop() { // read the analog input on pin 0: analogValue = analogRead(A0);

188

Page 190: Arduino Language Reference

// print it out in many formats: serial.print(analogValue); // print as an ASCII-encoded decimal serial.print("\t"); // print a tab character serial.print(analogValue, DEC); // print as an ASCII-encoded decimal serial.print("\t"); // print a tab character serial.print(analogValue, HEX); // print as an ASCII-encoded hexadecimal serial.print("\t"); // print a tab character serial.print(analogValue, OCT); // print as an ASCII-encoded octal serial.print("\t"); // print a tab character serial.print(analogValue, BIN); // print as an ASCII-encoded binary serial.print("\t"); // print a tab character serial.print(analogValue/4, BYTE); // print as a raw byte value (divide the // value by 4 because analogRead() returns numbers // from 0 to 1023, but a byte can only hold values // up to 255) serial.print("\t"); // print a tab character serial.println(); // print a linefeed character

// delay 10 milliseconds before the next reading: delay(10); }

SoftwareSerial: println(data)

Prints data to the transmit pin of the software serial port, followed by a carriage return and line feed. Works the same as the Serial.println() function.

Parameters: vary, see Serial.println() for details

Returns byte println() will return the number of bytes written, though reading that number is

optionalExample

SoftwareSerial serial(10,11); int analogValue;

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

void loop() { // read the analog input on pin 0: analogValue = analogRead(A0);

// print it out in many formats: serial.print(analogValue); // print as an ASCII-encoded decimal serial.print("\t"); // print a tab character serial.print(analogValue, DEC); // print as an ASCII-encoded decimal

189

Page 191: Arduino Language Reference

serial.print("\t"); // print a tab character serial.print(analogValue, HEX); // print as an ASCII-encoded hexadecimal serial.print("\t"); // print a tab character serial.print(analogValue, OCT); // print as an ASCII-encoded octal serial.print("\t"); // print a tab character serial.print(analogValue, BIN); // print as an ASCII-encoded binary serial.print("\t"); // print a tab character serial.print(analogValue/4, BYTE); // print as a raw byte value (divide the // value by 4 because analogRead() returns numbers // from 0 to 1023, but a byte can only hold values // up to 255) serial.print("\t"); // print a tab character serial.println(); // print a linefeed character

// delay 10 milliseconds before the next reading: delay(10); }

SoftwareSerial: read

Return a character that was received on the RX pin of the software serial port. Note that only one SoftwareSerial instance can receive incoming data at a time (select which one with the listen() function).

Parameters: none

Returns: the character read, or -1 if none is available

Example

SoftwareSerial mySerial(10,11);

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

void loop() { char c = mySerial.read(); }

SoftwareSerial: write(data)

Prints data to the transmit pin of the software serial port as raw bytes. Works the same as the Serial.write() function.

Parameters: Serial.write() for details

Returns: byte

190

Page 192: Arduino Language Reference

write() will return the num. of bytes written, though reading that number is optional

Example

SoftwareSerial mySerial(10, 11);

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

void loop() { mySerial.write(45); // send a byte with the value 45

int bytesSent = mySerial.write(“hello”); //send the string “hello” and return the length of the string. }

SPI library

This library allows you to communicate with SPI devices, with the Arduino as the master device.

A Brief Introduction to the Serial Peripheral Interface (SPI)

Serial Peripheral Interface (SPI) is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It can also be used for communication between two microcontrollers.

With an SPI connection there is always one master device (usually a microcontroller) which controls the peripheral devices. Typically there are three lines common to all the devices:

- Master In Slave Out (MISO) - The Slave line for sending data to the master

- Master Out Slave In (MOSI) - The Master line for sending data to the peripherals,

- Serial Clock (SCK) - The clock pulses which synchronize data transmission generated by the master, and

- Slave Select pin - the pin on each device that the master can use to enable and disable specific devices. When a device's Slave Select pin is low, it communicates with the master. When it's high, it ignores the master. This allows you to have multiple SPI devices sharing the same MISO, MOSI, and CLK lines.

To write code for a new SPI device you need to note a few things:

- Is data shifted in Most Significant Bit (MSB) or Least Significant Bit (LSB) first? This is controlled by the SPI.setBitOrder() function.

- Is the data clock idle when high or low?

191

Page 193: Arduino Language Reference

- Are samples on the rising or falling edge of clock pulses? This and the clock idling are controlled by the SPI.setDataMode() function

- What speed is the SPI running at? This is controlled by the SPI.setClockDivider() function.

The SPI standard is loose and each device implements it a little differently. This means you have to pay special attention to the device's datasheet when writing your code. Generally speaking, there are three modes of transmission. These modes control whether data is shifted in and out on the rising or falling edge of the data clock signal (called the clock phase, and whether the clock is idle when high or low (called the clock polarity). The three modes combine polarity and phase. The SPI.setDataMode() function lets you set the mode to control clock polarity and phase according to this table:

Mode Clock Polarity (CPOL) Clock Phase (CPHA)

0 0 0

1 0 1

2 1 0

3 1 1Once you have your SPI parameters set correctly you just need to figure which registers in your device control which functions, and you're good to go. This will be explained in the data sheet for your device.

Connections

On the Arduino Duemilanove and other ATmega168 / 328-based boards, the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK). On the Arduino Mega, this is 50 (MISO), 51 (MOSI), 52 (SCK), and 53 (SS). MISO, MOSI, and SCK are also available in a consistent physical location on the ICSP header; this is useful, for example, in designing a shield that works on the Uno and the Mega.

Note that even if you're not using the SS pin, it must remain set as an output; otherwise, the SPI interface can be put into slave mode, rendering the library inoperative. It is, however, possible to use a pin other than pin 10 as the slave select (SS) pin. For example, the Arduino Ethernet shield uses pin 4 to control the SPI connection to the on-board SD card, and pin 10 to control the connection to the Ethernet controller.

Functions

- begin()- end()- setBitOrder()- setClockDivider()- setDataMode()- transfer()

192

Page 194: Arduino Language Reference

Examples

/*SCP1000 Barometric Pressure Sensor Display Shows the output of a Barometric Pressure Sensor on a Uses the SPI library. For details on the sensor, see: http://www.sparkfun.com/commerce/product_info.php?products_id=8161 http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ Circuit:

SCP1000 sensor attached to pins 6, 7, 10 - 13:DRDY: pin 6CSB: pin 7MOSI: pin 11MISO: pin 12SCK: pin 13 */

// the sensor communicates using SPI, so include the library:#include <SPI.h>

//Sensor's memory register addresses:const int PRESSURE = 0x1F; //3 most significant bits of pressureconst int PRESSURE_LSB = 0x20; //16 least significant bits of pressureconst int TEMPERATURE = 0x21; //16 bit temperature readingconst byte READ = 0b11111100; // SCP1000's read command

193

Page 195: Arduino Language Reference

const byte WRITE = 0b00000010; // SCP1000's write command

// pins used for the connection with the sensor// the other you need are controlled by the SPI library):const int dataReadyPin = 6;const int chipSelectPin = 7;

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

// start the SPI library: SPI.begin();

// initalize the data ready and chip select pins: pinMode(dataReadyPin, INPUT); pinMode(chipSelectPin, OUTPUT);

//Configure SCP1000 for low noise configuration: writeRegister(0x02, 0x2D); writeRegister(0x01, 0x03); writeRegister(0x03, 0x02); // give the sensor time to set up: delay(100);}

void loop() { //Select High Resolution Mode writeRegister(0x03, 0x0A);

// don't do anything until the data ready pin is high: if (digitalRead(dataReadyPin) == HIGH) { //Read the temperature data int tempData = readRegister(0x21, 2);

// convert the temperature to celsius and display it: float realTemp = (float)tempData / 20.0; Serial.print("Temp[C]="); Serial.print(realTemp);

//Read the pressure data highest 3 bits: byte pressure_data_high = readRegister(0x1F, 1); pressure_data_high &= 0b00000111; //you only needs bits 2 to 0

//Read the pressure data lower 16 bits: unsigned int pressure_data_low = readRegister(0x20, 2); //combine the two parts into one 19-bit number: long pressure = ((pressure_data_high << 16) | pressure_data_low)/4;

// display the temperature: Serial.println("\tPressure [Pa]=" + String(pressure)); }

194

Page 196: Arduino Language Reference

}

//Read from or write to register from the SCP1000:unsigned int readRegister(byte thisRegister, int bytesToRead ) { byte inByte = 0; // incoming byte from the SPI unsigned int result = 0; // result to return Serial.print(thisRegister, BIN); Serial.print("\t"); // SCP1000 expects the register name in the upper 6 bits // of the byte. So shift the bits left by two bits: thisRegister = thisRegister << 2; // now combine the address and the command into one byte byte dataToSend = thisRegister & READ; Serial.println(thisRegister, BIN); // take the chip select low to select the device: digitalWrite(chipSelectPin, LOW); // send the device the register you want to read: SPI.transfer(dataToSend); // send a value of 0 to read the first byte returned: result = SPI.transfer(0x00); // decrement the number of bytes left to read: bytesToRead--; // if you still have another byte to read: if (bytesToRead > 0) { // shift the first byte left, then get the second byte: result = result << 8; inByte = SPI.transfer(0x00); // combine the byte you just got with the previous one: result = result | inByte; // decrement the number of bytes left to read: bytesToRead--; } // take the chip select high to de-select: digitalWrite(chipSelectPin, HIGH); // return the result: return(result);}

//Sends a write command to SCP1000

void writeRegister(byte thisRegister, byte thisValue) {

// SCP1000 expects register address in the upper 6 bits of the byte. So shift the bits left by two bits: thisRegister = thisRegister << 2; // now combine the register address and the command into one byte: byte dataToSend = thisRegister | WRITE;

// take the chip select low to select the device: digitalWrite(chipSelectPin, LOW);

SPI.transfer(dataToSend); //Send register location SPI.transfer(thisValue); //Send value to record into register

195

Page 197: Arduino Language Reference

// take the chip select high to de-select: digitalWrite(chipSelectPin, HIGH);}

/*Digital Potentiometer Control This example controls an Analog Devices AD5206 digital potentiometer. The AD5206 has 6 potentiometer channels. Each channel's pins are labeled A - connect this to voltageW - this is the pot's wiper, which changes when you set itB - connect this to ground. The AD5206 is SPI-compatible,and to command it, you send two bytes, one with the channel number (0 - 5) and one with the resistance value for the channel (0 - 255). The circuit: * All A pins of AD5206 connected to +5V * All B pins of AD5206 connected to ground * An LED and a 220-ohm resisor in series connected from each W pin to ground * CS - to digital pin 10 (SS pin) * SDI - to digital pin 11 (MOSI pin) * CLK - to digital pin 13 (SCK pin)*/

// inslude the SPI library:#include <SPI.h>

// set pin 10 as the slave select for the digital pot:const int slaveSelectPin = 10;

196

Page 198: Arduino Language Reference

void setup() { // set the slaveSelectPin as an output: pinMode (slaveSelectPin, OUTPUT); // initialize SPI: SPI.begin(); }

void loop() { // go through the six channels of the digital pot: for (int channel = 0; channel < 6; channel++) { // change the resistance on this channel from min to max: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, level); delay(10); } // wait a second at the top: delay(100); // change the resistance on this channel from max to min: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, 255 - level); delay(10); } }}

int digitalPotWrite(int address, int value) { // take the SS pin low to select the chip: digitalWrite(slaveSelectPin,LOW); // send in the address and value via SPI: SPI.transfer(address); SPI.transfer(value); // take the SS pin high to de-select the chip: digitalWrite(slaveSelectPin,HIGH); }

SPI

begin()Initializes the SPI bus, setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low and SS high.

Syntax: SPI.begin()Parameters: NoneReturns: None

SPI

end()

Disables the SPI bus (leaving pin modes unchanged).

197

Page 199: Arduino Language Reference

Syntax: SPI.end()Parameters: NoneReturns: None

SPI

setBitOrder()

Sets the order of the bits shifted out of and into the SPI bus, either LSBFIRST (least-significant bit first) or MSBFIRST (most-significant bit first).

Syntax: SPI.setBitOrder(order)Parameters: order: either LSBFIRST or MSBFIRSTReturns: None

SPI

setClockDivider()

Sets the SPI clock divider relative to the system clock. The dividers available are 2, 4, 8, 16, 32, 64, or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter the frequency of the system clock.

Syntax: SPI.setClockDivider(divider)Parameters: divider:

- SPI_CLOCK_DIV2- SPI_CLOCK_DIV4- SPI_CLOCK_DIV8- SPI_CLOCK_DIV16- SPI_CLOCK_DIV32- SPI_CLOCK_DIV64 or- SPI_CLOCK_DIV128

Returns: None

SPI

setDataMode()

Sets the SPI data mode: that is, clock polarity and phase. See the Wikipedia article on SPI for details.

Syntax: SPI.setDataMode(mode)

Parameters: mode: SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3

Returns: None

198

Page 200: Arduino Language Reference

SPI

transfer()

Transfers one byte over the SPI bus, both sending and receiving.

Syntax: SPI.transfer(val)

Parameters: val: the byte to send out over the bus

Returns: the byte read from the bus

sq(x)

Calculates the square of a number: the number multiplied by itself.

Parameters: x: the number, any data typeReturns: the square of the number

sqrt(x)

Calculates the square root of a number.

Parameters: x: the number, any data type

Returns double, the number's square root.

static

The static keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls.

Variables declared as static will only be created and initialized the first time a function is called.

Example

* RandomWalk wanders up and down randomly between two endpoints. The maximum move in * one loop is governed by the parameter "stepsize".* A static variable is moved up and down a random amount.* This technique is also known as "pink noise" and "drunken walk".*/

#define randomWalkLowRange -20#define randomWalkHighRange 20int stepsize;

int thisTime;

199

Page 201: Arduino Language Reference

int total;

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

void loop(){ // tetst randomWalk function stepsize = 5; thisTime = randomWalk(stepsize); Serial.println(thisTime); delay(10);}

int randomWalk(int moveSize){ static int place; // variable to store value in random walk - declared static so that it stores // values in between function calls, but no other functions can change its value

place = place + (random(-moveSize, moveSize + 1));

if (place < randomWalkLowRange){ // check lower and upper limits place = place + (randomWalkLowRange - place); // reflect number back in positive direction } else if(place > randomWalkHighRange){ place = place - (place - randomWalkHighRange); // reflect number back in negative direction }

return place;}

Stepper library

Circuit for Unipolar Stepper Motor - Two Pins

200

Page 202: Arduino Language Reference

Circuit for Unipolar Stepper Motor - Four Pins

201

Page 203: Arduino Language Reference

Circuit for Bipolar Stepper Motor - Two Pins

Circuit for Bipolar Stepper Motor - Four Pins

202

Page 204: Arduino Language Reference

Stepper(steps, pin1, pin2)

Stepper(steps, pin1, pin2, pin3, pin4)

This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board. Use it at the top of your sketch, above setup() and loop(). The number of parameters depends on how you've wired your motor - either using two or four pins of the Arduino board.

Parameters steps: the number of steps in one revolution of your motor. If your motor gives the number of degrees per step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps). (int)pin1, pin2: two pins that are attached to the motor (int)pin3, pin4: optional the last two pins attached to the motor, if it's connected to four pins (int)

Returns: A new instance of the Stepper motor class.

Example

Stepper myStepper = Stepper(100, 5, 6);

stepper.setSpeed(rpms)

Sets the motor speed in rotations per minute (RPMs). This function doesn't make the motor turn, just sets the speed at which it will when you call step().

Parameters: rpms: the speed at which the motor should turn in rotations per minute - a positive number (long)

Returns: None

stepper.step(steps)

Turns the motor a specific number of steps, at a speed determined by the most recent call to setSpeed(). This function is blocking; that is, it will wait until the motor has finished moving to pass control to the next line in your sketch. For example, if you set the speed to, say, 1 RPM and called step(100) on a 100-step motor, this function would take a full minute to run. For better control, keep the speed high and only go a few steps with each call to step().

Parameters: steps: the number of steps to turn the motor - positive to turn one direction, negative to turn the other (int)

Returns: None

stepper example

/* * MotorKnob

203

Page 205: Arduino Language Reference

* * A stepper motor follows the turns of a potentiometer (or other sensor) on analog input 0. * * http://www.arduino.cc/en/Reference/Stepper. This example code is in the public domain. */

#include <Stepper.h>

// change this to the number of steps on your motor#define STEPS 100

// create an instance of the stepper class, specifying the number of steps of the motor and the pins // it's attached to

Stepper stepper(STEPS, 8, 9, 10, 11);

// the previous reading from the analog inputint previous = 0;

void setup(){ // set the speed of the motor to 30 RPMs stepper.setSpeed(30);}

void loop(){ // get the sensor value int val = analogRead(0);

// move a number of steps equal to the change in the sensor reading stepper.step(val - previous);

// remember the previous value of the sensor previous = val;}

stream

Stream is the base class for character and binary based streams. It is not called directly, but invoked whenever you use a function that relies on it.

Stream defines the reading functions in Arduino. When using any core functionality that uses a read() or similar method, you can safely assume it calls on the Stream class. For functions like print(), Stream inherits from the Print class.

Some of the libraries that rely on Stream include :

- Serial - Wire - Ethernet Client

204

Page 206: Arduino Language Reference

- Ethernet Server - SD

Functions

- available() - read() - flush() - find() - findUntil() - peek() - readBytes() - readBytesUntil() - parseInt() - parsefloat() - setTimeout()

stream.available()

available() gets the number of bytes available in the stream. This is only for bytes that have already arrived.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.available()

Parameters: stream : an instance of a class that inherits from Stream.

Returns: int : the number of bytes available to read

stream.find()

find() reads data from the stream until the target string of given length is found The function returns true if target string is found, false if timed out.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.find(target)

Parameters: stream : an instance of a class that inherits from Stream. target : the string to search for (char)

Returns: boolean

stream.findUntil()

findUntil() reads data from the stream until the target string of given length or terminator string is

205

Page 207: Arduino Language Reference

found. The function returns true if target string is found, false if timed out

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.findUntil(target, terminal)

Parameters: stream : an instance of a class that inherits from Stream. target : the string to search for (char) terminal : the terminal string in the search (char)

Returns: boolean

stream.flush()

flush() clears the buffer once all outgoing characters have been sent.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.flush()

Parameters: stream : an instance of a class that inherits from Stream.

Returns: boolean

stream.parseFloat()

parseFloat() returns the first valid floating point number from the current position. Initial characters that are not digits (or the minus sign) are skipped. parseFloat() is terminated by the first character that is not a floating point number.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.parseFloat(list)

Parameters: stream : an instance of a class that inherits from Stream. list : the stream to check for floats (char)

Returns: float

stream.parseInt()

parseInt() returns the first valid (long) integer number from the current position. Initial characters that are not integers (or the minus sign) are skipped. parseInt() is terminated by the first character that is not a digit.

This function is part of the Stream class, and is called by any class that inherits from it (Wire,

206

Page 208: Arduino Language Reference

Serial, etc). See the Stream class main page for more information.

Syntax: stream.parseInt(list)

Parameters: stream : an instance of a class that inherits from Stream. list : the stream to check for ints (char)

Returns: int

stream.peek()

Read a byte from the file without advancing to the next one. That is, successive calls to peek() will return the same value, as will the next call to read().

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.peek()

Parameters: stream : an instance of a class that inherits from Stream.

Returns: The next byte (or character), or -1 if none is available.

stream.readBytes()

readBytes() read characters from a stream into a buffer. The function terminates if the determined length has been read, or it times out (see setTimeout()).

readBytes() returns the number of characters placed in the buffer. A 0 means no valid data was found.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.readBytes(buffer, length)

Parameters: stream : an instance of a class that inherits from Stream. buffer: the buffer to store the bytes in (char[] or byte[]) length : the number of bytes to read (int)

Returns: byte

stream.readBytesUntil()

readBytesUntil() read characters from a stream into a buffer. The function terminates if the terminator character is detected, the determined length has been read, or it times out (see setTimeout()). readBytesUntil() returns the number of characters placed in the buffer. A 0 means no valid data was found.

207

Page 209: Arduino Language Reference

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.readBytesUntil(character, buffer, length)

Parameters: stream : an instance of a class that inherits from Stream. character : the character to search for (char) buffer: the buffer to store the bytes in (char[] or byte[]) length : the number of bytes

to read (int)

Returns: byte

stream.read()

read() reads characters from an incoming stream to the buffer.

This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.read()

Parameters: stream : an instance of a class that inherits from Stream.

Returns: the first byte of incoming data available (or -1 if no data is available)

stream.setTimeout()

setTimeout() sets the maximum milliseconds to wait for stream data, it defaults to 1000 milliseconds. This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax: stream.setTimeout(time)

Parameters: stream : an instance of a class that inherits from Stream. time : timeout duration in milliseconds (long).

Returns: None

string

Text strings can be represented in two ways. you can use the String data type, which is part of the core as of version 0019, or you can make a string out of an array of type char and null-terminate it. This page described the latter method. For more details on the String object, which gives you more functionality at the cost of more memory, see the String object page.

Examples

All of the following are valid declarations for strings.

208

Page 210: Arduino Language Reference

char Str1[15]; char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'}; char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'}; char Str4[ ] = "arduino"; char Str5[8] = "arduino"; char Str6[15] = "arduino";

Possibilities for declaring strings

@ Declare an array of chars without initializing it as in Str1@ Declare an array of chars (with one extra char) and the compiler will add the required null

character, as in Str2@ Explicitly add the null character, Str3@ Initialize with a string constant in quotation marks; the compiler will size the array to fit the

string constant and a terminating null character, Str4@ Initialize the array with an explicit size and string constant, Str5@ Initialize the array, leaving extra space for a larger string, Str6

Null termination

Generally, strings are terminated with a null character (ASCII code 0). This allows functions (like Serial.print()) to tell where the end of a string is. Otherwise, they would continue reading subsequent bytes of memory that aren't actually part of the string.

This means that your string needs to have space for one more character than the text you want it to contain. That is why Str2 and Str5 need to be eight characters, even though "arduino" is only seven - the last position is automatically filled with a null character. Str4 will be automatically sized to eight characters, one for the extra null. In Str3, we've explicitly included the null character (written '\0') ourselves.

Note that it's possible to have a string without a final null character (e.g. if you had specified the length of Str2 as seven instead of eight). This will break most functions that use strings, so you shouldn't do it intentionally. If you notice something behaving strangely (operating on characters not in the string), however, this could be the problem.

Single quotes or double quotes?

Strings are always defined inside double quotes ("Abc") and characters are always defined inside single quotes('A').

Wrapping long strings. You can wrap long strings like this:

char myString[] = "This is the first line"" this is the second line"" etcetera";

Arrays of strings

It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is in actually an example of a two-dimensional array.

209

Page 211: Arduino Language Reference

In the code below, the asterisk after the datatype char "char*" indicates that this is an array of "pointers". All array names are actually pointers, so this is required to make an array of arrays. Pointers are one of the more esoteric parts of C for beginners to understand, but it isn't necessary to understand pointers in detail to use them effectively here.

Example

char* myStrings[]={"This is string 1", "This is string 2", "This is string 3","This is string 4", "This is string 5","This is string 6"};

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

void loop(){for (int i = 0; i < 6; i++){ Serial.println(myStrings[i]); delay(500); }}

String class

The String class, part of the core as of version 0019, allows you to use and manipulate strings of text in more complex ways than character arrays do. You can concatenate Strings, append to them, search for and replace substrings, and more. It takes more memory than a simple character array, but it is also more useful.

For reference, character arrays are referred to as strings with a small s, and instances of the String class are referred to as Strings with a capital S. Note that constant strings, specified in "double quotes" are treated as char arrays, not instances of the String class.

Functions

@ String() @ charAt() @ compareTo() @ concat() @ endsWith() @ equals() @ equalsIgnoreCase() @ getBytes() @ indexOf() @ lastIndexOf() @ length() @ replace() @ setCharAt() @ startsWith() @ substring()

210

Page 212: Arduino Language Reference

@ toCharArray() @ toLowerCase() @ toUpperCase() @ trim()

Operators

@ [] (element access) @ + (concatenation) @ == (comparison)

Examples

@ StringConstructors

String stringOne = "Hello String"; // using a constant StringString stringOne = String('a'); // converting a constant char into a StringString stringTwo = String("This is a string"); // converting a constant string into a String objectString stringOne = String(stringTwo + " with more");// concatenating two stringsString stringOne = String(13); // using a constant integerString stringOne = String(analogRead(0), DEC); // using an int and a baseString stringOne = String(45, HEX); // using an int and a base (hexadecimal)String stringOne = String(255, BIN); // using an int and a base (binary)String stringOne = String(millis(), DEC); // using a long and a base

@ StringAdditionOperator

You can add Strings together in a variety of ways. This is called concatenation and it results in the original String being longer by the length of the String or character array with which you concatenate it. The + operator allows you to combine a String with another String, with a constant character array, an ASCII representation of a constant or variable number, or a constant character.

// adding a constant integer to a string: stringThree = stringOne + 123;

// adding a constant long interger to a string: stringThree = stringOne + 123456789;

// adding a constant character to a string: stringThree = stringOne + 'A';

// adding a constant string to a string: stringThree = stringOne + "abc";

// adding two Strings together: stringThree = stringOne + stringTwo;

You can also use the + operator to add the results of a function to a String, if the function returns one of the allowed data types mentioned above. For example,

stringThree = stringOne + millis();

211

Page 213: Arduino Language Reference

This is allowable since the millis() function returns a long integer, which can be added to a String. You could also do this:

stringThree = stringOne + analogRead(A0);

because analogRead() returns an integer. String concatenation can be very useful when you need to display a combination of values and the descriptions of those values into one String to display via serial communication, on an LCD display, over an Ethernet connection, or anywhere that Strings are useful.

Caution: You should be careful about concatenating multiple variable types on the same line, as you may get unexpected results. For Example

int sensorValue = analogRead(A0); String stringOne = "Sensor value: "; String stringThree = stringOne + sensorValue; Serial.println(stringThree);

results in "Sensor Value: 402" or whatever the analogRead() result is, but

int sensorValue = analogRead(A0); String stringThree = "Sensor value: " + sensorValue; Serial.println(stringThree);

gives unpredictable results because stringThree never got an initial value before you started concatenating different data types. Here's another example where improper initialization will cause errors:

Serial.println("I want " + analogRead(A0) + " donuts");

This won't compile because the compiler doesn't handle the operator precedence correctly. On the other hand, the following will compile, but it won't run as expected:

int sensorValue = analogRead(A0); String stringThree = "I want " + sensorValue; Serial.println(stringThree + " donuts");

It doesn't run correctly for the same reason as before: stringThree never got an initial value before you started concatenating different data types. For best results, initialize your Strings before you concatenate them.

@ StringIndexOf String indexOf() and lastIndexOf()Method

The String object indexOf() method gives you the ability to search for the first instance of a particular character value in a String. You can also look for the first instance of the character after a given offset. The lastIndexOf() method lets you do the same things from the end of a String.

String stringOne = "<HTML><HEAD><BODY>"; int firstClosingBracket = stringOne.indexOf('>');

212

Page 214: Arduino Language Reference

In this case, firstClosingBracket equals 5, because the first > character is at position 5 in the String (counting the first character as 0). If you want to get the second closing bracket, you can use the fact that you know the position of the first one, and search from firstClosingBracket + 1 as the offset, like so:

stringOne = "<HTML><HEAD><BODY>"; int secondClosingBracket = stringOne.indexOf('>', firstClosingBracket + 1 );

The result would be 11, the position of the closing bracket for the HEAD tag. If you want to search from the end of the String, you can use the lastIndexOf() method instead. This function returns the position of the last occurrence of a given character.

stringOne = "<HTML><HEAD><BODY>"; int lastOpeningBracket = stringOne.lastIndexOf('<');

In this case, lastOpeningBracket equals 12, the position of the < for the BODY tag. If you want the opening bracket for the HEAD tag, it would be at stringOne.lastIndexOf('<', lastOpeningBracket -1), or 6.

@ StringAppendOperator

Just as you can concatenate Strings with other data objects using the StringAdditionOperator, you can also use the += operator and the cconcat() method to append things to Strings. The += operator and the concat() method work the same way, it's just a matter of which style you prefer. The two examples below illustrate both, and result in the same String:

String stringOne = "A long integer: ";

// using += to add a long variable to a string: stringOne += 123456789;

or

String stringOne = "A long integer: ";

// using concat() to add a long variable to a string: stringTwo.concat(123456789);

In both cases, stringOne equals "A long integer: 123456789". Like the + operator, these operators are handy for assembling longer strings from a combination of data objects.

@ StringLengthTrim

length() returns the length of a String. There are many occasions when you need this. For example,if you wanted to make sure a String was less than 140 characters, to fit it in a text message, you could do this:

/*String length() Examples of how to use length() in a String. Open the Serial Monitor and start sending characters to

213

Page 215: Arduino Language Reference

see the results.*/

String txtMsg = ""; // a string for incoming textint lastStringLength = txtMsg.length(); // previous length of the String

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

// send an intro: Serial.println("\n\nString length():"); Serial.ptintln();}

void loop() { // add any incoming characters to the String: while (Serial.available() > 0) { char inChar = Serial.read(); txtMsg += inChar; }

// print the message and a notice if it's changed: if (txtMsg.length() != lastStringLength) { Serial.println(txtMsg); Serial.println(txtMsg.length()); // if the String's longer than 140 characters, complain: if (txtMsg.length() < 140) { Serial.println("That's a perfectly acceptable text message"); } else { Serial.println("That's too long for a text message."); } // note the length for next time through the loop: lastStringLength = txtMsg.length(); }}

trim() is useful for when you know there are extraneous whitespace characters on the beginning or the end of a String and you want to get rid of them. Whitespace refers to characters that take space but aren't seen. It includes the single space (ASCII 32), tab (ASCII 9), vertical tab (ASCII 11), form feed (ASCII 12), carriage return (ASCII 13), or newline (ASCII 10). The example below shows a String with whitespace, before and after trimming:

/* String length() and trim() Examples of how to use length() and trim() in a String*/

214

Page 216: Arduino Language Reference

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

// send an intro: Serial.println("\n\nString length() and trim():"); Serial.println();}

void loop() { // here's a String with empty spaces at the end (called white space): String stringOne = "Hello! "; Serial.print(stringOne); Serial.print("<--- end of string. Length: "); Serial.println(stringOne.length());

// trim the white space off the string: stringOne.trim(); Serial.print(stringOne); Serial.print("<--- end of trimmed string. Length: "); Serial.println(stringOne.length());

// do nothing while true: while(true);}

@ StringCaseChanges

/*String Case changesExamples of how to change the case of a string */

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

// send an intro: Serial.println("\n\nString case changes:"); Serial.println();}

void loop() { // toUpperCase() changes all letters to upper case: String stringOne = "<html><head><body>";

215

Page 217: Arduino Language Reference

Serial.println(stringOne); stringOne.toUpperCase(); Serial.println(stringOne);

// toLowerCase() changes all letters to lower case: String stringTwo = "</BODY></HTML>"; Serial.println(stringTwo); stringTwo.toLowerCase(); Serial.println(stringTwo);

// do nothing while true: while(true);}

@ StringReplace

Caution: If you try to replace a substring that's more than the whole string itself, nothing will be replaced. For Example

String stringOne = "<html><head><body>"; String stringTwo = stringOne.replace("<html><head></head><body></body></html>", "Blah");

In this case, the code will compile, but stringOne will remain unchanged, since the replacement substring is more than the String itself.

/* String replace() Examples of how to replace characters or substrings of a string*/

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

// send an intro: Serial.println("\n\nString replace:\n"); Serial.println();}

void loop() { String stringOne = "<html><head><body>"; Serial.println(stringOne); // replace() changes all instances of one substring with another: // first, make a copy of th original string: String stringTwo = stringOne; // then perform the replacements: stringTwo.replace("<", "</"); // print the original: Serial.println("Original string: " + stringOne);

216

Page 218: Arduino Language Reference

// and print the modified string: Serial.println("Modified string: " + stringTwo);

// you can also use replace() on single characters: String normalString = "bookkeeper"; Serial.println("normal: " + normalString); String leetString = normalString; leetString.replace('o', '0'); leetString.replace('e', '3'); Serial.println("l33tspeak: " + leetString);

// do nothing while true: while(true);}

@ StringCharacters

/*String charAt() and setCharAt() Examples of how to get and set characters of a String*/

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

Serial.println("\n\nString charAt() and setCharAt():");}

void loop() { // make a string to report a sensor reading: String reportString = "SensorReading: 456"; Serial.println(reportString);

// the reading's most significant digit is at position 15 in the reportString: char mostSignificantDigit = reportString.charAt(15); Serial.println("Most significant digit of the sensor reading is: " + mostSignificantDigit);

// add blank space: Serial.println();

// you can alo set the character of a string. Change the : to a = character reportString.setCharAt(13, '='); Serial.println(reportString);

// do nothing while true: while(true);}

217

Page 219: Arduino Language Reference

@ StringStartsWithEndsWith

startsWith() and endsWith() can be used to look for a particular message header, or for a single character at the end of a String. They can also be used with an offset to look for a substring starting at a particular position. For Example

stringOne = "HTTP/1.1 200 OK"; if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); }

This is functionally the same as this:

stringOne = "HTTP/1.1 200 OK"; if (stringOne.substring(9) == "200 OK") { Serial.println("Got an OK from the server"); }

Caution: If you look for a position that's outside the range of the string,you'll get unpredictable results. For example, in the example above stringOne.startsWith("200 OK", 16) wouldn't check against the String itself, but whatever is in memory just beyond it. For best results, make sure the index values you use for startsWith and endsWith are between 0 and the String's length().

/* String startWith() and endsWith() Examples of how to use startsWith() and endsWith() in a String*/

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only }

// send an intro: Serial.println("\n\nString startsWith() and endsWith():"); Serial.println();}

void loop() { // startsWith() checks to see if a String starts with a particular substring: String stringOne = "HTTP/1.1 200 OK"; Serial.println(stringOne); if (stringOne.startsWith("HTTP/1.1")) { Serial.println("Server's using http version 1.1"); }

// you can also look for startsWith() at an offset position in the string: stringOne = "HTTP/1.1 200 OK";

218

Page 220: Arduino Language Reference

if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); }

// endsWith() checks to see if a String ends with a particular character: String sensorReading = "sensor = "; sensorReading += analogRead(A0); Serial.print (sensorReading); if (sensorReading.endsWith(0)) { Serial.println(". This reading is divisible by ten"); } else { Serial.println(". This reading is not divisible by ten");

}

// do nothing while true: while(true);}

@ StringComparisonOperators

startsWith() and endsWith() can be used to look for a particular message header, or for a single character at the end of a String. They can also be used with an offset to look for a substring starting at a particular position. For Example

stringOne = "HTTP/1.1 200 OK"; if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); }

This is functionally the same as this:

stringOne = "HTTP/1.1 200 OK"; if (stringOne.substring(9) == "200 OK") { Serial.println("Got an OK from the server"); }

Caution: If you look for a position that's outside the range of the string,you'll get unpredictable results. For example, in the example above stringOne.startsWith("200 OK", 16) wouldn't check against the String itself, but whatever is in memory just beyond it. For best results, make sure the index values you use for startsWith and endsWith are between 0 and the String's length(). /* String startWith() and endsWith() Examples of how to use startsWith() and endsWith() in a String*/

void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) {

219

Page 221: Arduino Language Reference

; // wait for serial port to connect. Needed for Leonardo only } // send an intro: Serial.println("\n\nString startsWith() and endsWith():"); Serial.println();}

void loop() { // startsWith() checks to see if a String starts with a particular substring: String stringOne = "HTTP/1.1 200 OK"; Serial.println(stringOne); if (stringOne.startsWith("HTTP/1.1")) { Serial.println("Server's using http version 1.1"); }

// you can also look for startsWith() at an offset position in the string: stringOne = "HTTP/1.1 200 OK"; if (stringOne.startsWith("200 OK", 9)) { Serial.println("Got an OK from the server"); }

// endsWith() checks to see if a String ends with a particular character: String sensorReading = "sensor = "; sensorReading += analogRead(A0); Serial.print (sensorReading); if (sensorReading.endsWith(0)) { Serial.println(". This reading is divisible by ten"); } else { Serial.println(". This reading is not divisible by ten"); }

// do nothing while true: while(true);}

@ StringSubstring

substring() with only one parameter looks for a given substring from the position given to the end of the string. It expects that the substring extends all the way to the end of the String. For Example

String stringOne = "Content-Type: text/html"; // substring(index) looks for the substring from the index position to the end: if (stringOne.substring(19) == "html") {} is true, while

String stringOne = "Content-Type: text/html"; // substring(index) looks for the substring from the index position to the end: if (stringOne.substring(19) == "htm") {}

220

Page 222: Arduino Language Reference

is not true, because there's an l after the htm in the String.

substring() with two parameters looks for a given substring from the first parameter to the second. For Example

String stringOne = "Content-Type: text/html";

// you can also look for a substring in the middle of a string: if (stringOne.substring(14,18) == "text") {}

String

[ ] (element access)

Allows you access to the individual characters of a string.

Syntax: char thisChar = string1[n]

Parameters: char thisChar - a character variable string1 - a string variable int n - a numeric variable

Returns: the nth char of the string. Same as charAt().

String

charAt()

Access a particular character of the String.

Syntax: string.charAt(n)

Parameters: string: a variable of type String n: the character to access

Returns: the n'th character of the String

String

compareTo()

Compares two Strings, testing whether one comes before or after the other, or whether they're equal. The strings are compared character by character, using the ASCII values of the characters. That means, for example, that 'a' comes before 'b' but after 'A'. Numbers come before letters.

Syntax: string.compareTo(string2)

221

Page 223: Arduino Language Reference

Parameters: string: a variable of type String string2: another variable of type String

Returns: a negative number: if string comes before string2 0: if string equals string2 a positive number: if string comes after string2

String

== operator

Compares two strings for equality. The comparison is case-sensitive, meaning the String "hello" is not equal to the String "HELLO". Functionally the same as string.equals()

Syntax: string1 == string2

Parameters: string1, string2: variables of type String

Returns: true: if string1 equals string2 false: otherwise

String

concat()

Combines, or concatenates two strings into one new String. The second string is appended to the first, and the result is placed in a new String

Syntax: string.concat(string, string2)

Parameters: string, string2: variables of type String

Returns: new String that is the combination of the original two Strings

222

Page 224: Arduino Language Reference

String

String()

Constructs an instance of the String class. There are multiple versions that construct Strings from different data types (i.e. format them as sequences of characters), including: @ a constant string of characters, in double quotes (i.e. a char array) @ a single constant character, in single quotes @ another instance of the String object @ a constant integer or long integer @ a constant integer or long integer, using a specified base @ an integer or long integer variable @ an integer or long integer variable, using a specified baseConstructing a String from a number results in a string that contains the ASCII representation of that number. The default is base ten, so

String thisString = String(13)

gives you the String "13". You can use other bases, however. For example,

String thisString = String(13, HEX)

gives you the String "D", which is the hexadecimal representation of the decimal value 13.Or if you prefer binary,

String thisString = String(13, BIN)

gives you the String "1011", which is the binary representation of 13.

Syntax: String(val) String(val, base)

Parameters: val: a variable to format as a String - string, char, byte, int, long, unsigned int, unsigned long base (optional) - the base in which to format an integral value

Returns: an instance of the String class

Examples

All of the following are valid declarations for Strings.

String stringOne = "Hello String"; // using a constant StringString stringOne = String('a'); // converting a constant char into a StringString stringTwo = String("This is a string"); // converting a constant string into a String objectString stringOne = String(stringTwo + "with more"); // concatenating two stringsString stringOne = String(13); // using a constant integerString stringOne = String(analogRead(0), DEC); // using an int and a baseString stringOne = String(45, HEX); // using an int and a base (hexadecimal)String stringOne = String(255, BIN); // using an int and a base (binary)String stringOne = String(millis(), DEC); // using a long and a base

223

Page 225: Arduino Language Reference

String

endsWith()

Tests whether or not a String ends with the characters of another String.

Syntax: string.endsWith(string2)

Parameters: string: a variable of type String string2: another variable of type String

Returns: true: if string ends with the characters of string2 false: otherwise

String

equals()

Compares two strings for equality. The comparison is case-sensitive, meaning the String "hello" is not equal to the String "HELLO".

Syntax: string.equals(string2)

Parameters: string, string2: variables of type String

Returns: true: if string equals string2 false: otherwise

String

equalsIgnoreCase()

Compares two strings for equality. The comparison is not case-sensitive, meaning the String("hello") is equal to the String("HELLO").

Syntax: string.equalsIgnoreCase(string2)

Parameters: string, string2: variables of type String

Returns: true: if string equals string2 (ignoring case) false: otherwise

String

getBytes()

Copies the string's characters to the supplied buffer.

Syntax: string.getBytes(buf, len)

224

Page 226: Arduino Language Reference

Parameters: string: a variable of type Stringbuf: the buffer to copy the characters into (byte [])len: the size of the buffer (unsigned int)

Returns: None

String

indexOf()

Locates a character or String within another String. By default, searches from the beginning of the String, but can also start from a given index, allowing for the locating of all instances of the character or String.

Syntax: string.indexOf(val) string.indexOf(val, from)

Parameters: string: a variable of type String val: the value to search for - char or String from: the index to start the search from

Returns: The index of val within the String, or -1 if not found.

String

lastIndexOf()

Locates a character or String within another String. By default, searches from the end of the String, but can also work backwards from a given index, allowing for the locating of all instances of the character or String.

Syntax: string.lastIndexOf(val) string.lastIndexOf(val, from)

Parameters: string: a variable of type String val: the value to search for - char or String from: the index to work backwards from

Returns: The index of val within the String, or -1 if not found.

String

length()

Returns the length of the String, in characters. (Note that this doesn't include a trailing null character.)

Syntax: string.length()

225

Page 227: Arduino Language Reference

Parameters: string: a variable of type String

Returns: The length of the String in characters.

String

+ operator

Combines, or concatenates two strings into one new String. The second string is appended to the first, and the result is placed in a new String. Works the same as string.concat().

Syntax: string3 = string1 + string 2; string3 += string2;

Parameters: string, string2, string3: variables of type String

Returns: new String that is the combination of the original two Strings

String

replace()

The String replace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a string with a different substring.

Syntax: string.replace(substring1, substring2)

Parameters: string: a variable of type String substring1: another variable of type String substring2: another variable of type String

Returns: another String containing the new string with replaced characters.

String

setCharAt()

Sets a character of the String. Has no effect on indices outside the existing length of the String.

Syntax: string.setCharAt(index, c)

Parameters: string: a variable of type String index: the index to set the character at c: the character to store to the given location

Returns: None

226

Page 228: Arduino Language Reference

String

startsWith()

Tests whether or not a String starts with the characters of another String.

Syntax: string.startsWith(string2)

Parameters: string, string2: variable2 of type String

Returns: true: if string starts with the characters of string2 false: otherwise

String

substring()

Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.

Syntax string.substring(from) string.substring(from, to)

Parameters: string: a variable of type String from: the index to start the substring at to (optional): the index to end the substring before

Returns: the substring

String

toCharArray()

Copies the string's characters to the supplied buffer.

Syntax: string.toCharArray(buf, len)

Parameters: string: a variable of type Stringbuf: the buffer to copy the characters into (char [])len: the size of the buffer (unsigned int)

Returns: None

227

Page 229: Arduino Language Reference

String

toLowerCase()

Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the string in place rather than returning a new one.

Syntax: string.toLowerCase()

Parameters: string: a variable of type String

Returns: none

String

toUpperCase()

Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the string in place rather than returning a new one.

Syntax: string.toUpperCase()

Parameters: string: a variable of type String

Returns: none

String

trim()

Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the string in place rather than returning a new one.

Syntax: string.trim()

Parameters: string: a variable of type String

Returns: none

228

Page 230: Arduino Language Reference

switch / case statements

Like if statements, switch...case controls the flow of programs by allowing programmers to specify different code that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.

The break keyword exits the switch statement, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.

Example

switch (var) { case 1: //do something when var equals 1 break; case 2: //do something when var equals 2 break; default: // if nothing else matches, do the default // default is optional}

Syntax switch (var) { case label: // statements break; case label: // statements break; default: // statements

}

Parameters: var: the variable whose value to compare to the various caseslabel: a value to compare the variable to

tan(rad)

Calculates the tangent of an angle (in radians). The result will be between negative infinity and infinity.

Parameters: rad: the angle in radians (float)

Returns: The tangent of the angle (double)

229

Page 231: Arduino Language Reference

Time library

The Time library adds timekeeping functionality to Arduino with or without external timekeeping hardware. It allows a sketch to get the time and date as: second, minute, hour, day, month and year. It also provides time as a standard C time_t so elapsed times can be easily calculated and time values shared across different platforms.

The code is derived from the earlier Playground DateTime library but is updated to provide an API that is more flexible and easier to use.

The download includes example sketches illustrating how similar sketch code can be used with: a Real Time Clock,Internet NTP time service, GPS time data, DCF77 radio signal, and Serial time messages from a computer. To use all of the features in the library, you'll need the UDPbitewise library

Functional Overview

hour(); // the hour now (0-23)minute(); // the minute now (0-59)second(); // the second now (0-59)day(); // the day now (1-31)weekday(); // day of the week, Sunday is day 1month(); // the month now (1-12)year(); // the full four digit year: (2009, 2010 etc)hourFormat12(); // the hour now in 12 hour formatisAM(); // returns true if time now is AM isPM(); // returns true if time now is PMnow(); // returns the current time as seconds since Jan 1 1970

The time and date functions can take an optional parameter for the time. This prevents errors if the time rolls over between elements. For example, if a new minute begins between getting the minute and second, the values will be inconsistent. Using the following functions eliminates this problem

time_t t = now(); // store the current time in time variable t hour(t); // returns the hour for the given time tminute(t); // returns the minute for the given time tsecond(t); // returns the second for the given time t day(t); // the day for the given time t weekday(t); // day of the week for the given time t month(t); // the month for the given time t year(t); // the year for the given time t

Functions for managing the timer services are: setTime(t); // set the system time to the give time tsetTime(hr,min,sec,day,month,yr); // another way to set the time

adjustTime(adjustment); // adjust system time by adding the adjustment valuetimeStatus(); // indicates if time has been set and recently

// synchronized. Returns one of the following:timeNotSet // the time has never been set, the clock started at Jan 1 1970

timeNeedsSync // the time had been set but a sync attempt did not succeedtimeSet // the time is set and is synced

230

Page 232: Arduino Language Reference

Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but the returned time may have drifted if the status is timeNeedsSync.

setSyncProvider(getTimeFunction); // set the external time provider setSyncInterval(interval); // set the number of seconds between re-sync

Strings for days and months are supported in the library, see the TimeSerialDateString.pde example in the download

There are many convenience macros in the time.h file for time constants and conversion of time units.

Using the Library Copy the download to the Library directory. The Time directory contains the Time library and some example sketches illustrating how the library can be used with various time sources:

- TimeSerial.pde shows Arduino as a clock without external hardware. It is synchronized by time messages sent over the serial port. A companion Processing sketch will automatically provide these messages if it is running and connected to the Arduino serial port.

- TimeRTC uses a DS1307 real time clock to provide time synchronization. A basic RTC library named DS1307RTC is included in the download. To run this sketch the DS1307RTC library must be installed.

- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service.

- TimeGPS gets time from a GPS.

Example

The test sketch uses a message on the serial port to set the time. A Processing sketch that sends these messsages is included in the download but you can test this sketch by sending T1262347200 using the serial monitor (this sets the time to noon on Jan 1 2010). On a unix system, you can set the time with the shell command:

TZ_adjust=-8; echo T$(($(date +%s)+60*60*$TZ_adjust)) > /dev/tty.usbserial-A8008pym

Adjust the TZ_adjust value to your timezone and the serial port to your Arduino.

#include <Time.h>

#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by Unix time_t as ten ASCII digits#define TIME_HEADER 'T' // Header tag for serial time sync message#define TIME_REQUEST 7 // ASCII bell character requests a time sync message

// T1262347200 //noon Jan 1 2010

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

231

Page 233: Arduino Language Reference

void loop(){ if(Serial.available() ) { processSyncMessage(); } if(timeStatus() == timeNotSet) Serial.println("waiting for sync message"); else digitalClockDisplay(); delay(1000);}

void digitalClockDisplay(){ // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); }

void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits);}

void processSyncMessage() { // if time sync available from serial port, update time and return true while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of header & 10 ASCII digits char c = Serial.read() ; Serial.print(c); if( c == TIME_HEADER ) { time_t pctime = 0; for(int i=0; i < TIME_MSG_LEN -1; i++){ c = Serial.read(); if( c >= '0' && c <= '9'){ pctime = (10 * pctime) + (c - '0') ; // convert digits to a number } } setTime(pctime); // Sync Arduino clock to the time received on the serial port } }}

232

Page 234: Arduino Language Reference

Here is a fragment from the TimeNTP.pde example sketch showing how the syncProvider functionality simplifies the sketch code. This sketch gets time from an Internet time provider (NTP) using the Arduino Ethernet shield. Note that the loop code does not require any logic to maintain time sync. The Time library will automatically monitor NTP and sync the time as necessary.

void setup() { Serial.begin(9600); Ethernet.begin(mac,ip,gateway); Serial.println("waiting for sync"); setSyncProvider(getNtpTime); while(timeStatus()== timeNotSet) ; // wait until the time is set by the sync provider}

void loop(){ if( now() != prevDisplay) //update the display only if the time has changed { prevDisplay = now(); digitalClockDisplay(); }}

void digitalClockDisplay(){ // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); }

void printDigits(int digits){ // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if(digits < 10) Serial.print('0'); Serial.print(digits);}

/*-------- NTP code ----------*/// ntp code not shown - see TimeNTP.pde example sketch

233

Page 235: Arduino Language Reference

tone()

Generates a square wave of the specified frequency (and 50% duty cycle) on a pin. A duration can be specified, otherwise the wave continues until a call to noTone(). The pin can be connected to a piezo buzzer or other speaker to play tones.

Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency.

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

NOTE: if you want to play different pitches on multiple pins, you need to call noTone() on one pin before calling tone() on the next pin.

Syntax: tone(pin, frequency) tone(pin, frequency, duration)

Parameters: pin: the pin on which to generate the tonefrequency: the frequency of the tone in hertz - unsigned intduration: the duration of the tone in milliseconds (optional) - unsigned long

Returns: nothing

unsigned char

An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.

The unsigned char datatype encodes numbers from 0 to 255.

For consistency of Arduino programming style, the byte data type is to be preferred.

Example

unsigned char myChar = 240;

unsigned int

Unsigned ints (unsigned integers) are the same as ints in that they store a 2 byte value. Instead of storing negative numbers however they only store positive values, yielding a useful range of 0 to 65,535 (2^16) - 1).

The difference between unsigned ints and (signed) ints, lies in the way the highest bit, sometimes refered to as the "sign" bit, is interpreted. In the Arduino int type (which is signed), if the high bit is a "1", the number is interpreted as a negative number, and the other 15 bits are interpreted with 2's complement math.

Example

Unsigned int ledPin = 13;

234

Page 236: Arduino Language Reference

Syntax: unsigned int var = val;# var - your unsigned int variable name

# val - the value you assign to that variable

Coding Tip

When variables are made to exceed their maximum capacity they "roll over" back to their minimum capacitiy, note that this happens in both directions

unsigned int x x = 0; x = x - 1; // x now contains 65535 - rolls over in neg direction x = x + 1; // x now contains 0 - rolls over

unsigned long

Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

Example

unsigned long time;

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

void loop(){ Serial.print("Time: "); time = millis(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000);}

Syntax: unsigned long var = val;# var - your long variable name

# val - the value you assign to that variable

235

Page 237: Arduino Language Reference

Variables

A variable is a way of naming and storing a value for later use by the program, such as data from a sensor or an intermediate value used in a calculation.

Declaring VariablesBefore they are used, all variables have to be declared. Declaring a variable means defining its type, and optionally, setting an initial value (initializing the variable). Variables do not have to be initialized (assigned a value) when they are declared, but it is often useful.

int inputVariable1;int inputVariable2 = 0; // both are correct

Programmers should consider the size of the numbers they wish to store in choosing variable types. Variables will roll over when the value stored exceeds the space assigned to store it. See below for an example.

Variable Scope

Another important choice that programmers face is where to declare variables. The specific place that variables are declared influences how various functions in a program will see the variable. This is called variable scope.

Initializing Variables

Variables may be initialized (assigned a starting value) when they are declared or not. It is always good programming practice however to double check that a variable has valid data in it, before it is accessed for some other purpose.

Example

int calibrationVal = 17; // declare calibrationVal and set initial value

Variable Rollover

When variables are made to exceed their maximum capacity they "roll over" back to their minimum capacity, note that this happens in both directions.

int x x = -32,768; x = x - 1; // x now contains 32,767 - rolls over in neg. direction

x = 32,767; x = x + 1; // x now contains -32,768 - rolls over

Using Variables

Once variables have been declared, they are used by setting the variable equal to the value one wishes to store with the assignment operator (single equal sign). The assignment operator tells the program to put whatever is on the right side of the equal sign into the variable on the left side.

inputVariable1 = 7; // sets the variable named inputVariable1 to 7

236

Page 238: Arduino Language Reference

inputVariable2 = analogRead(2); // sets the variable named inputVariable2 to the // (digitized) input voltage read from analog pin #2

Examples

int lightSensVal; char currentLetter; unsigned long speedOfLight = 186000UL; char errorMessage = {"choose another option"}; // see string

Once a variable has been set (assigned a value), you can test its value to see if it meets certain conditions, or you can use its value directly. For instance, the following code tests whether the inputVariable2 is less than 100, then sets a delay based on inputVariable2 which is a minimum of 100:

if (inputVariable2 < 100){ inputVariable2 = 100;}

delay(inputVariable2);

This example shows all three useful operations with variables. It tests the variable ( if (inputVariable2 < 100) ), it sets the variable if it passes the test ( inputVariable2 = 100 ), and it uses the value of the variable as an input parameter to the delay() function ( delay(inputVariable2) )

Style Note: You should give your variables descriptive names, so as to make your code more readable. Variable names like tiltSensor or pushButton help you (and anyone else reading your code) understand what the variable represents. Variable names like var or value, on the other hand, do little to make your code readable.

You can name a variable any word that is not already one of the keywords in Arduino. Avoid beginning variable names with numeral characters.

Some variable types

# char # byte # int # unsigned int # long # unsigned long # float # double

void

The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.

237

Page 239: Arduino Language Reference

Example

// actions are performed in the functions "setup" and "loop"// but no information is reported to the larger program

void setup(){ // ...}

void loop(){ // ...}

volatile keyword

volatile is a keyword known as a variable qualifier, it is usually used before the datatype of a variable, to modify the way in which the compiler and subsequent program treats the variable.

Declaring a variable volatile is a directive to the compiler. The compiler is software which translates your C/C++ code into the machine code, which are the real instructions for the Atmega chip in the Arduino.

Specifically, it directs the compiler to load the variable from RAM and not from a storage register, which is a temporary memory location where program variables are stored and manipulated. Under certain conditions, the value for a variable stored in registers can be inaccurate.

A variable should be declared volatile whenever its value can be changed by something beyond the control of the code section in which it appears, such as a concurrently executing thread. In the Arduino, the only place that this is likely to occur is in sections of code associated with interrupts, called an interrupt service routine.

Example

// toggles LED when interrupt pin changes state

int pin = 13;volatile int state = LOW;

void setup(){ pinMode(pin, OUTPUT); attachInterrupt(0, blink, CHANGE);}

void loop(){ digitalWrite(pin, state);}

238

Page 240: Arduino Language Reference

void blink(){ state = !state;}

while loops

while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor.

Syntax: while(expression){ // statement(s)

}

Parameters: expression - a (boolean) C statement that evaluates to true or false

Example

var = 0;while(var < 200){

// do something repetitive 200 times var++; }

WiFi library

With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet. It can serve as either a server accepting incoming connections or a client making outgoing ones. The library supports WEP and WPA2 Personal encryption, but not WPA2 Enterprise. Also note, if the SSID is not broadcast, the shield cannot connect.

Arduino communicates with the WiFi shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used but it must be kept as an output or the SPI interface won't work. Digital pin 7 is used as a handshake pin between the Wifi shield and the Arduino, and should not be used.

The WiFi library is very similar to the Ethernet library, and many of the function calls are the same.

For additional information on the WiFi shield, see the Getting Started page and the WiFi shield hardware page.

WiFi class

The WiFi class initializes the ethernet library and network settings.

239

Page 241: Arduino Language Reference

* begin() * disconnect() * SSID() * BSSID() * RSSI() * encryptionType() * scanNetworks() * getSocket() * macAddress()

IPAddress class

The IPAddress class provides information about the network configuration.

* localIP() * subnetMask() * gatewayIP()

Server class

The Server class creates servers which can send data to and receive data from connected clients (programs running on other computers or devices).

* Server

* WiFiServer() * begin() * available() * write() * print() * println()

Client class

The client class creates clients that can connect to servers and send and receive data.

* Client

* WiFiClient() * connected() * connect() * write() * print() * println() * available() * read() * flush() * stop()

240

Page 242: Arduino Language Reference

Examples

ConnectNoEncryption

/* This example connects to an unencrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details.

Circuit: * WiFi shield attached */

#include <WiFi.h>

char ssid[] = "yourNetwork"; // the name of your networkint status = WL_IDLE_STATUS; // the Wifi radio's status

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

// attempt to connect to an open network: Serial.print("Attempting to connect to open network: "); Serial.println(ssid); status = WiFi.begin(ssid);

// if you're not connected, stop here: if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected : else { Serial.print("You're connected to the network"); printCurrentNet(); printWifiData(); }}

void loop() { // check the network connection once every 10 seconds: delay(10000); printCurrentNet();}

void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip);

241

Page 243: Arduino Language Reference

// print your MAC address: byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); Serial.print(mac[5],HEX); Serial.print(":"); Serial.print(mac[4],HEX); Serial.print(":"); Serial.print(mac[3],HEX); Serial.print(":"); Serial.print(mac[2],HEX); Serial.print(":"); Serial.print(mac[1],HEX); Serial.print(":"); Serial.println(mac[0],HEX);

// print your subnet mask: IPAddress subnet = WiFi.subnetMask(); Serial.print("NetMask: "); Serial.println(subnet);

// print your gateway address: IPAddress gateway = WiFi.gatewayIP(); Serial.print("Gateway: "); Serial.println(gateway);}

void printCurrentNet() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print the MAC address of the router you're attached to: byte bssid[6]; WiFi.BSSID(bssid); Serial.print("BSSID: "); Serial.print(bssid[5],HEX); Serial.print(":"); Serial.print(bssid[4],HEX); Serial.print(":"); Serial.print(bssid[3],HEX); Serial.print(":"); Serial.print(bssid[2],HEX); Serial.print(":"); Serial.print(bssid[1],HEX); Serial.print(":"); Serial.println(bssid[0],HEX);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.println(rssi);

242

Page 244: Arduino Language Reference

// print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); Serial.println(encryption,HEX);}

ConnectWithWEP

/*

This example connects to a WEP-encrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details.

If you use 40-bit WEP, you need a key that is 10 characters long, and the characters must be hexadecimal (0-9 or A-F). e.g. for 40-bit, ABBADEAF01 will work, but ABBADEAF won't work (too short) and ABBAISDEAF won't work (I and S are not hexadecimal characters).

For 128-bit, you need a string that is 26 characters long. D0D0DEADF00DABBADEAFBEADED will work because it's 26 characters, all in the 0-9, A-F range.

Circuit:* WiFi shield attached */

#include <WiFi.h>

char ssid[] = "yourNetwork"; // your network SSID (name) char key[] = "D0D0DEADF00DABBADEAFBEADED"; // your network keyint keyIndex = 0; // your network key Index numberint status = WL_IDLE_STATUS; // the Wifi radio's status

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

// attempt to connect to an open network: Serial.print("Attempting to connect to WEP network: "); Serial.println(ssid); status = WiFi.begin(ssid, keyIndex, key);

// if you're not connected, stop here: if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected : else { Serial.print("You're connected to the network"); printCurrentNet(); printWifiData();

243

Page 245: Arduino Language Reference

}}

void loop() { // check the network connection once every 10 seconds: delay(10000); printCurrentNet();}

void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip);

// print your MAC address: byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); Serial.print(mac[5],HEX); Serial.print(":"); Serial.print(mac[4],HEX); Serial.print(":"); Serial.print(mac[3],HEX); Serial.print(":"); Serial.print(mac[2],HEX); Serial.print(":"); Serial.print(mac[1],HEX); Serial.print(":"); Serial.println(mac[0],HEX);}

void printCurrentNet() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print the MAC address of the router you're attached to: byte bssid[6]; WiFi.BSSID(bssid); Serial.print("BSSID: "); Serial.print(bssid[5],HEX); Serial.print(":"); Serial.print(bssid[4],HEX); Serial.print(":"); Serial.print(bssid[3],HEX); Serial.print(":"); Serial.print(bssid[2],HEX); Serial.print(":"); Serial.print(bssid[1],HEX); Serial.print(":");

244

Page 246: Arduino Language Reference

Serial.println(bssid[0],HEX);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.println(rssi);

// print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); Serial.println(encryption,HEX); Serial.println();}

ConnectWithWPA

/*

This example connects to a WPA-encrypted Wifi network. Then it prints the MAC address of the Wifi shield, the IP address obtained, and other network details.

Circuit:* WiFi shield attached */

#include <WiFi.h>

char ssid[] = "networkName"; // your network SSID (name) char pass[] = "yourPassword"; // your network passwordint status = WL_IDLE_STATUS; // the Wifi radio's status

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

// attempt to connect to an open network: Serial.print("Attempting to connect to WPA network: "); Serial.println(ssid); status = WiFi.begin(ssid, pass);

// if you're not connected, stop here: if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected : else { Serial.print("You're connected to the network"); printCurrentNet(); printWifiData();

245

Page 247: Arduino Language Reference

}}

void loop() { // check the network connection once every 10 seconds: delay(10000); printCurrentNet();}

void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip);

// print your MAC address: byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); Serial.print(mac[5],HEX); Serial.print(":"); Serial.print(mac[4],HEX); Serial.print(":"); Serial.print(mac[3],HEX); Serial.print(":"); Serial.print(mac[2],HEX); Serial.print(":"); Serial.print(mac[1],HEX); Serial.print(":"); Serial.println(mac[0],HEX);

}

void printCurrentNet() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print the MAC address of the router you're attached to: byte bssid[6]; WiFi.BSSID(bssid); Serial.print("BSSID: "); Serial.print(bssid[5],HEX); Serial.print(":"); Serial.print(bssid[4],HEX); Serial.print(":"); Serial.print(bssid[3],HEX); Serial.print(":"); Serial.print(bssid[2],HEX); Serial.print(":"); Serial.print(bssid[1],HEX);

246

Page 248: Arduino Language Reference

Serial.print(":"); Serial.println(bssid[0],HEX);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.println(rssi);

// print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); Serial.println(encryption,HEX); Serial.println();}

ScanNetworks

/*

This example prints the Wifi shield's MAC address, and scans for available Wifi networks using the Wifi shield. Every ten seconds, it scans again. It doesn't actually connect to any network, so no encryption scheme is specified.

Circuit: * WiFi shield attached

*/

# include <SPI.h>

#include <WiFi.h>

void setup() {

// initialize serial and wait for the port to open: Serial.begin(9600);

// attempt to connect using WEP encryption: Serial.println("Initializing Wifi..."); printMacAddress();

// scan for existing networks: Serial.println("Scanning available networks..."); listNetworks();

}

void loop() {

delay(10000); // scan for existing networks: Serial.println("Scanning available networks...");

247

Page 249: Arduino Language Reference

listNetworks();

}

void printMacAddress() {

// the MAC address of your Wifi shield byte mac[6];

// print your MAC address: WiFi.macAddress(mac); Serial.print("MAC: "); Serial.print(mac[5],HEX); Serial.print(":"); Serial.print(mac[4],HEX); Serial.print(":"); Serial.print(mac[3],HEX); Serial.print(":"); Serial.print(mac[2],HEX); Serial.print(":"); Serial.print(mac[1],HEX); Serial.print(":"); Serial.println(mac[0],HEX);

}

void listNetworks() {

// scan for nearby networks: Serial.println("** Scan Networks **"); byte numSsid = WiFi.scanNetworks();

// print the list of networks seen: Serial.print("number of available networks:"); Serial.println(numSsid);

// print the network number and name for each network found: for (int thisNet = 0; thisNet<numSsid; thisNet++) { Serial.print(thisNet); Serial.print(") "); Serial.print(WiFi.SSID(thisNet)); Serial.print("\tSignal: "); Serial.print(WiFi.RSSI(thisNet)); Serial.print(" dBm"); Serial.print("\tEncryption: "); Serial.println(WiFi.encryptionType(thisNet)); }

}

248

Page 250: Arduino Language Reference

/*

Chat Server

A simple server that distributes any incoming messages to all connected clients. To use telnet to your device's IP address and type. You can see the client's input in the serial monitor as well.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

Circuit: * WiFi shield attached */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "YourNetwork"; // your network SSID (name) char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)

int keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

WiFiServer server(23);

boolean alreadyConnected = false; // whether or not the client was connected previously

void setup() { // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // start the server: server.begin(); // you're connected now, so print out the status: printWifiStatus(); }

void loop() { // wait for a new client: WiFiClient client = server.available();

// when the client sends the first byte, say hello: if (client) {

249

Page 251: Arduino Language Reference

if (!alreadyConnected) { // clead out the input buffer: client.flush(); Serial.println("We have a new client"); client.println("Hello, client!"); alreadyConnected = true; }

if (client.available() > 0) { // read the bytes incoming from the client: char thisChar = client.read(); // echo the bytes back to the client: server.write(thisChar); // echo the bytes to the server as well: Serial.write(thisChar); } }}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

/*

Wifi Pachube sensor client

This sketch connects an analog sensor to Pachube (http://www.pachube.com) using an Arduino Wifi shield.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

This example has been updated to use version 2.0 of the Pachube.com API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed.

Circuit:

250

Page 252: Arduino Language Reference

* Analog sensor attached to analog in 0 * Wifi shield attached to pins 10, 11, 12, 13 */

#include <SPI.h>#include <WiFi.h>

#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here#define FEEDID 00000 // replace your feed ID#define USERAGENT "My Arduino Project" // user agent is the project name

char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password

int status = WL_IDLE_STATUS;

// initialize the library instance:WiFiClient client;// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server:IPAddress server(216,52,233,122); // numeric IP for api.pachube.com//char server[] = "api.pachube.com"; // name address for pachube API

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecondsboolean lastConnected = false; // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com

void setup() { // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the status: printWifiStatus();}

void loop() { // read the analog sensor: int sensorReading = analogRead(A0);

// if there's incoming data from the net connection. // send it out the serial port. This is for debugging // purposes only: if (client.available()) {

251

Page 253: Arduino Language Reference

char c = client.read(); Serial.print(c); }

// if there's no net connection, but there was one last time // through the loop, then stop the client: if (!client.connected() && lastConnected) { Serial.println(); Serial.println("disconnecting."); client.stop(); }

// if you're not connected, and ten seconds have passed since // your last connection, then connect again and send data: if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { sendData(sensorReading); } // store the state of the connection for next time through // the loop: lastConnected = client.connected();}

// this method makes a HTTP connection to the server:void sendData(int thisData) { // if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting..."); // send the HTTP PUT request: client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); client.println("Host: api.pachube.com"); client.print("X-PachubeApiKey: "); client.println(APIKEY); client.print("User-Agent: "); client.println(USERAGENT); client.print("Content-Length: ");

// calculate the length of the sensor reading in bytes: // 8 bytes for "sensor1," + number of digits of the data: int thisLength = 8 + getLength(thisData); client.println(thisLength);

// last pieces of the HTTP PUT request: client.println("Content-Type: text/csv"); client.println("Connection: close"); client.println();

// here's the actual content of the PUT request: client.print("sensor1,"); client.println(thisData);

252

Page 254: Arduino Language Reference

} else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println(); Serial.println("disconnecting."); client.stop(); } // note the time that the connection was made or attempted: lastConnectionTime = millis();}

// This method calculates the number of digits in the// sensor reading. Since each digit of the ASCII decimal// representation is a byte, the number of digits equals// the number of bytes:

int getLength(int someValue) { // there's at least one byte: int digits = 1; // continually divide the value by ten, // adding one to the digit count for each // time you divide, until you're at 0: int dividend = someValue /10; while (dividend > 0) { dividend = dividend /10; digits++; } // return the number of digits: return digits;}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

253

Page 255: Arduino Language Reference

/*

Wifi Pachube sensor client with Strings

This sketch connects an analog sensor to Pachube using a Arduino Wifi shield.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

This example has been updated to use version 2.0 of the Pachube.com API. To make it work, create a feed with a datastream, and give it the ID sensor1. Or change the code below to match your feed.

This example uses the String library, which is part of the Arduino core from version 0019.

Circuit: * Analog sensor attached to analog in 0 * Wifi shield attached to pins 10, 11, 12, 13 */

#include <SPI.h>#include <WiFi.h>

#define APIKEY "YOUR API KEY GOES HERE" // replace your pachube api key here#define FEEDID 00000 // replace your feed ID#define USERAGENT "My Arduino Project" // user agent is the project name

char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password

int status = WL_IDLE_STATUS;

// initialize the library instance:WiFiClient client;

// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(216,52,233,122); // numeric IP for api.pachube.comchar server[] = "api.pachube.com"; // name address for pachube API

unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecondsboolean lastConnected = false; // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com

void setup() { // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass);

254

Page 256: Arduino Language Reference

// wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the status: printWifiStatus();}

void loop() { // read the analog sensor: int sensorReading = analogRead(A0); // convert the data to a String to send it:

String dataString = "sensor1,"; dataString += sensorReading;

// you can append multiple readings to this String if your // pachube feed is set up to handle multiple values: int otherSensorReading = analogRead(A1); dataString += "\nsensor2,"; dataString += otherSensorReading;

// if there's incoming data from the net connection. // send it out the serial port. This is for debugging // purposes only: if (client.available()) { char c = client.read(); Serial.print(c); }

// if there's no net connection, but there was one last time // through the loop, then stop the client: if (!client.connected() && lastConnected) { Serial.println(); Serial.println("disconnecting."); client.stop(); }

// if you're not connected, and ten seconds have passed since // your last connection, then connect again and send data: if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { sendData(dataString); } // store the state of the connection for next time through // the loop: lastConnected = client.connected();}

// this method makes a HTTP connection to the server:void sendData(String thisData) { // if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting...");

255

Page 257: Arduino Language Reference

// send the HTTP PUT request: client.print("PUT /v2/feeds/"); client.print(FEEDID); client.println(".csv HTTP/1.1"); client.println("Host: api.pachube.com"); client.print("X-PachubeApiKey: "); client.println(APIKEY); client.print("User-Agent: "); client.println(USERAGENT); client.print("Content-Length: "); client.println(thisData.length());

// last pieces of the HTTP PUT request: client.println("Content-Type: text/csv"); client.println("Connection: close"); client.println();

// here's the actual content of the PUT request: client.println(thisData); } else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println(); Serial.println("disconnecting."); client.stop(); } // note the time that the connection was made or attempted: lastConnectionTime = millis();}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

256

Page 258: Arduino Language Reference

WiFiTwitterClient

/* Wifi Twitter Client with Strings

This sketch connects to Twitter using using an Arduino WiFi shield. It parses the XML returned, and looks for <text>this is a tweet</text>

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

This example uses the String library, which is part of the Arduino core from version 0019.

Circuit: * WiFi shield attached to pins 10, 11, 12, 13 */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "YourNetwork"; // your network SSID (name) char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)int keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS; // status of the wifi connection

// initialize the library instance:WiFiClient client;

const unsigned long requestInterval = 30*1000; // delay between requests; 30 seconds

// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server://IPAddress server(199,59,149,200); // numeric IP for api.twitter.comchar server[] = "api.twitter.com"; // name address for twitter API

boolean requested; // whether you've made a request since connectingunsigned long lastAttemptTime = 0; // last time you connected to the server, in milliseconds

String currentLine = ""; // string to hold the text from serverString tweet = ""; // string to hold the tweetboolean readingTweet = false; // if you're currently reading the tweet

void setup() { // reserve space for the strings: currentLine.reserve(256); tweet.reserve(150); // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: ");

257

Page 259: Arduino Language Reference

Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the status: printWifiStatus(); connectToServer();}

void loop(){ if (client.connected()) { if (client.available()) { // read incoming bytes: char inChar = client.read();

// add incoming byte to end of line: currentLine += inChar;

// if you get a newline, clear the line: if (inChar == '\n') { currentLine = ""; } // if the current line ends with <text>, it will // be followed by the tweet: if ( currentLine.endsWith("<text>")) { // tweet is beginning. Clear the tweet string: readingTweet = true; tweet = ""; // break out of the loop so this character isn't added to the tweet: return; } // if you're currently reading the bytes of a tweet, // add them to the tweet String: if (readingTweet) { if (inChar != '<') { tweet += inChar; } else { // if you got a "<" character, // you've reached the end of the tweet: readingTweet = false; Serial.println(tweet); // close the connection to the server: client.stop(); } } } } else if (millis() - lastAttemptTime > requestInterval) { // if you're not connected, and two minutes have passed since

258

Page 260: Arduino Language Reference

// your last connection, then attempt to connect again: connectToServer(); }}

void connectToServer() { // attempt to connect, and wait a millisecond: Serial.println("connecting to server..."); if (client.connect(server, 80)) { Serial.println("making HTTP request..."); // make HTTP GET request to twitter: client.println("GET /1/statuses/user_timeline.xml?screen_name=arduino HTTP/1.1"); client.println("Host:api.twitter.com"); client.println("Connection:close"); client.println(); } // note the time of this connect attempt: lastAttemptTime = millis();}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

Web client

/*

This sketch connects to a website (http://www.google.com) using a WiFi shield.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

Circuit: * WiFi shield attached

259

Page 261: Arduino Language Reference

*/

#include <SPI.h>#include <WiFi.h>

char ssid[] = "YourNetwork";// your network SSID (name) char pass[] = "password"; // your network password (use for WPA, or use as key for WEP)int keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;// if you don't want to use DNS (and reduce your sketch size)// use the numeric IP instead of the name for the server:IPAddress server(173,194,73,105); // numeric IP for Google (no DNS)//char server[] = "www.google.com"; // name address for Google (using DNS)

// Initialize the Ethernet client library with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP):

WiFiClient client;

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

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } Serial.println("Connected to wifi"); printWifiStatus();

Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected to server"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.1"); client.println("Host:www.google.com"); client.println("Connection: close"); client.println(); }}

void loop() { // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); Serial.write(c);

260

Page 262: Arduino Language Reference

}

// if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting from server."); client.stop();

// do nothing forevermore: while(true); }}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

Repeating Wifi Web client

/*This sketch connects to a a web server and makes a request using an Arduino Wifi shield.

Circuit:* Wifi shield attached to pins 10, 11, 12, 13 */

#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network passwordint keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

// Initialize the Wifi client libraryWiFiClient client;

261

Page 263: Arduino Language Reference

// server address:char server[] = "www.arduino.cc";//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0; // last time you connected to the server, in msec boolean lastConnected = false; // state of the connection last time through the main loopconst unsigned long postingInterval = 10*1000; // delay between updates, in milliseconds

void setup() { // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the status: printWifiStatus();}

void loop() { // if there's incoming data from the net connection. // send it out the serial port. This is for debugging purposes only: while (client.available()) { char c = client.read(); Serial.write(c); }

// if there's no net connection, but there was one last time // through the loop, then stop the client: if (!client.connected() && lastConnected) { Serial.println(); Serial.println("disconnecting."); client.stop(); }

// if you're not connected, and ten seconds have passed since // your last connection, then connect again and send data: if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) { httpRequest(); } // store the state of the connection for next time through // the loop: lastConnected = client.connected();}

// this method makes a HTTP connection to the server:void httpRequest() {

262

Page 264: Arduino Language Reference

// if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting..."); // send the HTTP PUT request: client.println("GET /latest.txt HTTP/1.1"); client.println("Host: www.arduino.cc"); client.println("User-Agent: arduino-ethernet"); client.println("Connection: close"); client.println();

// note the time that the connection was made: lastConnectionTime = millis(); } else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println("disconnecting."); client.stop(); }}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

Web Server

/*A simple web server that shows the value of the analog input pins. using a WiFi shield.

This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly.

Circuit: * WiFi shield attached * Analog inputs attached to pins A0 through A5 (optional) */

263

Page 265: Arduino Language Reference

#include <SPI.h>#include <WiFi.h>

char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network passwordint keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() { // start serial port: Serial.begin(9600);

// attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } server.begin(); // you're connected now, so print out the status: printWifiStatus();}

void loop() { // listen for incoming clients WiFiClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connnection: close"); client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // add a meta refresh tag, so the browser pulls again every 5 seconds:

264

Page 266: Arduino Language Reference

client.println("<meta http-equiv=\"refresh\" content=\"5\">"); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print(" is "); client.print(sensorReading); client.println("<br />"); } client.println("</html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); }}

void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID());

// print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip);

// print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm");}

265

Page 267: Arduino Language Reference

WiFi

WiFi.begin()

Initializes the WiFi library's network settings and provides the current status.

Syntax: WiFi.begin(); WiFi.begin(ssid); WiFi.begin(ssid, pass); WiFi.begin(ssid, keyIndex, key);

Parameters: ssid: the SSID (Service Set Identifier) is the name of the WiFi network you want to connect to.keyIndex: WEP encrypted networks can hold up to 4 different keys. This identifies which key you are going to use.key: a hexadecimal string used as a security code for WEP encrypted networks.pass: WPA encrypted networks use a password in the form of a string for security.

Returns: # WL_CONNECTED when connected to a network # WL_IDLE_STATUS when not connected to a network, but powered on

Example

#include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword";

void setup() { WiFi.begin(ssid, pass); }

void loop () {}

WiFi

WiFi.BSSID()

Gets the MAC address of the routher you are connected to

Syntax: WiFi.BSSID(bssid);Parameters: bssid : 6 byte arrayReturns: A byte array containing the MAC address of the router the WiFi shield is currently

connected to.

Example

266

Page 268: Arduino Language Reference

#include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword";

void setup() { WiFi.begin(ssid, pass);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else { // print the MAC address of the router you're attached to: byte bssid[6]; WiFi.BSSID(bssid); Serial.print("BSSID: "); Serial.print(bssid[5],HEX); Serial.print(":"); Serial.print(bssid[4],HEX); Serial.print(":"); Serial.print(bssid[3],HEX); Serial.print(":"); Serial.print(bssid[2],HEX); Serial.print(":"); Serial.print(bssid[1],HEX); Serial.print(":"); Serial.println(bssid[0],HEX); } }

void loop () {}

WiFi : Client class

Client()

Client is the base class for all WiFi client based calls. It is not called directly, but invoked whenever you use a function that relies on it.

WiFi : Client class

client.available()

Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to).

267

Page 269: Arduino Language Reference

available() inherits from the Stream utility class.

Syntax: client.available()Parameters: noneReturns: The number of bytes available.

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "myNetwork"; // your network SSID (name) char pass[] = "myPassword"; // your network password

int status = WL_IDLE_STATUS; char servername[]="google.com"; // Google

WiFiClient client;

void setup() { Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); // don't do anything else: while(true); } else { Serial.println("Connected to wifi"); Serial.println("\nStarting connection..."); // if you get a connection, report back via serial: if (client.connect(servername, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } } }

void loop() { // if there are incoming bytes available // from the server, read them and print them: if (client.available()) { char c = client.read(); Serial.print(c); }

268

Page 270: Arduino Language Reference

// if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop();

// do nothing forevermore: for(;;) ; } }

WiFi : Client class

connected()

Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data.

Syntax: client.connected()Parameters: noneReturns: Returns true if the client is connected, false if not.

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "myNetwork"; // your network SSID (name) char pass[] = "myPassword"; // your network password

int status = WL_IDLE_STATUS; IPAddress server(74,125,115,105); // Google

// Initialize the client library WiFiClient client;

void setup() { Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); // don't do anything else: while(true); } else {

269

Page 271: Arduino Language Reference

Serial.println("Connected to wifi"); Serial.println("\nStarting connection..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } } }

void loop() { if (client.available()) { char c = client.read(); Serial.print(c); }

if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } }

WiFi : Client class

connect()

Connect to the IP address and port specified in the constructor. The return value indicates success or failure. connect() also supports DNS lookups when using a domain name (ex:google.com).

Syntax: client.connect(ip, port) client.connect(URL, port)

Parameters: ip: the IP address that the client will connect to (array of 4 bytes)URL: the domain name the client will connect to (string, ex.:"arduino.cc")port: the port that the client will connect to (int)

Returns: Returns true if the connection succeeds, false if not.

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "myNetwork"; // your network SSID (name) char pass[] = "myPassword"; // your network password

270

Page 272: Arduino Language Reference

int status = WL_IDLE_STATUS; char servername[]="google.com"; // remote server we will connect to

WiFiClient client;

void setup() { Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); // don't do anything else: while(true); } else { Serial.println("Connected to wifi"); Serial.println("\nStarting connection..."); // if you get a connection, report back via serial: if (client.connect(servername, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } } }void loop() { }

WiFi : Client class

flush()

Discard any bytes that have been written to the client but not yet read.

flush() inherits from the Stream utility class.

Syntax: client.flush()Parameters: noneReturns: none

WiFi : Client class

WiFiClient()

Creates a client that can connect to to a specified internet IP address and port as defined in client.connect().

271

Page 273: Arduino Language Reference

Syntax: WiFiClient()

Parameters: none

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "myNetwork"; // your network SSID (name) char pass[] = "myPassword"; // your network password

int status = WL_IDLE_STATUS; IPAddress server(74,125,115,105); // Google

// Initialize the client library WiFiClient client;

void setup() { Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); // don't do anything else: while(true); } else { Serial.println("Connected to wifi"); Serial.println("\nStarting connection..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.0"); client.println(); } } }

void loop() { }

272

Page 274: Arduino Language Reference

WiFi : Client class

print()

Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: client.print(data) client.print(data, BASE)

Parameters: data: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers:, DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte : returns the number of bytes written, though reading that number is optional

WiFi : Client class

println()

Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: client.println() client.println(data) client.print(data, BASE)

Parameters: data (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte: return the number of bytes written, though reading that number is optional

WiFi : Client class

read()

Read the next byte received from the server the client is connected to (after the last call to read()).read() inherits from the Stream utility class.

Syntax: client.read()Parameters: none

Returns: The next byte (or character), or -1 if none is available.

273

Page 275: Arduino Language Reference

WiFi : Client class

stop()

Disconnect from the server

Syntax: client.stop()Parameters: noneReturns: none

WiFi : Client class

write()

Write data to the server the client is connected to.

Syntax: client.write(data)Parameters: data: the byte or char to writeReturns: byte: the number of characters written. it is not necessary to read this value.

WiFi

WiFi.disconnect()

Disconnects the WiFi shield from the current network.

Syntax: WiFi.disconnect();Parameters: noneReturns: nothing

WiFi

WiFi.encryptionType()

Gets the encryption type of the current network

Syntax: WiFi.encryptionType();WiFi.encryptionType(wifiAccessPoint);

Parameters: wifiAccessPoint: specifies which network to get information from

Returns: byte : value represents the type of encryption* TKIP (WPA) = 2

* WEP = 5 * CCMP (WPA) = 4 * NONE = 7 * AUTO = 8Example

274

Page 276: Arduino Language Reference

#include <SPI.h> #include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword";

void setup() { WiFi.begin(ssid, pass);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else { // print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); Serial.println(encryption,HEX); } }

void loop () {}

WiFi.gatewayIP()

Gets the WiFi shield's gateway IP address.

Syntax: WiFi.gatewayIP();Parameters: noneReturns: An array containing the shield's gateway IP address

Example

include <SPI.h> include <WiFi.h>

int status = WL_IDLE_STATUS; // the Wifi radio's status

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword"; IPAddress gateway;

void setup() {

Serial.begin(9600);

WiFi.begin(ssid, pass);

275

Page 277: Arduino Language Reference

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else {

// print your gateway address: gateway = WiFi.gatewayIP(); Serial.print("GATEWAY: "); Serial.println(gateway); }}

void loop () {}

WiFi.getSocket()

gets the first socket available

Syntax: WiFi.getSocket();Parameters: noneReturns: int : the first socket available

WiFi.localIP()

Gets the WiFi shield's IP address

Syntax: WiFi.localIP();Parameters: noneReturns: the IP address of the shieldExample

#include <WiFi.h>

char ssid[] = "yourNetwork"; //SSID of your network

int status = WL_IDLE_STATUS; // the Wifi radio's status

IPAddress ip; // the IP address of your shield

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

WiFi.begin(ssid);

if ( status != WL_CONNECTED) {

276

Page 278: Arduino Language Reference

Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else { //print the local IP address ip = WiFi.localIP(); Serial.println(ip);

} }

void loop () {}

WiFi.macAddress()

Gets the MAC Address of your WiFi shield

Syntax: WiFi.macAddress(mac);Parameters: mac: a 6 byte array to hold the MAC addressReturns: byte array : 6 bytes representing the MAC address of your shieldExample

#include <SPI.h> #include <WiFi.h>

char ssid[] = "yourNetwork"; // the name of your network int status = WL_IDLE_STATUS; // the Wifi radio's status

byte mac[6]; // the MAC address of your Wifi shield

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

status = WiFi.begin(ssid);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print your MAC address: else { WiFi.macAddress(mac); Serial.print("MAC: "); Serial.print(mac[5],HEX); Serial.print(":"); Serial.print(mac[4],HEX); Serial.print(":"); Serial.print(mac[3],HEX); Serial.print(":");

277

Page 279: Arduino Language Reference

Serial.print(mac[2],HEX); Serial.print(":"); Serial.print(mac[1],HEX); Serial.print(":"); Serial.println(mac[0],HEX); } }

void loop () {}

WiFi.RSSI()

Gets the signal strength of the connection to the router

Syntax: WiFi.RSSI(); WiFi.RSSI(wifiAccessPoint);

Parameters: wifiAccessPoint: specifies from which network to get the information

Returns: long : the current RSSI /Received Signal Strength in dBm

Example #include <SPI.h> #include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword"; void setup() { WiFi.begin(ssid, pass);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else { // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("RSSI:"); Serial.println(rssi); } }

void loop () {}

278

Page 280: Arduino Language Reference

WiFi.scanNetworks()

Scans for available WiFi networks and returns the discovered number

Syntax: WiFi.scanNetworks();Parameters: noneReturns: byte : number of discovered networks

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "yourNetwork"; // the name of your network int status = WL_IDLE_STATUS; // the Wifi radio's status

byte mac[6]; // the MAC address of your Wifi shield

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

status = WiFi.begin(ssid);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print your MAC address: else { Serial.println("** Scan Networks **"); byte numSsid = WiFi.scanNetworks();

Serial.print("SSID List:"); Serial.println(numSsid); } }

void loop () {}

WiFi.SSID()

Gets the SSID of the current network

Syntax: WiFi.SSID(); WiFi.SSID(wifiAccessPoint)

Parameters: wifiAccessPoint: specifies from which network to get the information

Returns: A string containing the SSID the WiFi shield is currently connected to.

279

Page 281: Arduino Language Reference

string containing name of network requested.

Example

#include <SPI.h> #include <WiFi.h>

//SSID of your network char ssid[] = "yourNetwork"; int status = WL_IDLE_STATUS; // the Wifi radio's status

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

// scan for existing networks: Serial.println("Scanning available networks..."); scanNetworks();

// attempt to connect using WEP encryption: Serial.println("Attempting to connect to open network..."); status = WiFi.begin(ssid);

Serial.print("SSID: "); Serial.println(ssid);

}

void loop () {}

void scanNetworks() { // scan for nearby networks: Serial.println("** Scan Networks **"); byte numSsid = WiFi.scanNetworks();

// print the list of networks seen: Serial.print("SSID List:"); Serial.println(numSsid); // print the network number and name for each network found: for (int thisNet = 0; thisNet<numSsid; thisNet++) { Serial.print(thisNet); Serial.print(") Network: "); Serial.println(WiFi.SSID(thisNet)); } }

280

Page 282: Arduino Language Reference

WiFi.subnetMask()

Gets the WiFi shield's subnet mask

Syntax: WiFi.subnet();Parameters: none

Returns: the subnet mask of the shield

Example

#include <WiFi.h> int status = WL_IDLE_STATUS; // the Wifi radio's status

//SSID of your network char ssid[] = "yourNetwork"; //password of your WPA Network char pass[] = "secretPassword";

IPAddress ip; IPAddress subnet; IPAddress gateway;

void setup() { WiFi.begin(ssid, pass);

if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } // if you are connected, print out info about the connection: else {

// print your subnet mask: subnet = WiFi.subnetMask(); Serial.print("NETMASK: "); Serial.println(); } } void loop () { }

281

Page 283: Arduino Language Reference

WiFi : Server class

server.available()

Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling client.stop().

available() inherits from the Stream utility class.

Syntax: server.available()

Parameters: None

Returns: a Client object; if no Client has data available for reading, this object will evaluate to false in an if-statement

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "Network"; // your network SSID (name) char pass[] = "myPassword"; // your network password int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() { // initialize serial: Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } else { server.begin(); Serial.print("Connected to wifi. My address:"); IPAddress myAddress = WiFi.localIP(); Serial.println(myAddress); } }

void loop() { // listen for incoming clients WiFiClient client = server.available(); if (client) {

282

Page 284: Arduino Language Reference

if (client.connected()) { Serial.println("Connected to client"); }

// close the connection: client.stop(); } }

WiFi : Server class

server.begin()

Tells the server to begin listening for incoming connections.

Syntax: server.begin()Parameters: NoneReturns: None

Example

#include <SPI.h> #include <WiFi.h> char ssid[] = "lamaison"; // your network SSID (name) char pass[] = "tenantaccess247"; // your network password int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() { // initialize serial: Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } else { server.begin(); Serial.print("Connected to wifi. My address:"); IPAddress myAddress = WiFi.localIP(); Serial.println(myAddress); } } void loop() { }

283

Page 285: Arduino Language Reference

WiFi : Server class

WiFi Server()

Creates a server that listens for incoming connections on the specified port.

Syntax: Server(port);

Parameters: port: the port to listen on (int)

Returns: None

Example

#include <SPI.h> #include <WiFi.h>

char ssid[] = "myNetwork"; // your network SSID (name) char pass[] = "myPassword"; // your network password int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() { // initialize serial: Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } else { server.begin(); Serial.print("Connected to wifi. My address:"); IPAddress myAddress = WiFi.localIP(); Serial.println(myAddress); } }

void loop() { }

284

Page 286: Arduino Language Reference

WiFi : Server class

server.print()

Print data to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: server.print(data) server.print(data, BASE)

Parameters: data: the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte print() will return the number of bytes written, though reading that number is optional

WiFi : Server class

server.println()

Prints data, followed by a newline, to all the clients connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3').

Syntax: server.println() server.println(data) server.println(data, BASE)

Parameters: data (optional): the data to print (char, byte, int, long, or string)BASE (optional): the base in which to print numbers: DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16).

Returns: byte println() will return the number of bytes written, though reading that number is

optional

WiFi : Server class

server.write()

Write data to all the clients connected to a server.

Syntax: server.write(data)Parameters: data: the value to write (byte or char)Returns: byte : the number of bytes written. It is not necessary to read this.

Example

#include <SPI.h>

285

Page 287: Arduino Language Reference

#include <WiFi.h>

char ssid[] = "yourNetwork"; char pass[] = "yourPassword"; int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() { // initialize serial: Serial.begin(9600); Serial.println("Attempting to connect to WPA network..."); Serial.print("SSID: "); Serial.println(ssid);

status = WiFi.begin(ssid, pass); if ( status != WL_CONNECTED) { Serial.println("Couldn't get a wifi connection"); while(true); } else { server.begin(); } }

void loop() { // listen for incoming clients WiFiClient client = server.available(); if (client == true) { // read bytes from the incoming client and write them back // to any clients connected to the server: server.write(client.read()); } }

286

Page 288: Arduino Language Reference

Wire Library

This library allows you to communicate with I2C / TWI devices. On most Arduino boards, SDA (data line) is on analog input pin 4, and SCL (clock line) is on analog input pin 5. On the Arduino Mega, SDA is digital pin 20 and SCL is 21.

As of Arduino 1.0, the library inherits from the Stream functions, making it consistent with other read/write libraries. Because of this, send() and receive() have been replaced with read() and write().

Functions

- available()- begin()- beginTransmission()- endTransmission()- onReceive()- onRequest()- read()- requestFrom()- write()

Note: There are both 7- and 8-bit versions of I2C addresses. 7 bits identify the device, and the eighth bit determines if it's being written to or read from. The Wire library uses 7 bit addresses throughout. If you have a datasheet or sample code that uses 8 bit address, you'll want to drop the low bit (i.e. shift the value one bit to the right), yielding an address between 0 and 127.

Wire.available()

Returns the number of bytes available for retrieval with receive(). This should be called on a master device after a call to requestFrom() or on a slave inside the onReceive() handler.

available() inherits from the Stream utility class.

Parameters: NoneReturns: The number of bytes available for reading.

Wire.begin()

Initiate the Wire library and join the I2C bus as a master or slave. This should normally be called only once.

Syntax: Wire.begin(address)Parameters: address: the 7-bit slave address (optional); if not specified, join the bus as a master.Returns: None

287

Page 289: Arduino Language Reference

Wire.beginTransmission(address)

Begin a transmission to the I2C slave device with the given address. Subsequently, queue bytes for transmission with the write() function and transmit them by calling endTransmission().

Syntax: Wire.beginTransmission(address)Parameters: address: the 7-bit address of the device to transmit toReturns: None

Wire.endTransmission()

Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().

As of Arduino 1.0.1, endTransmission() accepts a boolean argument changing its behavior for compatibility with certain I2C devices.

If true, endTransmission() sends a stop message after transmission, releasing the I2C bus. If false, endTransmission() sends a restart message after transmission. The bus will not be released, which prevents another master device from transmitting between messages. This allows one master device to send multiple transmissions while in control.

The default value is true.

Syntax: Wire.endTransmission() Wire.endTransmission(stop)

Parameters: stop : boolean. true will send a stop message, releasing the bus after transmission. false will send a restart, keeping the connection active.

Returns: byte, which indicates the status of the transmission:

- 0:success - 1:data too long to fit in transmit buffer - 2:received NACK on transmit of address - 3:received NACK on transmit of data - 4:other error

Wire.onReceive(handler)

Registers a function to be called when a slave device receives a transmission from a master.

Parameters: handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: void myHandler(int numBytes)

Returns: None

288

Page 290: Arduino Language Reference

Wire.onRequest(handler)

Register a function to be called when a master requests data from this slave device.

Parameters: handler: the function to be called, takes no parameters and returns nothing, e.g.: void myHandler()

Returns: None

Wire.read()

Reads a byte that was transmitted from a slave device to a master after a call to requestFrom() or was transmitted from a master to a slave. read() inherits from the Stream utility class.

Syntax: Wire.read()Parameters: noneReturns: The next byte received

Example

#include <Wire.h>

void setup() { Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output }

void loop() { Wire.requestFrom(2, 6); // request 6 bytes from slave device #2

while(Wire.available()) // slave may send less than requested { char c = Wire.read(); // receive a byte as character Serial.print(c); // print the character }

delay(500); }

Wire.receive()

Retrieve a byte that was transmitted from a slave device to a master after a call to requestFrom or was transmitted from a master to a slave.

Parameters: NoneReturns: The next byte received.

289

Page 291: Arduino Language Reference

Wire.requestFrom()

Used by the master to request bytes from a slave device. The bytes may then be retrieved with the available() and read() functions.

As of Arduino 1.0.1, requestFrom() accepts a boolean argument changing its behavior for compatibility with certain I2C devices.

If true, requestFrom() sends a stop message after the request, releasing the I2C bus. If false, requestFrom() sends a restart message after the request. The bus will not be released, which prevents another master device from requesting between messages. This allows one master device to send multiple requests while in control.

The default value is true.

Syntax: Wire.requestFrom(address, quantity) Wire.requestFrom(address, quantity, stop)

Parameters: address: the 7-bit address of the device to request bytes fromquantity: the number of bytes to requeststop : boolean. true will send a stop message after the request, releasing the bus. false will continually send a restart after the request, keeping the connection active.

Returns: None

Wire.send()

Sends data from a slave device in response to a request from a master, or queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission()).

Syntax: Wire.send(value)Wire.send(string)Wire.send(data, quantity)

Parameters: value: a byte to send (byte)string: a string to send (char *)data: an array of data to send (byte *)quantity: the number of bytes of data to transmit (byte)

Returns: None

290

Page 292: Arduino Language Reference

Wire.write()

Writes data from a slave device in response to a request from a master, or queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission()).

Syntax: Wire.write(value) Wire.write(string)

Wire.write(data, length)

Parameters: value: a value to send as a single bytestring: a string to send as a series of bytesdata: an array of data to send as byteslength: the number of bytes to transmit

Returns: bytewrite() will return the number of bytes written, though reading that number is optional

Example

#include <Wire.h>

byte val = 0;

void setup() { Wire.begin(); // join i2c bus }

void loop() { Wire.beginTransmission(44); // transmit to device #44 (0x2c) // device address is specified in datasheet Wire.write(val); // sends value byte Wire.endTransmission(); // stop transmitting

val++; // increment value if(val == 64) // if reached 64th position (max) { val = 0; // start over from lowest value } delay(500); }

291

Page 293: Arduino Language Reference

word()

Convert a value to the word data type or create a word from two bytes.

Syntax: word(x) word(h, l)

Parameters: x: a value of any typeh: the high-order (leftmost) byte of the wordl: the low-order (rightmost) byte of the word

Returns: word

word

A word stores a 16-bit unsigned number, from 0 to 65535. Same as an unsigned int.

Example

word w = 10000;

292

Page 294: Arduino Language Reference

TárgymutatóAbs(x)...................................................................................................................................................5Addition, Subtraction, Multiplication, & Division...............................................................................7AnalogRead().......................................................................................................................................5AnalogReference(type).........................................................................................................................6AnalogWrite().......................................................................................................................................6Arduino/Processing Language Comparison.......................................................................................24Array - creating, declaring ...................................................................................................................8Array, accessing....................................................................................................................................9Arrays...................................................................................................................................................8Assignment operator (=) .....................................................................................................................9Attached().........................................................................................................................................170AttachInterrupt().................................................................................................................................10Begin()................................................................................................................................................11Bit().....................................................................................................................................................12BitClear()............................................................................................................................................12BitRead()............................................................................................................................................12BitSet()...............................................................................................................................................13Bitshift left (<<), bitshift right (>>)....................................................................................................13Bitwise AND (&)...............................................................................................................................14Bitwise NOT (~).................................................................................................................................18Bitwise OR (|).....................................................................................................................................15Bitwise XOR (^).................................................................................................................................16BitWrite()...........................................................................................................................................19Boolean operators - ! (not)..................................................................................................................19Boolean operators - && (logical and)................................................................................................19Boolean operators - || (logical or).......................................................................................................19Break...................................................................................................................................................22Byte.....................................................................................................................................................22Byte()..................................................................................................................................................22Char....................................................................................................................................................23Char()..................................................................................................................................................23Comments...........................................................................................................................................23Compound bitwise AND (&=)...........................................................................................................16Compound bitwise OR (|=).................................................................................................................17Const keyword....................................................................................................................................26Constrain(x, a, b)................................................................................................................................26Continue.............................................................................................................................................27Cos(rad)..............................................................................................................................................27Curly Braces - {} ...............................................................................................................................20DCF77 Library...................................................................................................................................28Decrement (--)....................................................................................................................................82Define (#define)..................................................................................................................................29Defining Digital Pins, INPUT, INPUT_PULLUP, and OUTPUT.....................................................25Defining Logical Levels, true and false (Boolean Constants)............................................................24Defining Pin Levels, HIGH and LOW...............................................................................................25Delay()................................................................................................................................................30DelayMicroseconds()..........................................................................................................................30DetachInterrupt()................................................................................................................................31DigitalRead()......................................................................................................................................31

293

Page 295: Arduino Language Reference

DigitalWrite().....................................................................................................................................32Do - while...........................................................................................................................................33Double................................................................................................................................................33EEPROM Library...............................................................................................................................33EEPROM.read().................................................................................................................................34EEPROM.write()................................................................................................................................34Ethernet client.available()...................................................................................................................38Ethernet client.connect().....................................................................................................................40Ethernet client.connected().................................................................................................................39Ethernet client.flush().........................................................................................................................42Ethernet client.print()..........................................................................................................................42Ethernet client.println()......................................................................................................................43Ethernet client.read()..........................................................................................................................43Ethernet client.stop()..........................................................................................................................43Ethernet client.write().........................................................................................................................44Ethernet Client().................................................................................................................................41Ethernet Ethernet.maintain()..............................................................................................................46Ethernet EthernetServer()...................................................................................................................46Ethernet if (EthernetClient)................................................................................................................56Ethernet IPAddress()..........................................................................................................................44Ethernet library...................................................................................................................................35Ethernet server.available()..................................................................................................................57Ethernet server.begin().......................................................................................................................58Ethernet server.print().........................................................................................................................60Ethernet server.println()......................................................................................................................60Ethernet server.write()........................................................................................................................61Ethernet Server()................................................................................................................................59Ethernet UDP.available()....................................................................................................................47Ethernet UDP.begin().........................................................................................................................48Ethernet UDP.beginPacket()..............................................................................................................49Ethernet UDP.endPacket()..................................................................................................................50Ethernet UDP.parsePacket()...............................................................................................................51Ethernet UDP.read()...........................................................................................................................52Ethernet UDP.remoteIP()...................................................................................................................53Ethernet UDP.remotePort()................................................................................................................54Ethernet UDP.write()..........................................................................................................................55Ethernet: EthernetServer.....................................................................................................................46Ethernet.begin()..................................................................................................................................36Ethernet.localIP()................................................................................................................................45EthernetClient()..................................................................................................................................37Firmata Library...................................................................................................................................62Float....................................................................................................................................................65Float().................................................................................................................................................64For statements.....................................................................................................................................65Functions............................................................................................................................................67GLCD example sketch........................................................................................................................69GLCD Functions................................................................................................................................70GLCD Library....................................................................................................................................69Goto....................................................................................................................................................79HighByte()..........................................................................................................................................79If.........................................................................................................................................................79If / else................................................................................................................................................80

294

Page 296: Arduino Language Reference

Include (#include)...............................................................................................................................81Increment (++) ...................................................................................................................................82Int........................................................................................................................................................84Int().....................................................................................................................................................83Integer Constants................................................................................................................................83Interrupts using...................................................................................................................................10Interrupts()..........................................................................................................................................83Joystick Control..................................................................................................................................99Keyboard Button example..................................................................................................................95Keyboard Modifiers, Tables...............................................................................................................86Keyboard.begin()................................................................................................................................85Keyboard.end()...................................................................................................................................85Keyboard.press()................................................................................................................................87Keyboard.print().................................................................................................................................88Keyboard.println()..............................................................................................................................89Keyboard.release()..............................................................................................................................90Keyboard.releaseAll().........................................................................................................................89Keyboard.write()................................................................................................................................91LCD Library.....................................................................................................................................104Lcd.autoscroll()................................................................................................................................104Lcd.begin().......................................................................................................................................106Lcd.blink()........................................................................................................................................106Lcd.clear().........................................................................................................................................107Lcd.createChar()...............................................................................................................................108Lcd.cursor()......................................................................................................................................109Lcd.display().....................................................................................................................................110Lcd.home().......................................................................................................................................111Lcd.leftToRight()..............................................................................................................................111Lcd.noAutoscroll()...........................................................................................................................111Lcd.noBlink()...................................................................................................................................111Lcd.noCursor().................................................................................................................................111Lcd.noDisplay()................................................................................................................................112Lcd.print().........................................................................................................................................112Lcd.rightToLeft()..............................................................................................................................113Lcd.scrollDisplayLeft()....................................................................................................................113Lcd.scrollDisplayRight()..................................................................................................................114Lcd.setCursor().................................................................................................................................115Lcd.write()........................................................................................................................................116Libraries............................................................................................................................................102LiquidCrystal().................................................................................................................................107Long..................................................................................................................................................117Long()...............................................................................................................................................117Loop()...............................................................................................................................................117LowByte().........................................................................................................................................118Map()................................................................................................................................................118Max(x, y)..........................................................................................................................................119Micros()............................................................................................................................................119Millis()..............................................................................................................................................120Min(x, y)...........................................................................................................................................120Modulo (%)......................................................................................................................................121Mouse and Keyboard example...........................................................................................................93Mouse.begin()...................................................................................................................................122

295

Page 297: Arduino Language Reference

Mouse.click()....................................................................................................................................122Mouse.end()......................................................................................................................................123Mouse.isPressed().............................................................................................................................123Mouse.move()...................................................................................................................................124Mouse.press()...................................................................................................................................126Mouse.release().................................................................................................................................127MouseContinousDrawing Example....................................................................................................96NoInterrupts()...................................................................................................................................131NoTone()..........................................................................................................................................131One-Wire Protocol............................................................................................................................132Other operators (+= , -= , *= , /=).......................................................................................................82Ping...................................................................................................................................................138Ping - NewPing.................................................................................................................................128PinMode().........................................................................................................................................140Pointer operators...............................................................................................................................140Pow()................................................................................................................................................140PROGMEM......................................................................................................................................143PulseIn()...........................................................................................................................................146Random()..........................................................................................................................................147RandomSeed(seed)...........................................................................................................................148Return...............................................................................................................................................148Sd example: CardInfo.......................................................................................................................164Sd example: Datalogger....................................................................................................................161Sd example: DumpFile.....................................................................................................................163Sd file-class: file.available().............................................................................................................153Sd file-class: file.close()...................................................................................................................153Sd file-class: file.flush()...................................................................................................................153Sd file-class: file.isDirectory().........................................................................................................154Sd file-class: file.openNextFile()......................................................................................................155Sd file-class: file.peek()....................................................................................................................156Sd file-class: file.position()..............................................................................................................156Sd file-class: file.print()....................................................................................................................156Sd file-class: file.println().................................................................................................................157Sd file-class: file.read().....................................................................................................................157Sd file-class: file.rewindDirectory().................................................................................................158Sd file-class: file.seek()....................................................................................................................159Sd file-class: file.size().....................................................................................................................159Sd file-class: file.write()...................................................................................................................159SD library.........................................................................................................................................150Sd.begin().........................................................................................................................................150Sd.exists().........................................................................................................................................151Sd.mkdir().........................................................................................................................................151Sd.open()..........................................................................................................................................152Sd.remove()......................................................................................................................................152Sd.rmdir().........................................................................................................................................152Semicolon (;)....................................................................................................................................166Serial.................................................................................................................................................166SerialEvent().....................................................................................................................................167Servo library.....................................................................................................................................169Servo.attach()....................................................................................................................................170Servo.attached()................................................................................................................................170Servo.detach()...................................................................................................................................171

296

Page 298: Arduino Language Reference

Servo.read()......................................................................................................................................171Servo.write().....................................................................................................................................171Servo.writeMicroseconds()...............................................................................................................172Setup()..............................................................................................................................................173ShiftIn()............................................................................................................................................173ShiftOut()..........................................................................................................................................173SimpleSDAudio................................................................................................................................176Sin(rad).............................................................................................................................................181Sizeof................................................................................................................................................181SoftwareSerial Library.....................................................................................................................182SoftwareSerial: available()...............................................................................................................184SoftwareSerial: begin(speed)............................................................................................................184SoftwareSerial: isListening()............................................................................................................185SoftwareSerial: listen().....................................................................................................................186SoftwareSerial: overflow()...............................................................................................................187SoftwareSerial: peek.........................................................................................................................188SoftwareSerial: print(data)...............................................................................................................188SoftwareSerial: println(data)............................................................................................................189SoftwareSerial: read.........................................................................................................................190SoftwareSerial: write(data)...............................................................................................................190SPI - Digital Potentiometer Control.................................................................................................196SPI library.........................................................................................................................................191SPI.begin()........................................................................................................................................197SPI.end()...........................................................................................................................................197SPI.setBitOrder()..............................................................................................................................198SPI.setClockDivider()......................................................................................................................198SPI.setDataMode()...........................................................................................................................198SPI.transfer()....................................................................................................................................199Sqrt(x)...............................................................................................................................................199Static.................................................................................................................................................199Stepper library..................................................................................................................................200Stepper.setSpeed(rpms)....................................................................................................................203Stepper.step(steps)............................................................................................................................203Stepper(steps, pin1, pin2, pin3, pin4)...............................................................................................203Stepper(steps, pin1, pin2).................................................................................................................203Stream...............................................................................................................................................204Stream.available().............................................................................................................................205Stream.find().....................................................................................................................................205Stream.findUntil()............................................................................................................................205Stream.flush()...................................................................................................................................206Stream.parseFloat()..........................................................................................................................206Stream.parseInt()..............................................................................................................................206Stream.peek()....................................................................................................................................207Stream.read()....................................................................................................................................208Stream.readBytes()...........................................................................................................................207Stream.readBytesUntil()...................................................................................................................207Stream.setTimeout().........................................................................................................................208String................................................................................................................................................208String ([ ] (element access))..............................................................................................................221String (+ operator)............................................................................................................................226String (== operator)..........................................................................................................................222String class........................................................................................................................................210

297

Page 299: Arduino Language Reference

String.charAt()..................................................................................................................................221String.compareTo()..........................................................................................................................221String.concat()..................................................................................................................................222String.endsWith().............................................................................................................................224String.equals()..................................................................................................................................224String.equalsIgnoreCase()................................................................................................................224String.getBytes()...............................................................................................................................224String.indexOf()................................................................................................................................225String.lastIndexOf()..........................................................................................................................225String.length()...................................................................................................................................225String.replace().................................................................................................................................226String.setCharAt()............................................................................................................................226String.startsWith()............................................................................................................................227String.substring()..............................................................................................................................227String.toCharArray()........................................................................................................................227String.toLowerCase().......................................................................................................................228String.toUpperCase()........................................................................................................................228String.trim()......................................................................................................................................228String()..............................................................................................................................................223StringAdditionOperator....................................................................................................................211StringAppendOperator.....................................................................................................................213StringCaseChanges...........................................................................................................................215StringCharacters...............................................................................................................................217StringComparisonOperators.............................................................................................................219StringConstructors............................................................................................................................211StringIndexOf...................................................................................................................................212StringLengthTrim.............................................................................................................................213StringReplace...................................................................................................................................216StringStartsWithEndsWith...............................................................................................................218StringSubstring.................................................................................................................................220Switch / case statements...................................................................................................................229Tan(rad)............................................................................................................................................229Time library......................................................................................................................................230Tone()...............................................................................................................................................234U & L formatters................................................................................................................................83Unsigned char...................................................................................................................................234Unsigned int......................................................................................................................................234Unsigned long...................................................................................................................................235Variable scope..................................................................................................................................149Variables...........................................................................................................................................236Void..................................................................................................................................................237Volatile keyword..............................................................................................................................238While loops.......................................................................................................................................239WiFi - client.available()....................................................................................................................267WiFi - client.connect()......................................................................................................................270WiFi - client.connected()..................................................................................................................269WiFi - client.flush()..........................................................................................................................271WiFi - client.print()..........................................................................................................................273WiFi - client.println().......................................................................................................................273WiFi - client.read()...........................................................................................................................273WiFi - client.stop()...........................................................................................................................274WiFi - client.write()..........................................................................................................................274

298

Page 300: Arduino Language Reference

WiFi - server.available()...................................................................................................................282WiFi - server.begin()........................................................................................................................283WiFi - server.print()..........................................................................................................................285WiFi - server.println()......................................................................................................................285WiFi - server.write().........................................................................................................................285WiFi : Client class............................................................................................................................267WiFi example - Chat Server............................................................................................................249WiFi example - ConnectNoEncryption............................................................................................241WiFi example - ConnectWithWEP..................................................................................................243WiFi example - ConnectWithWPA..................................................................................................245WiFi example - Repeating Wifi Web client.....................................................................................261WiFi example - ScanNetworks.........................................................................................................247WiFi example - Web Server............................................................................................................263WiFi example - Web client...............................................................................................................259WiFi example - WiFiTwitterClient..................................................................................................257WiFi library......................................................................................................................................239WiFi Server()....................................................................................................................................284WiFi.begin().....................................................................................................................................266WiFi.BSSID()...................................................................................................................................266WiFi.disconnect().............................................................................................................................274WiFi.encryptionType().....................................................................................................................274WiFi.gatewayIP().............................................................................................................................275WiFi.getSocket()..............................................................................................................................276WiFi.localIP()...................................................................................................................................276WiFi.macAddress()..........................................................................................................................277WiFi.RSSI()......................................................................................................................................278WiFi.scanNetworks()........................................................................................................................279WiFi.SSID()......................................................................................................................................279WiFi.subnetMask()...........................................................................................................................281WiFiClient().....................................................................................................................................271Wire Library.....................................................................................................................................287Wire.available()................................................................................................................................287Wire.begin()......................................................................................................................................287Wire.beginTransmission(address)....................................................................................................288Wire.endTransmission()...................................................................................................................288Wire.onReceive(handler)..................................................................................................................288Wire.onRequest(handler)..................................................................................................................289Wire.read()........................................................................................................................................289Wire.receive()...................................................................................................................................289Wire.requestFrom()..........................................................................................................................290Wire.send().......................................................................................................................................290Wire.write()......................................................................................................................................291Word.................................................................................................................................................292Word()..............................................................................................................................................292

Összeállította: Solti Imre 2012

299