0% found this document useful (0 votes)
7 views15 pages

Basic Commands in Arduino

This document provides an introduction to the basic commands in Arduino. It explains that Arduino programs have two main functions, setup() and loop(), which are executed cyclically. It also describes various data types, operators, mathematical and time functions, and how to configure digital inputs and outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Basic Commands in Arduino

This document provides an introduction to the basic commands in Arduino. It explains that Arduino programs have two main functions, setup() and loop(), which are executed cyclically. It also describes various data types, operators, mathematical and time functions, and how to configure digital inputs and outputs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Basic commands in Arduino

The basic structure of the Arduino programming language is quite simple and it
consists of at least two parts. These two necessary parts, or functions, enclose
blocks that contain declarations, statements, or instructions.

Void setup()
{
Estates;
}
Void Loop ()
{
Estates;
}

In dondesetup () is the part in charge of gathering the configuration and Loop () is the one that
they contain the program that will run cyclically. Both functions are necessary
for the program to work.
The setup() function is called only once when the program starts. It is used to
initialize the work modes of the pins, or the serial port. It must be included in a
program even if there is no statement to execute. After calling setup(), the
functionLoop() does precisely what its name suggests, it executes cyclically,
what enables the program to be continuously responding to events that
they occur on the card.

{} between braces
The braces are used to define the beginning and the end of a block of instructions. They
used for programming blocks setup(), Loop(), if.., etc.
semicolon
The semicolon ';' is used to separate statements in the language of
Arduino programming.
/*… */ comment block
Comment blocks, or multi-line comments, are areas of text
ignored by the programs that are used for code descriptions or
comments that help understand the program. They start with / * and
they end with * / and can span several lines.
Because comments are ignored by the program and do not take up space
In the memory of Arduino, they can be used generously and they can also
to be used to 'comment' blocks of code for the purpose of annotating
debugging information
// line of comments
A comment line starts with // and ends with the following line of
code. Like block comments, line comments are ignored by the
program and do not take up space in memory.
A comment line is often used after an instruction, to
provide more information about what it does or to remember it better
forward.
This is a comment

MATHEMATICAL FUNCTIONS

min(x,y)
Calculate the minimum of two numbers of any type of data and return the number
smaller.
Example:
Value = min(value, 100); //assigns to 'value' the smaller of 'value' or 100,
ensuring that it never exceeds 100.

max(x,y)
Calculate the maximum of two numbers of any data type and return the number.
bigger.
Example:
Value = max(value, 100); //assigns to 'value' the largest of 'value' or 100,
ensuring that it is at least 100.

RANDOM FUNCTIONS

randomSeed(seed)
Assign a value, or seed, as the starting point for the function.
random ().
Example:
randomSeed(value); //assigns 'value' as the random seed

Since the Arduino is unable to create a truly random number, randomSeed


allows you to place a variable, constant, or another function within the random function, which
which helps to generate more random numbers. There is a variety of
different seeds, or functions, that can be used in this function including millis
() or even analogRead() to read electrical noise through an analog pin.
random(min, max)
The random function allows you to return pseudo-random numbers within a range.
specified by the min and max values.
Example:
Value = random(100, 200); //assigns a random number to 'value'
between 100 and 200.
Note: Use this after using the randomSeed() function.

TIME FUNCTIONS

millis() function
Returns the number of milliseconds that have elapsed since the Arduino board
started executing the current program. This number will overflow (will return to zero),
after approximately 50 days. The returned data is of type unsigned long
(range [0, 2^32–1]).

Delay function (time)


Pause the program for the specified time (in milliseconds) in the
time parameter. The data given as a parameter is of type unsigned long.

VARIABLES DECLARATION

A variable is a way to name and store a numerical value for its use.
posterior by the program. As its name indicates, the variables are numbers that
they can continuously vary contrary to what happens with constants whose value
It never changes. A variable must be declared and, optionally, assigned a value.
All variables must be declared before they can be used. To declare
a variable is started by defining its type:

TYPE DIMENSION
BYTE Byte stores an 8-bit numeric value without decimals.
a range between 0 and 255
INT Integers are a type of primary data that store values.
16-bit unsigned integers within the range
32,767 to -32,768.
LONG The extended numeric variable format 'Long' is
refers to integers (32-bit type) without decimals that
they are found within the range -2147483648 to 2147483647.
FLOAT The data format of the 'floating point' type 'float' applies to the
numbers with decimals. Floating point numbers have
a higher resolution than 32 bits with a range
understood 3.4028235E +38 to +38-3.4028235E.
CHAR Character
UNSIGNED INT Unsigned integer, from 0 to 65,535
UNSIGNED LONG unsigned 32bit integer, from 0 to 4,294,967,295
STRING string of characters
VOID Only used when a function does not return anything
arrays
An array is a set of values accessed by an index number.
Any value can be retrieved by using the name of the array and the
index number.
The first value of the matrix is the one indicated by index 0, that is to say the
The first value of the set is the one at position 0. An array must be declared and
optionally assigned values to each position before being used.

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


