0% found this document useful (0 votes)
47 views14 pages

Arduino Programming Basics Guide

This document provides a comprehensive guide on programming using Arduino with a focus on C/C++ syntax and the Arduino IDE setup. It covers essential programming concepts such as data types, variables, control structures, and built-in library functions for IoT applications. Additionally, it includes examples of conditional statements, loops, and string handling to facilitate effective programming in Arduino.
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)
47 views14 pages

Arduino Programming Basics Guide

This document provides a comprehensive guide on programming using Arduino with a focus on C/C++ syntax and the Arduino IDE setup. It covers essential programming concepts such as data types, variables, control structures, and built-in library functions for IoT applications. Additionally, it includes examples of conditional statements, loops, and string handling to facilitate effective programming in Arduino.
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

UNIT – 3.

PROGRAMMING USING ARDUINO

Programming Fundamentals with C using Arduino IDE


Arduino is a popular platform for IoT and embedded systems. Programming in C/C++ using the
Arduino IDE allows you to control sensors, actuators, and IoT devices efficiently.

1. Installing and Setting Up the Arduino IDE


Step 1: Download the Arduino IDE

 Visit the official Arduino website: [Link]


 Select the IDE version compatible with your operating system (Windows, macOS,
Linux).
 Download the installer or zip package.

Step 2: Install the Arduino IDE

 Windows: Run the downloaded .exe file and follow installation prompts.
 macOS: Open the .dmg file, drag Arduino IDE to Applications.
 Linux: Extract the tarball and run the [Link] script.

Step 3: Launch the Arduino IDE

 Open the installed Arduino IDE.


 You will see the main interface consisting of:
o Menu bar (File, Edit, Sketch, Tools, Help)
o Toolbar (Verify, Upload, New, Open, Save)
o Code editor area
o Message area (shows compilation messages)
o Serial monitor (for communication with Arduino)

Step 4: Connect Your Arduino Board

 Use a USB cable to connect the Arduino board (e.g., UNO, Nano, Mega) to your
computer.
 The power LED on the board should light up.

Step 5: Select Board and Port

 Go to Tools → Board → Arduino AVR Boards and select your board type.
 Go to Tools → Port and select the COM port corresponding to your board.

Step 6: Verify Installation

 Open a sample sketch: File → Examples → [Link] → Blink


 Click Verify (compiles the code) and then Upload to the board.
 The built-in LED on pin 13 should blink, confirming the setup works.

Basic Syntax in Arduino Programming (C/C++)


Understanding the basic syntax is crucial for writing programs (sketches) for Arduino and IoT
devices.

1. Arduino Sketch Structure


An Arduino program is called a sketch and has two main functions:

a) setup()

 Runs once when the Arduino is powered on or reset.


 Used to initialize pins, variables, and settings.

void setup()
{
pinMode(13, OUTPUT); // Set pin 13 as output
}

b) loop()

 Runs continuously after setup() finishes.


 Contains the main code that executes repeatedly.

void loop()
{
digitalWrite(13, HIGH); // Turn LED ON
delay(1000); // Wait 1 second
digitalWrite(13, LOW); // Turn LED OFF
delay(1000); // Wait 1 second
}

2. Comments
 Used to explain code; ignored by the compiler.
 Single-line comment:

// This is a comment

Multi-line comment:

/* This is

a multi-line comment */
3. Variables and Data Types
Variables store data. Common data types in Arduino:

Data Type Size Description


int 2 bytes Integer numbers (-32,768 to 32,767)
long 4 bytes Large integers (-2,147,483,648 to 2,147,483,647)
float 4 bytes Decimal numbers
double 4 bytes Decimal numbers (same as float on Arduino)
char 1 byte Single character
boolean 1 byte true/false values

Example:

int ledPin = 13; // Integer variable


float voltage = 3.3; // Float variable
boolean status = true; // Boolean variable

4. Constants
 Fixed values that do not change during program execution.
 Declared using const keyword.

