Lecture 3: Arduino Programming Language

17
Microcontroller Design Dr. Shayma Akram Yousif 1 Lecture 3: Arduino Programming Language The Arduino Programming Language is basically a framework built on top of C++. A program written in the Arduino Programming Language is called sketch. A sketch is normally saved with the .ino extension (from Arduino). The main difference from “normal” C or C++ is that you wrap all your code into two main functions. You can have more than two, of course, but any Arduino program must provide at least those two. We don’t have a main() function like you are used to in C/C++ as the entry point for a program. Once you compile your sketch, the IDE will make sure the end result is a correct C++ program and will basically add the missing glue by preprocessing it. Part of the Arduino Programming Language is the built-in libraries that allow you to easily integrate with the functionality provided by the Arduino board. The Arduino program can be divided in three main parts: Structure, Values (variables and constants), and Functions.

Transcript of Lecture 3: Arduino Programming Language

Microcontroller Design Dr. Shayma Akram Yousif

1

Lecture 3:

Arduino Programming Language

• The Arduino Programming Language is basically a framework built

on top of C++.

• A program written in the Arduino Programming Language is called sketch. A sketch is normally saved with the .ino extension

(from Arduino).

• The main difference from “normal” C or C++ is that you wrap all

your code into two main functions. You can have more than two, of

course, but any Arduino program must provide at least those two.

• We don’t have a main() function like you are used to in C/C++ as the entry point for a program. Once you compile your sketch, the

IDE will make sure the end result is a correct C++ program and will basically add the missing glue by preprocessing it.

• Part of the Arduino Programming Language is the built-in libraries that allow you to easily integrate with the functionality provided by

the Arduino board.

The Arduino program can be divided in three main parts: Structure,

Values (variables and constants), and Functions.

Microcontroller Design Dr. Shayma Akram Yousif

2

Structure

Software structure consist of two main functions −

• Setup( ) function

• Loop( ) function

Microcontroller Design Dr. Shayma Akram Yousif

3

Setup()

• The setup() function is called when a sketch starts. Use it to

initialize the variables, pin modes, start using libraries, etc.

• The setup function will only run once, after each power up or reset

of the Arduino board.

Example Code

int buttonPin = 3;

void setup() {

Serial.begin(9600);

pinMode(buttonPin, INPUT);

}

void loop() {

// ...

}

Loop()

• After creating a setup() function, which initializes and sets the initial

values, the loop() function does precisely what its name suggests,

and loops consecutively, allowing your program to change and

respond. Use it to actively control the Arduino board.

Example Code

int buttonPin = 3;

// setup initializes serial and the button pin

void setup() {

Serial.begin(9600);

pinMode(buttonPin, INPUT);

}

// loop checks the button pin each time, and will send serial if it is

pressed

Microcontroller Design Dr. Shayma Akram Yousif

4

void loop() {

if (digitalRead(buttonPin) == HIGH) {

Serial.write('H');

}

else {

Serial.write('L');

}

delay(1000);

}

Variables

The variables are defined as the place to store the data and values. It

consists of a name, value, and type.

Data types

Microcontroller Design Dr. Shayma Akram Yousif

5

Consider the below example:

Examples:

1. int a = 3;

2. char myvariable = ' B ';

3. float val = 1.178;

4. String a = "Hello";

Constants

Pin level Constants

The digital pins can take two value HIGH or LOW.

In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode()

function. The pin is further made HIGH or LOW using the digitalWrite()

function.

HIGH

The board includes two types of voltage pins to provide HIGH value, which

are listed below:

o 5V

o 3V

Some boards include only 5V pins, while some include 3.3V.

Some boards consist of both 5V and 3.3V pins. For example, Arduino

UNO R3.

The pin configured as HIGH is set at either 5V or 3.3V.

Microcontroller Design Dr. Shayma Akram Yousif

6

The pins are configured at the 5V or 3.3V depending on:

o for voltage > 3.0V (presented at 5V pin)

o for voltage > 2.0V (presented at 3.3V pin)

LOW

The pin configured as LOW is set at 0 Volts.

The pins are configured at the 5V or 3.3V depending on:

o for voltage < 1.5V (presented at 5V pin)

o for voltage < 1V (presented at 3.3V pin)

Logical level Constants

The logical level constants are true or false.

The value of true and false are defined as 1 and 0. Any non-zero integer is determined as true in terms of Boolean language. The true and false

constants are type in lowercase rather than uppercase (such as HIGH, LOW,

etc.).

