Anda di halaman 1dari 21

Arduino Manual

For Hanze Institute of Technology's International Challenge

Introduction
Arduino is a micro controller platform that is gaining more and more popularity, because of it's many advantages compared to other micro controllers. Some of this advantages are that it's cheap, it can run on every Operating System (OS), it's programing environment is simple and easy to understand, and last but not least, it's open source. This means there are no additional costs after buying the board itself. One of the main reasons that the Arduino and it's standard programing environment was chosen for this project is that the programing language is C based. We assume that it would be easier for you to find additional information regarding programing and in the 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 of how to use the board and additional information regarding the hardware around the project. Arduino Software (Page 3) In this section, the specifics of the Arduino software 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 in depth about how to use C and some useful commands in it that will help you with 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 more technical information regarding the provided sensors. How to use them in the real world and how to connected to your Arduino. In this section information about LEDs and servos is included as well. Here we go. Good luck!

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 controller from USB or an externally connected battery. In addition the board has a very useful restart 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'll probably 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 three pins: Signal, Power,and Ground ( White, Red and Black ) . Once connected the shield provides 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 integrated micro 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 you can 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 a 9V 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.

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 running you can access many different things that will help you to start working right away. From File>Examples you can find simple programs for many different functionalities of the board. A good idea before you start with your main project, is to check them out and play around with them. Modify them a bit to get a feel for it. In Sketch>Import Library is an other very useful function of the environment. Since Arduino is an open source platform you have access to other peoples work. That work is summarized in libraries that you can use in your program to make your life easier. The two libraries that you are most likely to use are the Servo and LiquidCrystal. Servo will provide you with 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

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 errors you 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 best not 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 whole program, 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 mind about 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 your advantage. 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 a blinking LED.

Arduino Specific Commands


To begin with, we are going to observe the simplest of all Arduino programs and the one that 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 on delay(1000); // wait for a second digitalWrite(13, LOW); // set the LED off delay(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 one second 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

analogRead(analog pin); returns the current state of an analog input pin 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 to read their values.

Example:
if (analogRead(3) <= 500) then{ Something happens... }

