You are on page 1of 19

programação arduino

Site: ΕΛ/ΛΑΚ Moodle Impresso por: Usuário convidado


Curso: Impressão 3D com circuitos e Arduino Encontro: Data: Domingo, 13 de março de 2022, 06:01
Livro: programação arduino
Descrição

Pisque um LED, o Arduino 'hello world'.

Índice

1. Conectando o Arduino ao computador


2. A IDE do Arduino
2.1. Antes de executar o primeiro programa
2.2. Entendendo a interface

3. Pisque um LED
4. Desconstruindo o Blink
4.1. Comentários
4.2. Afirmações
4.3. Funções
4.4. Loop interno()
5. Remixagem de piscar
1. Conectando o Arduino ao computador

Primeiro, vamos conectar o Arduino ao computador com o cabo USB AB. Se parece com isso:

Podemos conectar uma extremidade a qualquer porta USB disponível do computador e a outra extremidade à porta USB
do Arduino.

O LED de energia marcado como LIGADO deve agora acender!

2. A IDE do Arduino

O Arduino IDE é um aplicativo gratuito (e de código aberto!) para escrever código e carregá-lo em uma placa Arduino. Caso
seu computador ainda não o tenha instalado, você pode encontrá-lo nesta página de download e clicar na opção que
melhor descreve seu sistema, seguindo as instruções.

Se você já tem o Arduino IDE instalado, abra-o. Se parece com isso:


2.1. Before running the first program

Everytime we want to program a different board, we need to tell the IDE where to find it and what kind is.

Select Board Type Arduino UNO


Under the Tools menu, find the Board submenu and navigate that to select Arduino (Genuino) UNO.

Select Correct Serial Port


Under the Tools menu again, find the Port submenu and choose the one your board is connected to. Some tips to find out
which is which:

The name of your board may appear next to it.


Unplug the Arduino and see which one disappears from the list.

2.2. Understanding the interface

The IDE has a code editor where you write your code to test. It also has some quick buttons and menus for various functions.
When you test your code, there is a notification area and a status bar that give information about any errors.
3. Blink a LED

A program designed for an Arduino board is called a sketch, and the process of transferring it to the board is called
uploading.

We are now going to upload the first sketch. It will be one of the examples available on the IDE.

Open Blink sketch


Go to the File > Examples > 01.Basics > Blink.

Verify the code


The first step to getting a sketch ready for uploading is to verify it. You can do this by clicking the 'tick' quick button, or
opening the Sketch menu and selecting Verify/Compile. This will check it over for any errors and then translate it into a
program
compatible with the Arduino hardware (compiling).

After a few seconds you should see the message Done compiling.

Upload to the board


Now that there are no errors in the code and it is compiled, it is ready for upload. Make sure the Arduino
is plugged in, the
Power LED is on and the correct board and Serial Port are selected.

Next, select Upload from the Sketch menu, or hit the horizontal arrow quick button.

Blink!
As the program is rather small, it will not take a lot of time to upload. You may notice the RX and TX LEDs blink during
upload. When it is up and running, the LED marked L will start blinking on and off, 1 second on - 1 second off.

4. Deconstructing Blink

Sketches are written in text. When you select Verify, the Arduino software checks the program and translates it to Arduino-
machine-language - which is not human-readable but is easy for the Arduino to understand.

Sketches themselves are written in C and/or C++,


which is a programming language that is very popular and powerful.

We will now take a closer look at the code itself.


/*

  Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO

  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to

  the correct LED pin independent of which board is used.

  If you want to know what pin the on-board LED is connected to on your Arduino

  model, check the Technical Specs of your board at:

  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014

  by Scott Fitzgerald

  modified 2 Sep 2016

  by Arturo Guadalupi

  modified 8 Sep 2016

  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink

*/

// the setup function runs once when you press reset or power the board

