Arduino Manual v7

Embed Size (px)

Citation preview

  • 7/29/2019 Arduino Manual v7

    1/21

    Arduino Manual

    For Hanze Institute ofTechnology's

    International Challenge

  • 7/29/2019 Arduino Manual v7

    2/21

    Introduction

    Arduino is a micro controller platform that is gaining more and morepopularity, because of it's many advantages compared to other micro

    controllers. Some of this advantages are that it's cheap, it can run on everyOperating System (OS), it's programing environment is simple and easy tounderstand, and last but not least, it's open source. This means there are noadditional costs after buying the board itself. One of the main reasons that theArduino and it's standard programing environment was chosen for thisproject is that the programing language is C based. We assume that it wouldbe easier for you to find additional information regarding programing and inthe best case you already know how to program in C, C# or C++.

    This manual is split up into four parts:

    The Platform's Hardware (Page 2) In that section there is an explanation ofhow to use the board and additional information regarding the hardwarearound the project.

    Arduino Software (Page 3) In this section, the specifics of the Arduinosoftware are explained. Like where to download it from, how to set it up and

    some of the most basic control commands.

    Crash Course in C Programing (Page 8) This part will explain more indepth about how to use C and some useful commands in it that will help youwith your project. If you know C please feel free to skip this part.

    Sensors, Servos and LEDs (Page 16) In the last section you can find moretechnical information regarding the provided sensors. How to use them in the

    real world and how to connected to your Arduino. In this section informationabout LEDs and servos is included as well.

    Here we go. Good luck!

    1

  • 7/29/2019 Arduino Manual v7

    3/21

    The Platform's Hardware

    The Arduino platform is based on Atmel's ATMEGA8 and ATMEGA168. The integrated

    circuit that you see in the center is the micro controller itself. The Arduino board

    provides easy access to the controller trough an USB connection, 13 digital ports and 6

    analog inputs. The Arduino platform provides stable power as well for the controllerfrom USB or an externally connected battery. In addition the board has a very usefulrestart button, that when pressed that the micro controller starts executing your program

    from the beginning.

    In the provided set there is another board called a shield. The idea behind Arduino

    shields is that they provide a specific functionality and being modular at the same time.

    It's possible to put many of them on top of each other, however in practice you'llprobably need one or two. The shield provided is used to make your life of connecting

    sensors and servo motors to the board easier. All active sensors need a minimum of threepins: Signal, Power,and Ground ( White, Red and Black ) . Once connected the shieldprovides every Arduino pin from 0 to 13 with such a configuration, and all you need to

    do is make sure you're connecting the right sensor in the right place and in the right way.

    LCD is a simple 16x2 display. This means you can display up to 16 characters in two

    lines. This display is commonly used with micro controllers, because it has an integratedmicro controller on its own to make it easier to connect. Arduino has a special library

    that makes this display even easier to operate. In the back there is a one page description

    of how to connect it to the Arduino board.

    When you first get the Arduino and power it on. The starting program that is on it makes

    the LED on pin 13 blink. If you see this than the board is functioning properly and youcan start working with it. Keep in mind that when you are uploading a program to it, the

    USB cable should not be disconnected, because you may cause a big mess that is really

    hard to fix. In case you want to use a power supply other than the USB, you can use a9V battery or up to a 12V power supply. Arduino is capable of working with anything

    from 5V to 34V, however under 7V there might be problems with powering sensors and

    motors and over 12V the board will start to heat up.

    2

  • 7/29/2019 Arduino Manual v7

    4/21

    Arduino Software

    The Environment

    The Arduino programing environment can be downloaded for free from the following

    link: http://arduino.cc/en/Main/Software.

    Once you have it installed and runningyou can access many different things

    that will help you to start working right

    away. From File>Examples you canfind simple programs for many

    different functionalities of the board. Agood idea before you start with your

    main project, is to check them out and

    play around with them. Modify them abit to get a feel for it.

    In Sketch>Import Library is an othervery useful function of the

    environment. Since Arduino is an open

    source platform you have access toother peoples work. That work is

    summarized in libraries that you can

    use in your program to make your lifeeasier. The two libraries that you are

    most likely to use are the Servo and

    LiquidCrystal. Servo will provide youwith functions to easily control a servo motor and to rotate it to specific degrees.

    LiquidCrystal you can use to represent your data with the help of the LCD provided.

    Tools>Serial Monitor is used to check if your program is running properly. You can

    easily create outputs and observed them there. This will be covered in a moment.Arduino has many different modifications and the this programing environment is

    designed to work with all of them. So from Tools>Board you can choose, which board

    you are using. When you start programing be sure to select Arduino Uno.

    When you have more than one board connected at the same time you will have to use

    Tools>Serial Port. This will select the port to which the Arduino, you want to program,is connected.

    3

    http://arduino.cc/en/Main/Softwarehttp://arduino.cc/en/Main/Software
  • 7/29/2019 Arduino Manual v7

    5/21

    The play button on the panel is used to verify your program. It checks

    if there are mistakes in your code. You should use this quite often,

    because if you write your whole program and then verify it once and you have errorsyou may get in trouble. The environment is not always clear of what the problem is so if

    you debug more often, it will be easier to correct the problems.

    The other button that you are going to be using often is the arrow pointing to the right.This is used to upload your program to the micro controller. While uploading it is bestnot to stop, however if you wish to stop it is better to press the stop button next to the

    play, rather than unplugging or closing the program.

    Last advice regarding the menu is to save as often as possible. Computers are not

    perfect. They crash, restart, bug, lag and all sorts of things. It is a good practice to save

    every few lines so you don't have problems if something bad happens.

    The Structure

    The structure of your programs is fairly simple. In the beginning of your code you will

    have the included libraries, the variables that you are going to use in your wholeprogram, constants and functions. More information on this is in the C programing

    section.

    The Arduino code is divided into to major parts: void setup() and void loop(). In the

    setup you can select which pins are going to be used for sensors and which for servos

    and LEDs. You can also initialize variables there. The thing you should keep in mindabout the Setup is that it is executed only once at the start of your program.

    The Loop function is the heart of your program. The commands there will be executed

    from top to bottom and start again. Almost all applications for micro controllers require

    them to run constantly. When programing keep in mind this loop and use it to youradvantage.

    Example: In the blink program we are going to see later, the commands just say for the

    LED to turn on and then off. Since the main loop repeats itself constantly the result is ablinking LED.

    4

  • 7/29/2019 Arduino Manual v7

    6/21

    Arduino Specific Commands

    To begin with, we are going to observe the simplest of all Arduino programs and the onethat is running right now on every new plugged in board.

    void setup() {// initialize the digital pin as an output.// Pin 13 has an LED connected on most Arduino boards:pinMode(13, OUTPUT);

    }

    void loop() {digitalWrite(13, HIGH); // set the LED ondelay(1000); // wait for a seconddigitalWrite(13, LOW); // set the LED offdelay(1000); // wait for a second

    }

    All lines, in which there is //, there are comments afterwards. These comments speak

    for themselves.

    In the Void setup() it is said that pin 13 is going to be used as an output. Since pin 13

    does not change its function, and most probably neither will any of your pins, it is

    defined in the void setup().

    The command digitalWrite(pin,state); is used to set the output to either high(on) or

    low(off).The only other command in this program is delay(time); it is used tell the micro

    controller to do nothing. The value is 1000, because the function uses milliseconds

    instead of seconds. In micro controllers things happen fast and for the Arduino onesecond is a long period of time.

    Next are described several other very useful commands for control.

    digitalRead(pin) returns the current state of an input pin.As the digitalWrite(pin) first needs the given pin to be defined as OUTPUT digital

    Read requires the pin to be defined as an INPUT.

    Example:if (digitalRead(10) == 0) then{

    Something happens...}

    5

  • 7/29/2019 Arduino Manual v7

    7/21

    analogRead(analog pin); returns the current state of an analog inputpin from 0 to 5. This value is an integer between 0 and 1024 that

    represents a voltage between 0V and 5V. This gives a sensitivity of

    4.8mV. Since most sensors give an analog output you will be using this command toread their values.

    Example:if (analogRead(3)

  • 7/29/2019 Arduino Manual v7

    8/21

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

    }

    void loop() {int sensorValue = analogRead(A0);Serial.println(sensorValue, DEC);

    }

    Serial.begin(9600); starts the procedure, it sets the speed of the connections to 9600

    bits per second. This is the most commonly used speed so better stick with it. It needs tobe executed once so it is placed in the setup(). Serial.println(value,format); is used

    to write information on the serial monitor. The value can be a an integer, double or

    string, it's up to you. The format is used to tell the program how to represent it. Inintegers for example you can say if you want the output in binary, decimal or

    hexadecimal.

    For output you will have available LCD, so the serial monitor will be better used for

    debugging purposes. The explanation of the LCD you can find in the end and the library

    to use it is integrated in the environment.

    Keep in mind that there are many more functions that you can use in your program. This

    description is intended to give you a head start into the material. It should in no case beyour only source of information about the programing. To see a full list of them with

    more detailed explanations please visit http://arduino.cc/en/Reference/HomePage. In this

    link are described all functions and on the site itself you can find more informationabout libraries as well.

    7

    http://arduino.cc/en/Reference/HomePagehttp://arduino.cc/en/Reference/HomePage
  • 7/29/2019 Arduino Manual v7

    9/21

    Crash Course in C

    Programing is not something that can be described in a short manual. There are whole

    books on the subjects, so this is not even scratching the surface. In the references given

    here the function main() is used. For you this will most likely represent loop()

    Example programs

    The following are simple examples to get things started. They do not do anything useful, but theyillustrate some key characteristics of C.

    /* this is a comment */main() /* function definition */{ /* start of block */

    printf("Hello world\n"); /* output; statement ends with a semicolon *//* use '\n' in printf to get a linefeed */

    } /* end of block */

    Things to note in example programs:

    comments cannot be nested.

    main() is the function where the program begins execution, and can only occur once.

    C is case specific.

    all white space (spaces, tabs, blank lines, comments) is equivalent to one space.

    VariablesAll variables must be declared and defined before they can be used. Variable names can be composedof characters, digits, and the underscore character ( _), and can usually be up to 32 characters long.Variable names should not begin with an underscore---these names are used by the compiler and thelibraries.

    Variables have specific types and usage; basic data types:

    char: a single byte, used for one character

    can specify signed or unsigned, although signed is preferred for compatibility with int

    int: integers

    can modify with short or longcan specify signed or unsigned

    float: single precision floating point (real) number

    double: double precision floating point number

    void: no type value, for pointers and functions

    8

    http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html#http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html#
  • 7/29/2019 Arduino Manual v7

    10/21

    /*** definition of constants ***/main(){

    char c = 'x';char c1 = '0'; /* the character 'zero', with the integer value for ASCII(0) */char c2 = '\0'; /* has the "integer" value zero */

    int n = 10;int n_oct = 065; /* octal */

    int n_hex = 0x3d; /* hexadecimal */

    long m = 10L;unsigned int k = 304U;unsigned long l = 3040UL;

    float x1 = 143.0;float x2 = 24.6e-3;double y = 34.1L;

    }

    Keywords and Operators: The C Language

    C has a small set of keywords; all are used to either declare data types or control the flow of theprogram. See table 1 below for a list of the keywords. The C operators are listed in Table 2 at the end ofthe chapter.

    Table 1: Keywords (K & R, p. 192)

    Data Type Declarations Control Flow Statements

    auto float long static unsigned break do if

    char enum register struct void case else return

    const extern short typedef volatile continue for switch

    double int signed union default goto while

    Basic Operators

    Some basic operators are

    arithmetic operators

    *, / , %, +, -

    % is called modulus division (remainder)

    logical operators

    , =, ==, !=, &&, ||

    the logical operators return a 1 (true) or 0 (false)

    for any conditional test, any non-zero value is true and a 0 is false

    == is the equality comparison ( not =)

    != not equal to

    &&, || logical AND and OR operators

    9

  • 7/29/2019 Arduino Manual v7

    11/21

    A common error is using the assignment operator = when thelogical operator == is required, e.g. (x = 2) instead of (x == 2); bothare valid expressions, so the compiler will not indicate an error.

    assignment operators

    =, +=, -=, *=, /=, %= !

    op= assignment, E1 op=E2 E1=E1 op (E2), with E1 evaluated once

    for example, x+=2 ==>x=x+2

    increment/decrement by 1, as a prefix or postfix++, --

    prefix: increments the variable and gives the new value as the result

    postfix: gives the old value as the result and then increments the variable

    negation

    !

    !(0) ==> 1

    !(any non-zero value) ==> 0

    conditional, compact if-else as an expression instead of a statement

    ?

    (type)

    casts object into a different type

    , (comma)

    combines separate expressions into one

    evaluates them from left to right

    the value of the whole expression is the value of the right most sub-expression

    Examples of Conditional Operators

    Expressions and Statements

    Expressions include variable names, function names, array names, constants, function calls, array

    references, and structure references. Applying an operator to an expression is still an expression, and anexpression enclosed within parentheses is also an expression. An lvalue is an expression which may beassigned a value, such as variables.i++ x+y z = x+y

    A statement is

    a valid expression followed by a semicolon

    a group of statements combined into a block by enclosing them in braces {}. This is thentreated as a single statement.

    a special statement (break, continue, do, for, goto, if, return, switch, while,} and the nullstatement)

    A statement can be labeled, for use with goto. Since goto disrupts structured control flow,however, it is not generally recommended.

    10

  • 7/29/2019 Arduino Manual v7

    12/21

    Control Flow

    Basic control flow is governed by the if..else, while,do...while, andfor statements.

    Decision Making

    Use the if...else for conditional decisions. (exp is any valid expression, statementis any valid

    statement) Syntax:

    if (exp)statement

    if (exp)

    statementelse

    statementif (exp1)

    statementelse if (exp2)

    statement...

    elsestatement

    Looping

    while: testing at the beginning of the loop

    do...while: testing at the end of the loop, after executing the loop at least once

    for: almost the same as while, in a compact form

    Syntax:

    while (exp){

    statement}

    do{

    statement} while (exp);

    for (exp1-opt ; exp2-opt ; exp3-opt){statement

    }

    Here exp-optis an optional expression.

    11

  • 7/29/2019 Arduino Manual v7

    13/21

    Other Control Flow

    Other program control flow is governed by the switch statement, which allowscomparison to a series of constant values, and the goto, continue, break,and return statements.

    Syntax:

    switch(exp){

    case (const-exp):statement-optbreak;

    case (const-exp):statement-optstatement-optbreak;

    .

    .

    .default:

    statement-optbreak;

    }

    The C Preprocessor

    Two essential preprocessor commands are #define and #include. Constants and macros aredefined with #define. The program can be split into separate files and combined with #include,and header files can also be inserted. (See sections 2.6 and 2.7)

    #include #include

    #include "functions.c"

    #define MAX 10#define TRUE 1#define FALSE 0

    Basic StructureThe syntax for declaring a function is

    return-type function-name (argument declarations){

    local variable declarations

    statements}

    The function prototype is a declaration and is needed if the function is defined after its use in theprogram. The syntax is

    return-type function-name (argument declarations);

    12

  • 7/29/2019 Arduino Manual v7

    14/21

    where the argument declarations must include the types of the arguments,but the argument names are optional. If the function is defined before itsuse, then a prototype is not necessary, since the definition also serves as adeclaration.

    If the return-type is omitted, int is assumed. If there are no argument declarations, use void, not emptyparentheses.

    Here are four examples of how functions can be used:A function that has no arguments and does not return a value:

    void print_message(void){

    printf("hello\n");}

    main(){

    print_message();}

    A function that takes an argument. The arguments are separated by commas; the order in whichthey are evaluated is unspecified. The value of each argument is passed to the correspondingparameter of the function.

    void print_integer(int i){

    printf("i = %d\n", i);}

    main(){

    int n=5;

    print_integer(n);}

    A function that returns a value:

    int input_integer(void); /** function prototype declarations **/main(){

    int x, y, z;x = input_integer();y = input_integer();printf("the sum is %d\n", z=x+y);

    }

    int input_integer(void){int a;do{

    printf("input a positive integer: ");scanf("%d", &a);

    } while (a

  • 7/29/2019 Arduino Manual v7

    15/21

    A function that takes an argument m and returns a value:

    main(){

    int x, y, z=100;int input_integer_le_n(int n); /** prototype declaration can be **/

    /** inside a function **/x = input_integer_le_n(z);y = input_integer_le_n(z);printf("the sum is %d\n", x+y);

    }

    int input_integer_le_n(int n){

    int a;do

    {printf("input a positive integer less than %d: ", n);scanf("%d", &a);

    } while (an);return a;

    }

    Return Statement

    A function can return a value of any type, using the return statement,

    Syntax:return exp;return (exp);return;

    The return statement can occur anywhere in the function, and will immediately end that function andreturn control to the function which called it. If there is no return statement, the function will continueexecution until the closing of the function definition, and return with an undefined value.

    The type of the expression returned should match the type of the function; C will automatically try toconvert exp to the return-type.

    Arrays

    An array is a contiguous space in memory which holds a certain number of objects of one type. Thesyntax for array declarations is

    type array-name[const-size];static type array-name[const-size] = initialization-list;static type array-name[] = initialization-list;

    14

  • 7/29/2019 Arduino Manual v7

    16/21

    An array of 10 integers is declared as

    int x[10];with index values from 0 to 9.

    A static array can be initialized:

    static int x[5] = 7,23,0,45,9;

    static int x[] = 7,23,0,45,9;

    static int x[10] = 7,23,0,45,9,0,0,0,0,0;static int x[10] = 7,23,0,45,9;

    where the remaining five elements of x[10] will automatically be 0. Part of the array can be passedas an argument by taking the address of the first element of the required subarray (using &), so &x[6]is an array with 4 elements.

    Strings

    Strings are simply character arrays, or more accurately, pointers to characters. A string literal isenclosed within quotes,"...", and is an array with those characters and `0' at the end, so "hello"{'h','e','l','l','o','\0'}. The string can be defined as

    static char *p = "hello"

    An example illustrating the use of pointers with the string copies one string into another:

    main(){

    char *t = "hello", s[100];void strcpy(char *, char *);strcpy(s,t);printf("%s\n", s); /** will print 'hello' **/

    }

    /** strcpy: copy t to s; pointer version 2 (K&R, p 105) **/

    void strcpy(char *s,char *t){

    while (*s++ = *t++) /** OR while ((*s++ = *t++) != '\0') **/;

    }

    For more information and the full crash course please visit:http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html

    15

    http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.htmlhttp://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.html
  • 7/29/2019 Arduino Manual v7

    17/21

    Sensors, Servos and LEDs

    PIR Sensor

    The Passive Infra-Red sensor is used to that detect motion by measuring changes in

    the infrared levels emitted by surrounding objects . This motion can be detected bychecking for a high signal on a single output. This sensor should be used with a digital

    pin on the Arduino and pin mode Input. It may use the standard connection white, redand black, respectively signal, power and ground. To be sure check the text around the

    connecter.

    The PIR sensor has an approximate range of 6 meters. After starting it needs 10-60

    second to adjust to the environment, while there is as little movement as possible. Thesensor is designed to adjust to slowly changing conditions that would happen normally

    as the day progresses and the environmental conditions change, but responds by making

    its output high when sudden changes occur, such as when there is motion.

    The jumper on the sensor is used to change between two possible modes of output.

    When the jumper is in the high position movements in a short period of time result in astable high output. If the sensor goes idle the output goes into a low state. In case the

    jumper is in a low position, movements result in a short flicker of the output to high and

    then low.

    Medium range IR distance sensor

    The distance sensor is able to judge a

    distance between 10 and 80cm. It usesthe standard sensor connections. Since

    the output is a voltage between 0.5V

    and 3.5V it should be connected to ananalog input of the Arduino board.

    It is capable of working with objects of

    different color. This is the output todistance graph of the sensor:

    16

  • 7/29/2019 Arduino Manual v7

    18/21

    Short range IR distance sensor

    As the sensor mentioned before this one uses infra-redlight to judge a distance. This one however, has a

    shorter range, up to 10cm on reflective surfaces and

    5cm for example for a hand. If the output of the analog

    pin is below 100 then the object is further than 10cm.

    Precision Temperature Sensor

    The temperature sensor is capable of measuringambient temperatures from -30C to +80C. It should

    be connected to an analog input using the standardcolor cable. The raw data output might not be suitablefor real world applications so use the following formula

    to convert the ram data into degrees Celsius:

    Temperature (C) = (SensorValue x 0.2222) 61.111

    Light Sensor

    The light sensor is capable to measure human perceptible

    light level in lux . The light sensor should be connected toan analog input using the standard color cable.

    A good quality of this sensor is that its output is directly in auseful in a real world application, because the raw sensor

    value corresponds to the light intensity in lux.

    17

  • 7/29/2019 Arduino Manual v7

    19/21

    Servos

    The servos can rotate to a given angle based on an impulse input onit's control pin. It should be connected using its color coded cable to a digital PWM pin.

    In this case the colors are yellow, red and brown, and they respectively represent

    signal,power and ground.

    Thankfully the Arduino environment has a library for easily controlling servo motors.

    Here is an example:#include

    Servo myservo; // create servo object to control a servo

    int potpin = 0; // analog pin used to connect the potentiometerint val; // variable to read the value from the analog pin

    void setup()

    {myservo.attach(9); // attaches the servo on pin 9 to the servo object

    }void loop(){val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)myservo.write(val); // sets the servo position according to the scaled valuedelay(15); // waits for the servo to get there

    }

    In this example a potentiometer is used to control the servo, however in your case you

    can use a sensor value as the input. In case you can connect several servos at the sametime you need to create on other object by executing the comand Servo name; with a

    different name then the previous one.

    As stated before the Arduino is an open source platform, so there are easily availableexamples and tips for using servos. Yet again a good source would be:

    http://arduino.cc/en/Reference/Servo

    18

    http://arduino.cc/en/Reference/Servohttp://arduino.cc/en/Reference/Servo
  • 7/29/2019 Arduino Manual v7

    20/21

    LEDs

    Light Emitting Diodes are very simple and easy to use. Unlike lightbulbs they have to be connected in a specific way. The positive leg of the LED (called

    anode) is the longer one and it should be connected to the output of the Arduino board.

    The shorter leg (called cathode) can be connected to ground

    using a resistor between 330 and 510. The resistor valuedecides the intensity of the LED and 470 is the mostcommonly used. The resistor can be connected trough

    either leg of the LED.

    You can connect two LEDs in series by connecting the

    cathode of one of the LED to the anode of the other one. A

    resistor is still needed, however it is best to use a lowervalue resistor so that the LEDs are still bright. In the case of three you don't need a

    resistor, but for more an additional circuit is required. Although you probably would notneed to connect more, information on how to execute this can be found online.

    References:

    http://arduino.cc/en/http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.htmlhttp://www.phidgets.com/http://content.solarbotics.com/products/datasheets/pirsensor-v1.2.pdfhttps://www.sparkfun.com/products/8959

    19

    http://arduino.cc/en/http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.htmlhttp://www.phidgets.com/http://arduino.cc/en/http://www.mattababy.org/~belmonte/Teaching/CCC/CrashCourseC.htmlhttp://www.phidgets.com/
  • 7/29/2019 Arduino Manual v7

    21/21

    20