analogWrite(PWM pin,value); is used to set one of the PWM pins of the Arduino to a given value. Although, the function says analog this is not a true analog output. PWM is basically a very quick change in the output between 0V and 5V, which results in an average voltage between the two. The value can be anywhere between 0 and 255, which tells the micro controller how long must the pin be on and how much off. 0 is always off and 255 is always on. For example if the value is set to 128 the pin will be 50% of the time on and 50% of the time off, resulting in an average voltage of 2.5V millis() and micros() is a function that returns the amount of time since the microcontroller has been on. These are useful functions to use if you want to create time sensitive actions and do something else in the meantime. Example, you want your program to check a given input every 2 seconds, while it does something else:
if ( ( ( millis()%2000) <= 1 ) && ( (millis()%2000) >=99 ) then{ Something happens every two seconds.... } Something happens in the meantime...

To elaborate, ( millis()%2000) divides the time has past since the board started, by 2000 (2 seconds) and gives the remainder. In a perfect world we would check if that is 0 and thus 2 seconds have past, however the program may not come at this code at the exact time. Thus an error range of 40 milliseconds is placed. Based on the size of your program and the presents of delays that time might has to be bigger. Serial.* is used to print information on the serial monitor. Keep in mind that if you want to use this function pins 0 and 1 must be free. Here is a short example:
6

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 to be 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. In integers 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 be your 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 information about libraries as well.

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 they illustrate some key characteristics of C.
/* this is a comment */ main() { printf("Hello world\n"); } /* /* /* /* /* function definition */ start of block */ 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.

Variables
All variables must be declared and defined before they can be used. Variable names can be composed of 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 the libraries. 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 long can 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

/*** 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 the program. See table 1 below for a list of the keywords. The C operators are listed in Table 2 at the end of the chapter. Table 1: Keywords (K & R, p. 192) Data Type Declarations Control Flow Statements auto char const float long static unsigned break void case continue default do else for if return switch enum register struct extern short signed union

typedef volatile

double int Basic Operators Some basic operators are

goto while

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

A common error is using the assignment operator = when the logical operator == is required, e.g. (x = 2) instead of (x == 2); both are 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 an expression enclosed within parentheses is also an expression. An lvalue is an expression which may be assigned 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 then treated as a single statement. a special statement (break, continue, do, for, goto, if, return, switch, while,} and the null statement) A statement can be labeled, for use with goto. Since goto disrupts structured control flow, however, it is not generally recommended.

10

Control Flow
Basic control flow is governed by the if..else, while,do...while, and for statements.

Decision Making
Use the if...else for conditional decisions. (exp is any valid expression, statement is any valid statement) Syntax:
if (exp) statement if (exp) statement else statement if (exp1) statement else if (exp2) statement . . . else statement

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) { } do { statement } while (exp); for (exp1-opt ; { } exp2-opt ; statement exp3-opt) statement

Here exp-opt is an optional expression.

11

Other Control Flow


Other program control flow is governed by the switch statement, which allows comparison to a series of constant values, and the goto, continue, break, and return statements. Syntax:
switch(exp) { case (const-exp): statement-opt break; case (const-exp): statement-opt statement-opt break; . . . default: statement-opt break; }

The C Preprocessor
Two essential preprocessor commands are #define and #include. Constants and macros are defined 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 <stdio.h> #include <math.h> #include "functions.c" #define MAX 10 #define TRUE 1 #define FALSE 0

Basic Structure
The 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 the program. The syntax is return-type function-name (argument declarations);

12

where the argument declarations must include the types of the arguments, but the argument names are optional. If the function is defined before its use, then a prototype is not necessary, since the definition also serves as a declaration. If the return-type is omitted, int is assumed. If there are no argument declarations, use void, not empty parentheses. 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 which they are evaluated is unspecified. The value of each argument is passed to the corresponding parameter 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 <= 0); return a; }

13

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


main() { int x, y, z=100; int input_integer_le_n(int n); x = input_integer_le_n(z); y = input_integer_le_n(z); printf("the sum is %d\n", x+y);

/** prototype declaration can be **/ /** inside a function **/

int input_integer_le_n(int n) { int a; do { printf("input a positive integer less than %d: ", n); scanf("%d", &a); } while (a<=0 || a>n); 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 and return control to the function which called it. If there is no return statement, the function will continue execution 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 to convert exp to the return-type.

Arrays
An array is a contiguous space in memory which holds a certain number of objects of one type. The syntax for array declarations is type array-name[const-size]; static type array-name[const-size] = initialization-list; static type array-name[] = initialization-list;

14

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 passed as 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 is enclosed 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); } /** strcpy: copy t to s; pointer version 2

/**

will print 'hello' **/

**/

(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

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 by checking 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, red and 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. The sensor 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 a stable 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 uses the standard sensor connections. Since the output is a voltage between 0.5V and 3.5V it should be connected to an analog input of the Arduino board. It is capable of working with objects of different color. This is the output to distance graph of the sensor:

16

Short range IR distance sensor


As the sensor mentioned before this one uses infra-red light 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 measuring ambient temperatures from -30C to +80C. It should be connected to an analog input using the standard color cable. The raw data output might not be suitable for 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 to an analog input using the standard color cable. A good quality of this sensor is that its output is directly in a useful in a real world application, because the raw sensor value corresponds to the light intensity in lux.

17

Servos
The servos can rotate to a given angle based on an impulse input on it'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.h> Servo myservo; // create servo object to control a servo int potpin = 0; // analog pin used to connect the potentiometer int 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 value delay(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 same time 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 available examples and tips for using servos. Yet again a good source would be: http://arduino.cc/en/Reference/Servo

18

LEDs
Light Emitting Diodes are very simple and easy to use. Unlike light bulbs 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 value decides the intensity of the LED and 470 is the most commonly 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 lower value 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 not need 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.html http://www.phidgets.com/ http://content.solarbotics.com/products/datasheets/pirsensor-v1.2.pdf https://www.sparkfun.com/products/8959

19

20

Anda mungkin juga menyukai