In the same way, it is possible to declare an array by indicating the data type and the size.
subsequently, assign values to a specific position:

int miArray[5]; // declares an array of integers with 6 positions


miArray[3] = 10; // assigns the value 10 to position 4

To read from an array, it is enough to write the name and the position to be read:

x = myArray[3]; // x is now equal to 10 which is in position 3 of the array

SYMBOLS AND OPERATORS

ARITHMETICS
The arithmetic operators included in the programming environment are addition,
subtraction, multiplication, and division. These return the sum, difference, product, or quotient.
(respectively) of two operands.

Sum: a = b + c
Subtraction: a = b - c

Multiplication: a = b * c
Division: x=a \ b

COMPOUND ASSIGNMENTS
Compound assignments combine an arithmetic operation with a variable.
assigned. These composite assignments can be:
COMPARISON OPERATORS

LOGICAL OPERATORS

Logical operators are usually a way to compare two expressions and


return true or false depending on the operator. There are three logical operators,
AND (&&), OR (||) and NOT (!).
Example:

CONSTANTS

The Arduino programming language has some default values, which are
constant calls. They are used to make programs easier to read. The
Constants are classified into groups:

TRUE/FALSE
These are boolean constants that define the HIGH (high) and LOW (low) levels.
when they refer to the state of the digital outputs. FALSE is associated with 0
(zero), while TRUE is associated with 1, but TRUE can also be anything
another thing except zero.

HIGH/LOW
These constants define the high or low output levels and are used for the
reading or digital writing for the sideburns. HIGH is defined as in the logic of
level 1, ON, or 5 volts, while LOW is logic level 0, OFF, or 0 volts.

Example:
DigitalWrite (13, HIGH); // activates output 13 with a high level (5v.)
INPUT/OUTPUT
These constants are used to define, at the beginning of the program, the mode of
operation of the pins using the pinMode instruction in such a way that the
pin can be an INPUT or an OUTPUT.

Example:
PinMode (13, OUTPUT); // we designate that PIN 13 is an output

CONFIGURATION OF DIGITAL INPUTS AND OUTPUTS

pinMode(pin, mode)
This instruction is used in the setup() configuration part and serves to
configure the working mode of a PIN to be INPUT (input) or OUTPUT
(exit).
Example:
pinMode(pin, OUTPUT); // configures 'pin' as output

The Arduino terminals are configured as inputs by default, so


It is not necessary to define them in the event that they are going to work as inputs.
The pins configured as input are, from an electrical point of view, like
inputs in high impedance state.
These pins have an internal resistance of 20 K that can be accessed.
through software. These resistors are accessed in the following way:

pinMode(pin, INPUT); // set the 'pin' as input


digitalWrite(pin, HIGH); // activates the internal resistors

Internal resistors are typically used to connect the inputs to


switches. In the previous example, it is not about converting a pin into an output, it is
just a method to activate the inner resistances.
The pins configured as OUTPUT are said to be in a low state.
impedance state and can provide 40mA (milliamperes) of current to others
devices and circuits. This current is sufficient to power an LED diode (not
forgetting to put a resistor in series), but it is not large enough to
feed loads with higher consumption such as relays, solenoids, or motors.

digitalRead(pin)

Read the value of a pin (defined as digital) giving a HIGH (high) or LOW (low) result.
The pin can be specified either as a variable or a constant (0-13).

Value = digitalRead(Pin); // makes 'value' equal to the state read in 'Pin'


digitalWrite(pin, value)

Send to the previously defined OUTPUT 'pin' the value HIGH or LOW (setting it to 1 or 0
the output). The pin can be specified either as a variable or as a constant (0-
13).
Example

digitalWrite(pin, HIGH); // sets a HIGH (high or 1) value on the 'pin'

CONFIGURATION OF ANALOG INPUTS AND OUTPUTS

analogRead(pin)

Read the value of a specific pin defined as an analog input with a


10-bit resolution. This instruction only works on pins (0-5). The range of
the value we can read ranges from 0 to 1023.

Value = analogRead(pin); // assigns to value what it reads from the input 'pin'

Note: The analog pins (0-5) unlike the digital pins, do not need to be
declared as INPUT or OUTPUT since they are always INPUT.

analogWrite(pin, value)
This instruction is used to write a pseudo-analog value using the
pulse width modulation (PWM) procedure to one of the pins of
Arduino marked as 'PWM pin'. The most recent Arduino, which implements the
The ATmega168 chip allows enabling pins 3 as PWM type analog outputs.
5, 6, 9, 10, and 11. The older Arduino models that implement the chip
ATmega8 only has pins 9, 10, and 11 enabled for this function. The value that
It can be sent to these analog output pins in the form of a variable.
the constant, but always with a margin of 0-255.

