0% found this document useful (0 votes)
3 views

Lecture 4 (2)

The document provides a comprehensive overview of fundamental Arduino code, including variable types, basic code definitions, digital and analog I/O functions, and control structures. It outlines the syntax and usage of various functions such as digitalRead, digitalWrite, analogRead, and control statements like if, else, for, and while. Additionally, it includes example codes to illustrate the application of these concepts in programming with Arduino.

Uploaded by

alhadeea313
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 4 (2)

The document provides a comprehensive overview of fundamental Arduino code, including variable types, basic code definitions, digital and analog I/O functions, and control structures. It outlines the syntax and usage of various functions such as digitalRead, digitalWrite, analogRead, and control statements like if, else, for, and while. Additionally, it includes example codes to illustrate the application of these concepts in programming with Arduino.

Uploaded by

alhadeea313
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Automation & Robotics lab

Fourth Class – First Semester


Asst. Lecturer: Waad Qaiss
2024-2025

Lecture: Fourth

Fundamental Arduino Code


Code Region Sections

Variables Types

Variable Usage Syntax Number


type of bytes
int A variable with a value (number) 2
int var = val;
ranging from -32700 to +32700
(approximately).
float A variable that accepts a large 4
numerical value and a decimal float var = val;

point (+/-).
Byte A variable that accepts a small 1
byte var = val;
numerical value (255-0).
bool A variable that has only two 1
bool var = val;
states (1 or 0) (true or false).
long A variable with a large number 4
long var = val;
(about -2B to 2B).
char A variable holding a number and 1
char var = val;
representing a letter with the
char myChar = 'A';
symbol ASCII.
String An array of letters (word or any
String stringOne
sentence). = "Hello String";

Basic Code Definition

1. Syntax

#define (define)
#include (include)
/* */ (block comment)
// (single line comment)
; (semicolon)
{} (curly braces)

2. Arithmetic Operators

* (multiplication)
+ (addition)
- (subtraction)
/ (division)
= (assignment operator)
3. Comparison Operators

!= (not equal to)


< (less than)
<= (less than or equal to)
== (equal to)
> (greater than)
>= (greater than or equal to)

4. Functions

A. Digital I/O

▪ digitalRead()
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.

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
}
▪ digitalWrite()
Description
Write a HIGH or a LOW value to a digital pin.

Syntax
digitalWrite(pin, value).
Parameters
pin: the Arduino pin number.
value: HIGH or LOW.

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
}

▪ pinMode()
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.

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
}

B. Analog I/O

▪ analogRead()
Description
Reads the value from the specified analog pin.

Syntax
analogRead(pin).
Parameters
pin: the name of the analog input pin to read from.

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
}

▪ analogWrite()
Description
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at
varying brightnesses or drive a motor at various speeds.
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.

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
}

Notes:

➢ Pulse Width Modulation, or PWM, is a technique for getting analog results


with digital means. Digital control is used to create a square wave, a signal
switched between on and off.

➢ In the graphic below, the green lines represent a regular time period. This
duration or period is the inverse of the PWM frequency. In other words, with
Arduino's PWM frequency at about 500Hz, the green lines would measure 2
milliseconds each. A call to analogWrite() is on a scale of 0 - 255, such that
analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
➢ On some microcontrollers PWM is only available on selected pins. Please
consider the pinout diagram of your board to find out which ones you can
use for PWM. They are denoted with a tilde sign (~).

C. Time

▪ delay()
Description
Pauses the program for the amount of time (in milliseconds) specified as
parameter.

Syntax
delay(ms).
Parameters
ms: the number of milliseconds to pause.

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()
Description
Pauses the program for the amount of time (in microseconds) specified by the
parameter.

Syntax
delayMicroseconds(µs).
Parameters
µs: the number of microseconds to pause.

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
}
D. Communication

▪ Serial.println()
Description
Prints data to the serial port as human-readable ASCII text followed by a
carriage return character (ASCII 13, or '\r') and a newline character (ASCII
10, or '\n').

Syntax
Serial.println(val).

Parameters
Serial: serial port object.
val: the value to print. Allowed data types: any data type.

Example Code

/*
Analog input reads an analog input on analog in 0, prints the value
out.
created 24 March 2006
by Tom Igoe
*/

int analogValue = 0; // variable to hold the analog value

void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);

// print it out in many formats:


Serial.println(analogValue); // print as an ASCII-encoded
decimal
Serial.println(analogValue, DEC); // print as an ASCII-encoded
decimal
Serial.println(analogValue, HEX); // print as an ASCII-encoded
hexadecimal
Serial.println(analogValue, OCT); // print as an ASCII-encoded
octal
Serial.println(analogValue, BIN); // print as an ASCII-encoded
binary