const int LED_PIN = 13;

5. Functions
 Blocks of code that perform a specific task.
 Can be built-in (digitalWrite, pinMode) or user-defined.

Example of user-defined function:

void blinkLED (int pin, int delayTime)


{
digitalWrite(pin, HIGH);
delay(delayTime);
digitalWrite(pin, LOW);
delay(delayTime);
}
6. Operators
 Arithmetic: +, -, *, /, %
 Assignment: =, +=, -=, *=
 Comparison: ==, !=, <, >, <=, >=
 Logical: &&, ||, !

Example:

int a = 5;
int b = 10;
if (a < b && b > 0) {
// Condition is true
}

7. Control Structures
a) Conditional Statements

if (temperature > 30) {


digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}

b) Loops

 for loop: Repeat a fixed number of times

EX:
for (int i = 0; i < 5; i++) {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}
while loop: Repeat while a condition is true
while (temperature < 30) {
// Keep checking temperature
}

Data Types, Variables, Constants, and Operators in Arduino


Programming
These are the fundamental building blocks for writing Arduino programs and IoT applications.

1. Data Types
Data types define the kind of data a variable can store. Choosing the right data type is
important for memory efficiency and precision.

Data Size
Description Example
Type (bytes)
int 2 Integer numbers (-32,768 to 32,767) int count = 10;
Large integers (-2,147,483,648 to long distance =
long 4
2,147,483,647) 100000;
float 4 Decimal numbers (single precision) float voltage = 3.3;
double 4 Decimal numbers (same as float on Arduino) double pi = 3.14159;
char 1 Single character char grade = 'A';
boolean status =
boolean 1 True/False values true;
byte 1 Unsigned 0–255 byte level = 255;

2. Variables
 Definition: Named storage locations in memory to store data that can change during
program execution.
 Declaration Syntax:

data_type variable_name = initial_value;

Examples:

int ledPin = 13;


float temperature = 27.5;
boolean isOn = true;

 Rules for Naming Variables:


o Must start with a letter or underscore (_)
o Can contain letters, digits, and underscores
o Case-sensitive (ledPin ≠ LedPin)
o Cannot use Arduino or C keywords
3. Constants
 Definition: Fixed values that do not change during program execution.
 Declared using the const keyword.

Examples:

const int LED_PIN = 13;


const float V_REF = 3.3;

 Advantages of Constants:
o Improves code readability
o Prevents accidental modification
o Useful for pin numbers, reference voltages, and fixed thresholds

4. Operators
Operators allow you to perform calculations, comparisons, and logical decisions.

a) Arithmetic Operators

Operator Description Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b

b) Assignment Operators

Operator Description Example


= Assign value a = 5;
+= Add and assign a += 3; // a = a + 3
-= Subtract and assign a -= 2; // a = a - 2
*= Multiply and assign a *= 4; // a = a * 4
/= Divide and assign a /= 2; // a = a / 2

c) Comparison Operators

Operator Description Example


== Equal to if(a == b)
!= Not equal to if(a != b)
> Greater than if(a > b)
< Less than if(a < b)
>= Greater than or equal if(a >= b)
<= Less than or equal if(a <= b)
d) Logical Operators

Operator Description Example


&& AND if(a > 0 && b > 0)

! NOT if(!isOn)

5. Examples in Arduino
const int LED_PIN = 13;
int counter = 0;
float temperature = 27.5;
boolean isOn = true;

void setup() {
pinMode(LED_PIN, OUTPUT);
}

void loop() {
if (temperature > 30 && isOn) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
counter += 1; // Increment counter
delay(1000);
}

Conditional Statements and Loops in Arduino Programming


Control structures like conditional statements and loops allow Arduino programs to make
decisions and repeat tasks, which are essential for IoT applications.

1. Conditional Statements
a) if Statement

 Executes a block of code only if a condition is true.

Syntax:

if (condition) {
// Code to execute if condition is true
}
Example:

int temperature = 35;

if (temperature > 30) {


digitalWrite(LED_PIN, HIGH); // Turn LED ON
}
b) if...else Statement

 Executes one block if the condition is true, another if false.

Syntax:

if (condition) {
// Code if true
} else {
// Code if false
}

Example:

if (temperature > 30) {


digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}

c) if...else if...else Statement

 Tests multiple conditions sequentially.

Syntax:

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none are true
}

Example:

if (temperature > 30) {


digitalWrite(FAN_PIN, HIGH);
} else if (temperature > 20) {
digitalWrite(FAN_PIN, LOW);
} else {
digitalWrite(HEATER_PIN, HIGH);
}

2. Loops
a) for Loop

 Repeats a block of code a fixed number of times.

Syntax:

for (initialization; condition; increment) {


// Code to repeat
}
Example:

for (int i = 0; i < 5; i++) {


digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}

b) while Loop

 Repeats a block of code while a condition is true.

Syntax:

while (condition) {
// Code to repeat
}

Example:

int temp = 25;


while (temp < 30) {
temp++;
delay(1000);
}

c) do...while Loop

 Executes the block at least once, then repeats while the condition is true.

Syntax:

do {
// Code to execute
} while (condition);

Example:
int counter = 0;
do {
counter++;
} while (counter < 5);
3. Nested Loops and Conditional Statements
 You can combine loops and if statements to handle complex logic in IoT applications.

Example:

for (int i = 0; i < 5; i++) {


if (i % 2 == 0) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
delay(500);
}

4. Applications in IoT

 Temperature Control: Turn heaters or fans on/off based on readings.


 LED Patterns: Blink LEDs in sequences using loops.
 Motor Control: Repeat motor actions or sensor polling at intervals.
 Decision Making: Handle multiple conditions for smart home automation.

Using Arduino C Library Functions


Arduino provides a rich set of built-in C/C++ library functions to simplify programming and
control IoT devices. These functions handle timing, communication, and hardware
interaction.

1. Serial Communication Functions


Serial communication allows Arduino to send and receive data from a computer or other
devices via the USB or UART interface.

a) [Link]()

 Initializes the serial communication at a specific baud rate (bits per second).

Syntax:

[Link](baud_rate);

Example:

void setup() {
[Link](9600); // Start serial communication at 9600 bps
}
b) [Link]() and [Link]()

 [Link](): Sends data to the serial monitor without a new line.


 [Link](): Sends data to the serial monitor with a new line.

Example:

void loop() {
int temperature = 25;
[Link]("Temperature: ");
[Link](temperature);
delay(1000);
}

c) [Link]()

 Checks if data is available to read from the serial port.


 Returns the number of bytes available.

Example:

if ([Link]() > 0) {
char input = [Link]();
[Link](input);
}

d) [Link]()

 Reads incoming data from the serial buffer.

Example:

char data = [Link]();

e) [Link]()

 Sends raw bytes to the serial port. Useful for binary data.

Example:

[Link](65); // Sends ASCII 'A'

2. delay() Function
 Pauses program execution for a specified number of milliseconds.

Syntax:

delay(milliseconds);
Example:

digitalWrite(LED_PIN, HIGH);
delay(1000); // Wait 1 second
digitalWrite(LED_PIN, LOW);
delay(1000);

3. Other Common Arduino Library Functions


Function Description Example
Configure pin as INPUT,
pinMode(pin, mode) OUTPUT, or pinMode(13, OUTPUT);
INPUT_PULLUP
digitalWrite(pin, value) Set digital pin HIGH or LOW digitalWrite(13, HIGH);
digitalRead(pin) Read digital value from a pin int state = digitalRead(2);
Read analog value (0–1023) int sensorValue =
analogRead(pin)
from a pin analogRead(A0);
analogWrite(pin, value) Output PWM signal (0–255) analogWrite(9, 128);
map(value, fromLow, Re-maps a number from one int speed = map(sensorValue,
fromHigh, toLow, toHigh) range to another 0, 1023, 0, 255);
Returns time in milliseconds unsigned long time =
millis()
since Arduino started millis();
Constrains a value between a int val =
constrain(x, a, b) constrain(sensorVal, 0, 100);
and b

