Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas

Introdução à Programação Arduino: Estruturas de Controle e Variáveis, Notas de estudo de Engenharia Elétrica

As estruturas básicas da linguagem de programação arduino, incluindo o uso de arrays, variáveis e estruturas de controle como for e if. Além disso, fornece exemplos e códigos para ilustrar a sintaxe e utilização de cada elemento. Recomenda-se aos interessados em detalhes consultarem 'the c programming language' de kernighan e ritchie e 'c in a nutshell' de prinz e crawford.

Tipologia: Notas de estudo

2013
Em oferta
40 Pontos
Discount

Oferta por tempo limitado


Compartilhado em 18/06/2013

tobias-tavares-de-luna-11
tobias-tavares-de-luna-11 🇧🇷

5

(4)

10 documentos

1 / 36

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
arduino
programming
notebook
brian w. evans
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
Discount

Em oferta

Pré-visualização parcial do texto

Baixe Introdução à Programação Arduino: Estruturas de Controle e Variáveis e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity!

arduino

programming

notebook

brian w. evans

Arduino Programming Notebook Written and compiled by Brian W. Evans

With information or inspiration taken from: http://www.arduino.cc http://www.wiring.org.co http://www.arduino.cc/en/Booklet/HomePage http://cslibrary.stanford.edu/101/

Including material written by: Paul Badger Massimo Banzi Hernando Barragán David Cuartielles Tom Igoe Daniel Jolliffe Todd Kurt David Mellis and others

Published: First Edition August 2007 Second Edition September 2008

12c bao

This work is licensed under the Creative Commons Attribution-Share Alike 2.5 License.

To view a copy of this license, visit:

http://creativecommons.org/licenses/by-sa/2.5/

Or send a letter to:

Creative Commons 171 Second Street, Suite 300 San Francisco, California, 94105, USA

  • structure structure
  • setup()
  • loop()
  • functions
  • {} curly braces
  • ; semicolon
  • /*… */ block comments
  • // line comments
  • variables variables
  • variable declaration
  • variable scope
  • byte datatypes
  • int
  • long
  • float
  • arrays
  • arithmetic arithmetic
  • compound assignments
  • comparison operators
  • logical operators
  • constants constants
  • true/false
  • high/low
  • input/output
  • if flow control
  • if… else
  • for
  • while
  • do… while
  • pinMode(pin, mode) digital i/o
  • digitalRead(pin)
  • digitalWrite(pin, value)
  • analogRead(pin) analog i/o
  • analogWrite(pin, value)
  • delay(ms) time
  • millis()
  • min(x, y) math
  • max(x, y)
  • randomSeed(seed) random
  • random(min, max)
  • Serial.begin(rate) serial
  • Serial.println(data)
  • digital output appendix
  • digital input
  • high current output
  • pwm output
  • potentiometer input
  • variable resistor input
  • servo output

preface

This notebook serves as a convenient, easy to use programming reference for the command structure and basic syntax of the Arduino microcontroller. To keep it simple, certain exclusions were made that make this a beginner’s reference best used as a secondary source alongside other websites, books, workshops, or classes. This decision has lead to a slight emphasis on using the Arduino for standalone purposes and, for example, excludes the more complex uses of arrays or advanced forms of serial communication.

Beginning with the basic structure of Arduino's C derived programming language, this notebook continues on to describe the syntax of the most common elements of the language and illustrates their usage with examples and code fragments. This includes many functions of the core library followed by an appendix with sample schematics and starter programs. The overall format compliments O’Sullivan and Igoe’s Physical Computing where possible.

For an introduction to the Arduino and interactive design, refer to Banzi’s Getting Started with Arduino , aka the Arduino Booklet. For the brave few interested in the intricacies of programming in C, Kernighan and Ritchie’s The C Programming Language, second edition, as well as Prinz and Crawford’s C in a Nutshell, provide some insight into the original programming syntax.

Above all else, this notebook would not have been possible without the great community of makers and shear mass of original material to be found at the Arduino website, playground, and forum at http://www.arduino.cc.

structure | 7

structure

The basic structure of the Arduino programming language is fairly simple and runs in at least two parts. These two required parts, or functions, enclose blocks of statements.

void setup() { statements; }

void loop() { statements; }

Where setup() is the preparation, loop() is the execution. Both functions are required for the program to work.

The setup function should follow the declaration of any variables at the very beginning of the program. It is the first function to run in the program, is run only once, and is used to set pinMode or initialize serial communication.

The loop function follows next and includes the code to be executed continuously – reading inputs, triggering outputs, etc. This function is the core of all Arduino programs and does the bulk of the work.

setup()

The setup() function is called once when your program starts. Use it to initialize pin modes, or begin serial. It must be included in a program even if there are no statements to run.

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

loop()

After calling the setup() function, the loop() function does precisely what its name suggests, and loops consecutively, allowing the program to change, respond, and control the Arduino board.