analogWrite(pin, value); // writes 'value' to the 'pin' defined as analog

Note: Analog outputs, unlike digital ones, do not need to be


declared as INPUT or OUTPUT.
LCD SCREEN MANAGEMENT

LiquidCrystal function()
This function creates a new software instance of an LCD connected to the board.
Syntax:
LiquidCrystal name_display (RS, E, DB4, DB5, DB6, DB7);

Example: LiquidCrystal Lcd (12, 11, 5, 4, 3, 2);

Function begin (columns, rows)


With the instance created, this function defines the size of the display.

Example: Lcd. begin (16,2);

Function print(data, base)


Send data to the screen.

Example 1: Lcd. Print("hello");


Example 2: Lcd. Print (analogRead (A3), DEC);

Function write (data)


Send a character to the display.

Example 1: Lcd.Write (236);

Function clear ()
Clear the screen content.

Example: Lcd. Clear ();

Function setCursor (column, row)


Specify the coordinates of the location where it will be written on the screen. In the case
From the screen that is used, the column is in the range [0,15] and the row in [0,1].

Example: Lcd. SetCursor (0,1);

Function createChar (num,data)


Allows the creation of characters defined by the programmer.

Example: To define the letter ñ, a 8x5 matrix is drawn and filled in appropriately.
SERIES COMMUNICATION

In order for the computer to visualize the data sent by the board, it can be used
the "Serial Monitor" built into the Arduino environment, such. The serial monitor must have
the same speed used in the function Serial.begin() has been selected.

Function Serial.begin(speed)
Establishes the data transmission speed in symbols per second (baud rate)
for serial data transmission. By convention, a speed is usually used
of 9600 [baud]. Obviously, transmission speeds can be used
numerically larger.
Serial.available() function
Returns the number of Bytes that are available for reading in the buffer
serial port input, which can store up to 64 [Bytes].

Serial.end() function
Disable the serial communication, allowing pins 0 (RX) and 1 (TX) to be
used as digital inputs or outputs. To re-enable communication
series, it is called aSerial.begin().


Serial.parseInt();
Take serial data only if they are integers; if they are not, then
ignore

Function Serial.print(value, format) and Serial.println(value, format)


Send data to the serial port as ASCII text. The float data is printed by
omission with two decimals. The difference between Serial.print() and Serial.println() is
that the first does not add a carriage return or new line.
If an integer is sent, the format field can be used to set
the numerical base of the number. The format field can take the following
valores: DEC, HEX, OCT, BIN.
If a floating-point number is sent, the format field can be used to
specify the number of decimal digits that this number has.

Serial.write(data)
Send binary data to the serial port. The data variable can be a byte or a series.
of bytes.
For example:
Serial.write(35) will send a byte, with the number 35 encoded in binary.
Serial.write("hello") will send a series of bytes with the string "hello". This function
It is similar to Serial.print().

Function Serial.read()
Allows reading the data that arrives through the serial port..
Example:

data = Serial.read(); //stores in the variable data the data it reads


INTERRUPTIONS

An interrupt allows the normal flow of a program to stop and execute a


specific function. Once this function finishes, control returns to the program. To
Just like in other systems, Arduino has two types of interrupts: hardware and
software.

HARDWARE INTERRUPTIONS
In the case of Arduino UNO, it has two interrupts, INT0 and INT1 associated with pins 2 and
3, respectively. An interruption can happen at any moment during the execution of
program.
Function attachInterrup(interrupt, ISR, mode)
The arguments of this function are:
Interrupt: Interrupt number {0, 1}
ISR: (InterruptionServiceRoutine) Function that will be executed when it
produce the interruption.
mode: Define when the interruption will be triggered.
LOW: it is triggered when the pin is at a low level.
CHANGE: it is triggered when the pin value changes.
FALLING: it triggers when the pin goes from a high level to a low level.
RISING: it is triggered when the pin goes from a low level to a high level
Function noInterrupts() and interrupts()
Sometimes, it is desired that certain areas of the code are not interrupted.
for the interruptions. This is achieved with these functions.

SOFTWARE INTERRUPTIONS

Software interrupts, in the case of Arduino, are associated with timers.


This means that a timer should be set for a certain amount of time, and
when this is fulfilled, the execution of a previously defined function is triggered.
There are several libraries that allow the use of timers. In particular, we will look at the
timer1.h

Function initialize (period)


Specify how often in microseconds the function that will handle it will be executed.
interruption. By default, the period is 1 second. When the timer is initialized, the
pins 9 and 10 are disabled for the analogWrite() function.
attachInterrupt(function)
Call the function function in the time interval specified by the function
previous.
detachInterrupt() function
This function disables the initialized interrupt.

You might also like