4. Example Program Using Serial and Delay


const int LED_PIN = 13;

void setup() {
pinMode(LED_PIN, OUTPUT);
[Link](9600); // Start serial communication
}

void loop() {
digitalWrite(LED_PIN, HIGH);
[Link]("LED is ON");
delay(1000); // Wait 1 second

digitalWrite(LED_PIN, LOW);
[Link]("LED is OFF");
delay(1000); // Wait 1 second
}

Explanation:

 LED toggles ON and OFF every second.


 Status is printed to the Serial Monitor.

Key Takeaways
 Arduino library functions simplify interfacing with hardware and peripherals.
 Serial functions are essential for debugging and IoT communication.
 delay() provides simple timing control for tasks like blinking LEDs.
 Other built-in functions (digitalWrite, analogRead, millis, map) are the core of
Arduino programming.

Strings and Mathematics Library Functions in


Arduino
Arduino provides built-in string handling and mathematical functions to make IoT
programming easier and more versatile.

1. Strings in Arduino
a) Types of Strings

1. C-style Strings
o Arrays of characters ending with a null character \0.
o Example:
2. char name[] = "Arduino";
3. Arduino String Class
o A dynamic string object with built-in methods.
o Example:
4. String greeting = "Hello IoT";

b) Common String Functions

Function Description Example


length() Returns the number of characters int len = [Link]();
concat() Concatenates two strings [Link](" World");
charAt() Returns character at index char ch = [Link](0);
String part =
substring() Extracts part of string [Link](0, 5);
Returns index of first occurrence
indexOf() int idx = [Link]('I');
of a character
toUpperCase() Converts string to uppercase [Link]();
toLowerCase() Converts string to lowercase [Link]();
if ([Link]("Hello IoT"))
equals() Compares two strings {...}

c) Example Using Strings


String msg = "IoT Devices";
[Link](msg); // Print the message
[Link](" are fun!");
[Link](msg); // IoT Devices are fun!
[Link]([Link]()); // Prints string length
2. Mathematics Library Functions
Arduino provides math functions to perform calculations, mostly from the standard C math
library.

a) Common Math Functions

Function Description Example


abs(x) Returns absolute value int a = abs(-5); // a = 5
Restricts value between int y = constrain(120, 0,
constrain(x, a, b)
min and max 100); // y = 100
map(value, fromLow, Maps value from one int speed = map(512, 0, 1023,
fromHigh, toLow, toHigh) range to another 0, 255);
min(a, b) Returns smaller value int m = min(5, 10); // m = 5
max(a, b) Returns larger value int m = max(5, 10); // m = 10
sqrt(x) Square root float s = sqrt(16); // s = 4
pow(x, y) x raised to the power y float p = pow(2, 3); // p = 8
Random number from 0
random(max) int r = random(100);
to max-1
Random number from
random(min, max) int r = random(50, 101);
min to max-1
Converts degrees to float rad = radians(180); //
radians(deg)
radians 3.14159
Converts radians to float deg = degrees(3.14159);
degrees(rad)
degrees // ~180

b) Example Using Math Functions


int a = -10;
[Link](abs(a)); // 10

int speed = map(512, 0, 1023, 0, 255);


[Link](speed); // 127

float area = pow(5, 2); // 25


[Link](area);

int randNum = random(50, 101); // Random between 50-100


[Link](randNum);

3. Key Takeaways

 Strings in Arduino can be handled using C-style arrays or String objects with useful
methods.
 Math library functions provide essential tools for calculations, scaling, random
numbers, and constraints.
 Combining string operations and math functions enables data processing and
communication in IoT projects.

You might also like