Constant Keyword

The name const represents the constant keyword. It modifies the behavior

of the variables in our program. It further makes the variable as 'read-only'.

The variable will remain the same as other variables, but its value cannot

be changed.

Example Code

const float pi = 3.14;

Example Code

const int a =2;

Microcontroller Design Dr. Shayma Akram Yousif

7

Functions

The functions allow a programmer to divide a specific code into various sections, and each section performs a particular task. The functions are

created to perform a task multiple times in a program.

The function is a type of procedure that returns the area of code from which

it is called.

For example, to repeat a task multiple times in code, we can use the same

set of statements every time the task is performed.

Function Declaration

The method to declare a function is listed below:

o Function return type

We need a return type for a function. For example, we can store the return

value of a function in a variable.

We can use any data type as a return type, such as float, char, etc.

o Function name

It consists of a name specified to the function. It represents the real body

of the function.

o Function parameter

It includes the parameters passed to the function. The parameters are

defined as the special variables, which are used to pass data to a function.

The function must be followed by parentheses ( ) and the semicolon ;

The actual data passed to the function is termed as an argument.

Microcontroller Design Dr. Shayma Akram Yousif

8

Example:

Consider the below image:

Example:

1. void setup()

2. {

3. Serial.begin(9600);

4. }

5. void loop() {

6. int a = 5; // initialization of values to the variables a and b

7. int b = 4;

8. int c;

9. c = myAddfunction(a, b); // c will now contains the value 9

10. Serial.println(c); // to print the resulted value

11. delay(1000); // time delay of 1 second or 1000 milliseconds

12. }

13. int myAddfunction(int i, int j)

14. {

15. int sum;

16. sum = i + j;

17. return sum;

18. }

Microcontroller Design Dr. Shayma Akram Yousif

9

pinMode()

[Digital I/O]

Description

Configures the specified pin to behave either as an input or an output.

Syntax

pinMode(pin, mode)

Parameters

pin: the Arduino pin number to set the mode of.

mode: INPUT, OUTPUT, or INPUT_PULLUP.

Returns

Nothing

Example Code

The code makes the digital pin 13 OUTPUT and Toggles it HIGH and LOW

void setup() {

pinMode(13, OUTPUT); // sets the digital pin 13 as output

}

void loop() {

digitalWrite(13, HIGH); // sets the digital pin 13 on

delay(1000); // waits for a second

digitalWrite(13, LOW); // sets the digital pin 13 off

delay(1000); // waits for a second

}

Microcontroller Design Dr. Shayma Akram Yousif

10

digitalRead()

[Digital I/O]

Description

Reads the value from a specified digital pin, either HIGH or LOW.

Syntax

digitalRead(pin)

Parameters

pin: the Arduino pin number you want to read

Returns

HIGH or LOW

Example Code

Sets pin 13 to the same value as pin 7, declared as an input.

int ledPin = 13; // LED connected to digital pin 13

int inPin = 7; // pushbutton connected to digital pin 7

int val = 0; // variable to store the read value

void setup() {

pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output

pinMode(inPin, INPUT); // sets the digital pin 7 as input

}

void loop() {

val = digitalRead(inPin); // read the input pin

digitalWrite(ledPin, val); // sets the LED to the button's value

}

Notes and Warnings

If the pin isn’t connected to anything, digitalRead() can return

either HIGH or LOW (and this can change randomly).

Microcontroller Design Dr. Shayma Akram Yousif

11

The analog input pins can be used as digital pins, referred to as A0, A1,

etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6 and A7

pins, which can only be used as analog inputs.

digitalWrite()

[Digital I/O]

Description

Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage

will be set to the corresponding value: 5V (or 3.3V on 3.3V boards)

for HIGH, 0V (ground) for LOW.

If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or

disable (LOW) the internal pullup on the input pin.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin,

when calling digitalWrite(HIGH), the LED may appear dim.

Microcontroller Design Dr. Shayma Akram Yousif

12

Syntax

digitalWrite(pin, value)

Parameters

pin: the Arduino pin number.

value: HIGH or LOW.

Returns

Nothing

Example Code

The code makes the digital pin 13 an OUTPUT and toggles it by

alternating between HIGH and LOW at one second pace.

void setup() {

pinMode(13, OUTPUT); // sets the digital pin 13 as output

}

void loop() {

digitalWrite(13, HIGH); // sets the digital pin 13 on

delay(1000); // waits for a second

digitalWrite(13, LOW); // sets the digital pin 13 off

delay(1000); // waits for a second

}