void setup() {

  // initialize digital pin LED_BUILTIN as an output.

  pinMode(LED_BUILTIN, OUTPUT);

// the loop function runs over and over again forever

void loop() {

  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

  delay(1000);                       // wait for a second

  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW

  delay(1000);                       // wait for a second

You may notice different parts of the code highlighted in different colours. This is automatic and helps the programmer
understand the code more easily.

4.1. Comments

Let's take a look at the first part of the sketch.

/*

  Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO

  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to

  the correct LED pin independent of which board is used.

  If you want to know what pin the on-board LED is connected to on your Arduino

  model, check the Technical Specs of your board at:

  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014

  by Scott Fitzgerald

  modified 2 Sep 2016

  by Arturo Guadalupi

  modified 8 Sep 2016

  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink

*/

This is a comment, it is a piece of text that is completely ignored by the Arduino. Comments in code are used to write notes
to anyone who might read your code.

We will use comments throughout our code examples to help explain what is going on. It is considered as a good practice
to write comments in the programming world; it makes sharing code and remixing it a lot easier.

You can see if something is a comment because there is a


/*

at the beginning and a


*/

at the end.

One-line comments
// the setup function runs once when you press reset or power the board

void setup() {

  // initialize digital pin LED_BUILTIN as an output.

  pinMode(LED_BUILTIN, OUTPUT);

The first line starts with

//

and is also a comment. This is used for short comments of one line.

4.2. Statements

We will now focus on two of the first lines of code: 

  // initialize digital pin LED_BUILTIN as an output.

  pinMode(LED_BUILTIN, OUTPUT);

The first line is obviously a comment.

The second line is not a comment, it is just code. It is the first statement of the sketch. A statement is like a sentence for the
Arduino and it always ends with a

;
.

This statement is commanding the Arduino to set the mode of the Built-in LED to output.

You may be wondering now why we had to do this in the first place, since we have mentioned that LEDs are outputs. This is because the
build-in LED is connected to a specific digital input/output port, pin 13. When using any digital pin in a program, we need to declare it as
input or output. More on this on the next module.

Function name
Inputs
pinMode ( LED_BUILTIN, OUTPUT
) ;
4.3. Functions

We will now take a step back, and look at the first line of code.

// the setup function runs once when you press reset or power the board

void setup() {

  // initialize digital pin LED_BUILTIN as an output.

  pinMode(LED_BUILTIN, OUTPUT);

We see that the

pinMode

statement is included in a structure like this:

void setup() {

...

These structures are called functions. In an Arduino sketch, these are the two basic sections: the setup() function and the
loop() function.

void setup() {

...

void loop() {

...

Whatever is inside setup() happens once in the beginning of the program execution, followed by loop() which repeats over
and over.
4.4. Inside loop()

First, let's take a look at what statements are inside the loop():

  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

  delay(1000);                       // wait for a second

  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW

  delay(1000);                       // wait for a second

This is essentially the part of the program that describes blinking. We see that blinking is actually turning a LED on, waiting
for a while, turning it off, waiting for a while again and then repeating from the top.

Let's take the statements one by one:

  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)

In an Arduino sketch, write means to set a value. digitalWrite() will set a value of HIGH or LOW. For the digital output pins
of the Arduino, HIGH and LOW means turning them ON and OFF.

Notice that the way we use digitalWrite() looks similar to pinMode() that we saw earlier.

delay(1000);                       // wait for a second

O delay() irá pausar o programa, evitando que o Arduino execute o próximo comando. O número entre parênteses é o
tempo de espera em milissegundos.

1000 ms = 1 seg

A próxima instrução é muito parecida com a primeira digitalWrite() do programa, porém desta vez ela coloca o pino em
LOW, desligando o LED.

5. Remixagem de piscar

Hora de mudar alguma coisa e ver o que acontece!

Experimente os seguintes exercícios:

Vá para o IDE do Arduino e altere o atraso de 1000 para 500 ms.


O que você acha que vai acontecer? :-)

Enlouqueça e mude um dos comentários.


O que você acha que vai acontecer agora? :-D
Faça o LED acender por 100ms e DESLIGAR por 900ms.
Faça o LED acender por 50ms e DESLIGAR por 50ms.
Agora 10ms ON e 10ms OF.
O que aconteceu?

You might also like