Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Variables and Control Structures in Arduino C

Uploaded by

Altan Blu
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)
14 views

Variables and Control Structures in Arduino C

Uploaded by

Altan Blu
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/ 6

1.

Variables and Data Types

1.1 Understanding variables


• Variables are used to store and manage data in Arduino programs.
• They act as named containers with a specific data type that defines the kind of data they can hold.

1.2 Data types (int, float, char, etc.)


• byte , uint8_t:
o 1 byte interger values (whole numbers)
o range: 0-255
• int , short , word, int16_t :
o 2 bytes,
o integer values with sign
o from -32,768 to 32,767
• unsigned int, uint16_t:
o 2 bytes,
o positive integer values,
o from 0 to 65,535
• long, int32_t:
o 4 bytes,
o integer values with sign
o from -2,147,483,648 to 2,147,483,647
• unsigned long, uint32_t:
o 4 bytes,
o positive integer values,
o 0 to 4,294,967,295
o Use this with millis() / micros()
• float: Used for floating-point values (decimal numbers).
o From -3.4028235E+38 to +3.4028235E+38
o 6-7 digits precision
o Avoid this if possible as it is less precise and slow. Where possible, use integers
and scale up decimal values e.g. multiple by 100
• Boolean, bool:
o 1 byte
o Used for true/false values.
• char:
o 1 byte
o Used for individual characters.
o Follows the ASCII encoding
• String:
o Used for storing sequences of characters.
o We will avoid this and use char array (“string” instead for flexibility. In certain cases where this is
more advantageous, this may be used
• Custom data types
o Additional data types could be made out of the default data types
o Use struct for this purpose
1.3 Declaring and initializing variables
• Syntax: data_type variable_name;
• Examples:
o int temperature;
o char response[20];
o byte color_code;
• we may also declare and initialize a variable
o Syntax: data_type variable_name = initial_value;
o Example: int age = 29;
• Basic rules:
o Variable names are case sensitive
o Must start with a letter
o Can contain numbers, letters and underscores
o Avoid reserved keywords

1.4 Exercise: Calculate the average of three numbers using variables.

1.5 Constants and literals


• Constants
• Used to represent fixed values
• Constants are values that do not change during program execution
• Use the const keyword to declare
• Example:
o const float PI = 3.14;
o const byte PIN_ONBOARD_LED = 13;
• Makes code readable
• Where necessary, replace hard coded numbers with descriptive constant variables
2.5.2 Literals
• Literals are fixed values directly used in the code
• Example of literals: 0xFF, 32, ‘A’, “hello world”
• Literals may simplify the code at certain instances

2.6 Types of variables according to scope: Global vs Local variables


• There are 2 primary types of variables according to where the variable may be accessed
• Global variables
o declared outside of any function, making them accessible from anywhere in the program.
o They have a global scope, which means they can be used both inside and outside functions.
o Global variables are typically used when a piece of data needs to be shared and modified across
multiple functions or throughout the entire program.
o These will permanently eat up RAM in an Arduino

int globalVariable = 10;

void setup() {
// Global variables can be accessed here.
}
void loop() {
// Global variables can also be accessed here.
}

• Local Variables:

o Local variables are declared inside a specific function, limiting their scope to that function.
o They are only accessible within the block of code where they are declared.
o Local variables are typically used when you need temporary storage for data within a specific
function, and you don't need to access that data outside of the function.
o Example:
void setup() {
int localVariable = 5; // Local variable declared inside the setup function.
// You can use 'localVariable' only within this function.
}

void loop() {
// 'localVariable' is not accessible here.
}
2.7 Types of variables according to lifetime: Auto vs Static variables
• Static Variables:
o Lifetime: Static variables have a lifetime that spans the entire program execution. They are
created once when the program starts and exist until the program terminates.
o Scope: Static variables have local scope, meaning they are usually declared within a function but
retain their values across multiple calls to that function.
o Initialization: Static variables are automatically initialized to zero if no initial value is specified.

void myFunction() {
static int staticVar = 0; // Declaring a static variable
staticVar++; // Incrementing the static variable
Serial.println(staticVar);
}

void setup() {
Serial.begin(9600);
myFunction(); // Calls the function
myFunction(); // Calls the function again
}

void loop() {
// ...
}

• Auto Variables (Default):

o Lifetime: Auto variables have a lifetime limited to the duration of the function in which
they are declared. They are created when the function is called and destroyed when the
function exits.
o Scope: Auto variables have local scope, meaning they are only accessible within the
function where they are declared.
o Initialization: Auto variables are not automatically initialized.

void myFunction() {
int autoVar = 0; // Declaring an auto variable
autoVar++; // Incrementing the auto variable
Serial.println(autoVar);
}

void setup() {
Serial.begin(9600);
myFunction(); // Calls the function
myFunction(); // Calls the function again
}

void loop() {
// ...
}

2. Control Structures

2.1 Introduction to control structures


• allow you to control the flow of your code and make decisions based on condition
• Sequential Execution: By default, code is executed sequentially from top to bottom
• These structures alter the sequential flow and include:
• Conditional statements
• Looping structures
• Switch case statements

2.2 Conditional statements (if, else if, else)


• used to make decisions
• They allow you to execute different blocks of code based on whether certain conditions are met
or not
• if Statement: It checks a condition, and if it's true, a specific block of code is executed
if (condition) {
// Code to execute if the condition is true
}
• else if Statement: Used to check additional conditions if the preceding "if" condition is false
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
}
• else Statement: Executes a block of code if none of the preceding conditions is true
if (condition1) {
// Code to execute if condition1 is true
} else {
// Code to execute if no conditions are true
}

2.3 Looping (for, while, do-while)


• Used to execute a block of code repeatedly
• for Loop: Executes a block of code a specific number of times.
Syntax
for (initialization; condition; increment/decrement)
{
// Code to repeat
}

Example:
for(byte i=0; i<10;i++)
{
Serial.println(i); //prints the numbers 0-9
}

• while Loop: Repeats a block of code while a specified condition is true.


Syntax:
while (condition) {
// Code to repeat
}
Examples:
while (digitalRead(2) == LOW) {
digitalWrite(13, !digitalRead(13));
delay(100);
}
• do-while Loop: Similar to a while loop, but it ensures that the code block is executed at least once
before checking the condition
syntax:
do {
// Code to repeat
} while (condition);

Example:
Do {
digitalWrite(13, !digitalRead(13));
delay(100);
} while (digitalRead(2) == LOW);

2.4 Switch case statements


o Switch case statements are used when you have multiple conditions to check against a single variable.
o They are particularly useful when you need to select among several predefined options.
o Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
// Code for Monday
break;
case 2:
// Code for Tuesday
break;
// ...
default:
// Code for other days
}

You might also like