analogRead()

[Analog I/O]

Description

Reads the value from the specified analog pin. Arduino boards contain a

multichannel, 10-bit analog to digital converter. This means that it will

map input voltages between 0 and the operating voltage (5V or 3.3V) into

integer values between 0 and 1023.

Microcontroller Design Dr. Shayma Akram Yousif

13

Syntax

analogRead(pin)

Parameters

pin: the name of the analog input pin to read from (A0 to A5 on most

boards, A0 to A6 on MKR boards, A0 to A7 on the Mini and Nano, A0 to

A15 on the Mega).

Returns

The analog reading on the pin.

Example Code

The code reads the voltage on analogPin and displays it.

int analogPin = A3; // potentiometer wiper (middle terminal) connected to

analog pin 3

// outside leads to ground and +5V

int val = 0; // variable to store the value read

void setup() {

Serial.begin(9600); // setup serial

}

void loop() {

val = analogRead(analogPin); // read the input pin

Serial.println(val); // debug value

}

Microcontroller Design Dr. Shayma Akram Yousif

14

analogWrite()

[Analog I/O]

Description

• The analogWrite Arduino command is used to update the status of

analog pins and also used to address the PWM pins on the board.

• The PWM pins are 8-bit pins, terming that you can set the duty cycle

somewhere between 0 -255.

• The analogWrite comes handy when you plan to control the motor

speed or the intensity of any LED.

• The value you write on the PWM pins will control the speed. For

example, if you intend to run the motor at full speed, you will set

the value 255 i.e. the maximum value it can handle that will

ultimately run the motor at full speed.

• You do not need to call pinMode() to set the pin as an output before

calling analogWrite().

The analogWrite function has nothing to do with the analog pins or

the analogRead function.

Syntax

analogWrite(pin, value)

Parameters

pin: the Arduino pin to write to. Allowed data types: int.

value: the duty cycle: between 0 (always off) and 255 (always on).

Allowed data types: int.

Microcontroller Design Dr. Shayma Akram Yousif

15

Returns

Nothing

Example Code

Sets the output to the LED proportional to the value read from the

potentiometer.

int ledPin = 9; // LED connected to digital pin 9

int analogPin = 3; // potentiometer connected to analog pin 3

int val = 0; // variable to store the read value

void setup() {

pinMode(ledPin, OUTPUT); // sets the pin as output

}

void loop() {

val = analogRead(analogPin); // read the input pin

analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023,

analogWrite values from 0 to 255

}

delay()

[Time]

Description

Pauses the program for the amount of time (in milliseconds) specified as

parameter. (There are 1000 milliseconds in a second.)

Syntax

delay(ms)

Parameters

ms: the number of milliseconds to pause. Allowed data types: unsigned

long.

Microcontroller Design Dr. Shayma Akram Yousif

16

Returns

Nothing

Example Code

The code pauses the program for one second before toggling the output

pin.

int ledPin = 13; // LED connected to digital pin 13

void setup() {

pinMode(ledPin, OUTPUT); // sets the digital pin as output

}

void loop() {

digitalWrite(ledPin, HIGH); // sets the LED on

delay(1000); // waits for a second

digitalWrite(ledPin, LOW); // sets the LED off

delay(1000); // waits for a second

}

delayMicroseconds()

[Time]

Description

Pauses the program for the amount of time (in microseconds) specified by

the parameter. There are a thousand microseconds in a millisecond and a

million microseconds in a second.

Currently, the largest value that will produce an accurate delay is 16383.

This could change in future Arduino releases. For delays longer than a few

thousand microseconds, you should use delay() instead.

Microcontroller Design Dr. Shayma Akram Yousif

17

Syntax

delayMicroseconds(us)

Parameters

us: the number of microseconds to pause. Allowed data types: unsigned

int.

Returns

Nothing

Example Code

The code configures pin number 8 to work as an output pin. It sends a

train of pulses of approximately 100 microseconds period. The

approximation is due to execution of the other instructions in the code.

int outPin = 8; // digital pin 8

void setup() {

pinMode(outPin, OUTPUT); // sets the digital pin as output

}

void loop() {

digitalWrite(outPin, HIGH); // sets the pin on

delayMicroseconds(50); // pauses for 50 microseconds

digitalWrite(outPin, LOW); // sets the pin off

delayMicroseconds(50); // pauses for 50 microseconds

}