// delay 10 milliseconds before the next reading:


delay(10);
}
▪ Serial.begin()
Description
Sets the data rate in bits per second (baud) for serial data transmission.

Syntax
Serial.begin(speed).
Parameters
Serial: serial port object.
speed: in bits per second (baud). Allowed data types: long.

Example Code
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600
bps
}

void loop() {}

5. Structure

A. Sketch

▪ setup()
Description
The setup() function is called when a sketch starts. Use it to initialize
variables, pin modes, start using libraries, etc. The setup() function will only
run once, after each powerup or reset of the Arduino board.

Example Code
int buttonPin = 3;

void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}

void loop() {
// ...
}
▪ loop()
Description
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 the program to change and respond.

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
void loop() {
if (digitalRead(buttonPin) == HIGH) {
Serial.write('H');
}
else {
Serial.write('L');
}

delay(1000);
}

B. Control Structure

▪ if
Description
The if statement checks for a condition and executes the following statement
or set of statements if the condition is 'true'.

Syntax
if (condition) {
//statement(s)
}
Parameters
condition: a boolean expression (i.e., can be true or false).
Example Code
The brackets may be omitted after an if statement. If this is done, the next line
(defined by the semicolon) becomes the only conditional statement.

if (x > 120) digitalWrite(LEDpin, HIGH);

if (x > 120)
digitalWrite(LEDpin, HIGH);

if (x > 120) {digitalWrite(LEDpin, HIGH);}

if (x > 120) {
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}
// all are correct

▪ else
Description
The if…else allows greater control over the flow of code than the basic if
statement, by allowing multiple tests to be grouped. An else clause (if at all
exists) will be executed if the condition in the if statement results in false.
The else can proceed another if test, so that multiple, mutually exclusive tests
can be run at the same time.
Each test will proceed to the next one until a true test is encountered. When a
true test is found, its associated block of code is run, and the program then
skips to the line following the entire if/else construction. If no test proves to
be true, the default else block is executed, if one is present, and sets the default
behavior.

Syntax
if (condition1) {
// do Thing A
}
else if (condition2) {
// do Thing B
}
else {
// do Thing C
}
Example Code
if (temperature >= 70) {
// Danger! Shut down the system.
}
else if (temperature >= 60) { // 60 <= temperature < 70
// Warning! User attention required.
}
else { // temperature < 60
// Safe! Continue usual tasks.
}

▪ for
Description
The for statement is used to repeat a block of statements enclosed in curly
braces. An increment counter is usually used to increment and terminate the
loop. The for statement is useful for any repetitive operation, and is often used
in combination with arrays to operate on collections of data/pins.

Syntax
for (initialization; condition; increment) {
// statement(s);
}
Parameters
initialization: happens first and exactly once.
condition: each time through the loop, condition is tested; if it’s true, the
statement block, and the increment is executed, then the condition is tested
again. When the condition becomes false, the loop ends.
increment: executed each time through the loop when condition is true.

Example Code
The brackets may be omitted after an if statement. If this is done, the next line
(defined by the semicolon) becomes the only conditional statement.

// Dim an LED using a PWM pin


int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10

void setup() {
// no setup needed
}

void loop() {
for (int i = 0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10);
}
}

▪ while
Description
A while loop 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.

Syntax
while (condition) {
// statement(s)
}
Parameters
condition: a boolean expression that evaluates to true or false.

Example Code
var = 0;
while (var < 200) {
// do something repetitive 200 times
var++;
}

▪ break
Description
break is used to exit from a for, while or do…while loop, bypassing the
normal loop condition.

Example Code
In the following code, the control exits the for loop when the sensor value
exceeds the threshold.
int threshold = 40;
for (int x = 0; x < 255; x++) {
analogWrite(PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold) { // bail out on sensor detect
x = 0;
break;
}
delay(50);
}
C. Boolean Operators

▪ ! (logical not)
Description
Logical NOT results in a true if the operand is false and vice versa.

Example Code
This operator can be used inside the condition of an if statement.
if (!x) { // if x is not true
// statements
}

▪ && (logical and)


Description
Logical AND results in true only if both operands are true.

Example Code
This operator can be used inside the condition of an if statement.
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // if BOTH
the switches read HIGH
// statements
}

▪ || (logical or)
Description
Logical OR results in a true if either of the two operands is true.
Example Code
This operator can be used inside the condition of an if statement.
if (x > 0 || y > 0) { // if either x or y is greater than zero
// statements
}

D. Compound Operators

++ (increment)
-- (decrement)

You might also like