void loop() { digitalWrite(pin, HIGH); // turns 'pin' on delay(1000); // pauses for one second digitalWrite(pin, LOW); // turns 'pin' off delay(1000); // pauses for one second }

functions

A function is a block of code that has a name and a block of statements that are executed when the function is called. The functions void setup() and void loop() have already been discussed and other built-in functions will be discussed later.

Custom functions can be written to perform repetitive tasks and reduce clutter in a program. Functions are declared by first declaring the function type. This is the type of value to be returned by the function such as 'int' for an integer type function. If no value is to be returned the function type would be void. After type, declare the name given to the function and in parenthesis any parameters being passed to the function.

type functionName(parameters) { statements; }

The following integer type function delayVal() is used to set a delay value in a program by reading the value of a potentiometer. It first declares a local variable v, sets v to the value of the potentiometer which gives a number between 0-1023, then divides that value by 4 for a final value between 0-255, and finally returns that value back to the main program.

int delayVal() { int v; // create temporary variable 'v' v = analogRead(pot); // read potentiometer value v /= 4; // converts 0-1023 to 0- return v; // return final value }

{} curly braces

Curly braces (also referred to as just "braces" or "curly brackets") define the beginning and end of function blocks and statement blocks such as the void loop() function and the for and if statements.

type function() { statements; }

An opening curly brace { must always be followed by a closing curly brace }. This is often referred to as the braces being balanced. Unbalanced braces can often lead to cryptic, impenetrable compiler errors that can sometimes be hard to track down in a large program.

The Arduino 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.

8 | structure

10 | variables

variables

A variable is a way of naming and storing a numerical value for later use by the program. As their namesake suggests, variables are numbers that can be continually changed as opposed to constants whose value never changes. A variable needs to be declared and optionally assigned to the value needing to be stored. The following code declares a variable called inputVariable and then assigns it the value obtained on analog input pin 2:

int inputVariable = 0; // declares a variable and // assigns value of 0 inputVariable = analogRead(2); // set variable to value of // analog pin 2

‘inputVariable’ is the variable itself. The first line declares that it will contain an int, short for integer. The second line sets the variable to the value at analog pin 2. This makes the value of pin 2 accessible elsewhere in the code.

Once a variable has been assigned, or re-assigned, you can test its value to see if it meets certain conditions, or you can use its value directly. As an example to illustrate three useful operations with variables, the following code tests whether the inputVariable is less than 100, if true it assigns the value 100 to inputVariable, and then sets a delay based on inputVariable which is now a minimum of 100:

if (inputVariable < 100) // tests variable if less than 100 { inputVariable = 100; // if true assigns value of 100 } delay(inputVariable); // uses variable as delay

Note: Variables should be given descriptive names, to make the code more readable. Variable names like tiltSensor or pushButton help the programmer and anyone else reading the code to understand what the variable represents. Variable names like var or value, on the other hand, do little to make the code readable and are only used here as examples. A variable can be named any word that is not already one of the keywords in the Arduino language.

variable declaration

All variables have to be declared before they can be used. Declaring a variable means defining its value type, as in int, long, float, etc., setting a specified name, and optionally assigning an initial value. This only needs to be done once in a program but the value can be changed at any time using arithmetic and various assignments.

The following example declares that inputVariable is an int, or integer type, and that its initial value equals zero. This is called a simple assignment.

int inputVariable = 0;

A variable can be declared in a number of locations throughout the program and where this definition takes place determines what parts of the program can use the variable.

variable scope

A variable can be declared at the beginning of the program before void setup(), locally inside of functions, and sometimes within a statement block such as for loops. Where the variable is declared determines the variable scope, or the ability of certain parts of a program to make use of the variable.

A global variable is one that can be seen and used by every function and statement in a program. This variable is declared at the beginning of the program, before the setup() function.

A local variable is one that is defined inside a function or as part of a for loop. It is only visible and can only be used inside the function in which it was declared. It is therefore possible to have two or more variables of the same name in different parts of the same program that contain different values. Ensuring that only one function has access to its variables simplifies the program and reduces the potential for programming errors.

The following example shows how to declare a few different types of variables and demonstrates each variable’s visibility:

int value; // 'value' is visible // to any function void setup() { // no setup needed }

void loop() { for (int i=0; i<20;) // 'i' is only visible { // inside the for-loop i++; } float f; // 'f' is only visible } // inside loop

variables | 11

arrays

An array is a collection of values that are accessed with an index number. Any value in the array may be called upon by calling the name of the array and the index number of the value. Arrays are zero indexed, with the first value in the array beginning at index number 0. An array needs to be declared and optionally assigned values before they can be used.

int myArray[] = {value0, value1, value2...}

Likewise it is possible to declare an array by declaring the array type and size and later assign values to an index position:

int myArray[5]; // declares integer array w/ 6 positions myArray[3] = 10; // assigns the 4th index the value 10

To retrieve a value from an array, assign a variable to the array and index position:

x = myArray[3]; // x now equals 10

Arrays are often used in for loops, where the increment counter is also used as the index position for each array value. The following example uses an array to flicker an LED. Using a for loop, the counter begins at 0, writes the value contained at index position 0 in the array flicker[], in this case 180, to the PWM pin 10, pauses for 200ms, then moves to the next index position.

int ledPin = 10; // LED on pin 10 byte flicker[] = {180, 30, 255, 200, 10, 90, 150, 60}; // above array of 8 void setup() // different values { pinMode(ledPin, OUTPUT); // sets OUTPUT pin }

void loop() { for(int i=0; i<7; i++) // loop equals number { // of values in array analogWrite(ledPin, flicker[i]); // write index value delay(200); // pause 200ms } }

datatypes | 13

14 | arithmetic

arithmetic

Arithmetic operators include addition, subtraction, multiplication, and division. They return the sum, difference, product, or quotient (respectively) of two operands.

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

The operation is conducted using the data type of the operands, so, for example, 9 / 4 results in 2 instead of 2.25 since 9 and 4 are ints and are incapable of using decimal points. This also means that the operation can overflow if the result is larger than what can be stored in the data type.

If the operands are of different types, the larger type is used for the calculation. For example, if one of the numbers (operands) are of the type float and the other of type integer, floating point math will be used for the calculation.

Choose variable sizes that are large enough to hold the largest results from your calculations. Know at what point your variable will rollover 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 and slow computation speeds.

Note: Use the cast operator e.g. (int)myFloat to convert one variable type to another on the fly. For example, i = (int)3.6 will set i equal to 3.

compound assignments

Compound assignments combine an arithmetic operation with a variable assignment. These are commonly found in for loops as described later. The most common compound assignments include:

x ++ // same as x = x + 1, or increments x by + x -- // same as x = x - 1, or decrements x by - x += y // same as x = x + y, or increments x by +y x -= y // same as x = x - y, or decrements x by -y x *= y // same as x = x * y, or multiplies x by y x /= y // same as x = x / y, or divides x by y

Note: For example, x *= 3 would triple the old value of x and re-assign the resulting value to x.

16 | constants

constants

The Arduino language has a few predefined values, which are called constants. They are used to make the programs easier to read. Constants are classified in groups.

true/false

These are Boolean constants that define logic levels. FALSE is easily defined as 0 (zero) while TRUE is often defined as 1, but can also be anything else except zero. So in a Boolean sense, -1, 2, and -200 are all also defined as TRUE.

if (b == TRUE); { doSomething; }

high/low

These constants define pin levels as HIGH or LOW and are used when reading or writing to digital pins. HIGH is defined as logic level 1, ON, or 5 volts while LOW is logic level 0, OFF, or 0 volts.

digitalWrite(13, HIGH);

input/output

Constants used with the pinMode() function to define the mode of a digital pin as either INPUT or OUTPUT.

pinMode(13, OUTPUT);

if

if statements test whether a certain condition has been reached, such as an analog value being above a certain number, and executes any statements inside the brackets if the statement is true. If false the program skips over the statement. The format for an if test is:

if (someVariable ?? value) { doSomething; }

The above example compares someVariable to another value, which can be either a variable or constant. If the comparison, or condition in parentheses is true, the statements inside the brackets are run. If not, the program skips over them and continues on after the brackets.

Note: Beware of accidentally using ‘=’, as in if(x=10), while technically valid, defines the variable x to the value of 10 and is as a result always true. Instead use ‘==’, as in if(x==10), which only tests whether x happens to equal the value 10 or not. Think of ‘=’ as “equals” opposed to ‘==’ being “is equal to”.

flow control | 17

for

The for statement is used to repeat a block of statements enclosed in curly braces a specified number of times. An increment counter is often used to increment and terminate the loop. There are three parts, separated by semicolons (;), to the for loop header:

for (initialization; condition; expression) { doSomething; }

The initialization of a local variable, or increment counter, happens first and only once. Each time through the loop, the following condition is tested. If the condition remains true, the following statements and expression are executed and the condition is tested again. When the condition becomes false, the loop ends.

The following example starts the integer i at 0, tests to see if i is still less than 20 and if true, increments i by 1 and executes the enclosed statements:

for (int i=0; i<20; i++) // declares i, tests if less { // than 20, increments i by 1 digitalWrite(13, HIGH); // turns pin 13 on delay(250); // pauses for 1/4 second digitalWrite(13, LOW); // turns pin 13 off delay(250); // pauses for 1/4 second }

Note: 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 expression can be any valid C statements with unrelated variables. These types of unusual for statements may provide solutions to some rare programming problems.

flow control | 19

while

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.

while (someVariable ?? value) { doSomething; }

The following example tests whether ‘someVariable’ is less than 200 and if true executes the statements inside the brackets and will continue looping until ‘someVariable’ is no longer less than 200.

while (someVariable < 200) // tests if less than 200 { doSomething; // executes enclosed statements someVariable++; // increments variable by 1 }

do… while

The do loop is a bottom driven loop that 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 { doSomething; } while (someVariable ?? value);

The following example assigns readSensors() to the variable ‘x’, pauses for 50 milliseconds, then loops indefinitely until ‘x’ is no longer less than 100:

do { x = readSensors(); // assigns the value of // readSensors() to x delay (50); // pauses 50 milliseconds } while (x < 100); // loops if x is less than 100

20 | flow control