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

Arduino Programming-Lec-3

The document provides information about common Arduino programming concepts including: - Functions like Serial.println(), pinMode(), digitalRead(), and digitalWrite() for basic input/output operations. - The typical structure of an Arduino sketch with setup() and loop() functions. - Using different variable types like int, float, and boolean. - Working with arrays and groups of values. - String manipulation functions and converting between strings and numbers.

Uploaded by

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

Arduino Programming-Lec-3

The document provides information about common Arduino programming concepts including: - Functions like Serial.println(), pinMode(), digitalRead(), and digitalWrite() for basic input/output operations. - The typical structure of an Arduino sketch with setup() and loop() functions. - Using different variable types like int, float, and boolean. - Working with arrays and groups of values. - String manipulation functions and converting between strings and numbers.

Uploaded by

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

Arduino Programming

Commonly used functions


• Serial.println(value)
✓Prints the value to the Arduino IDE’s Serial Monitor so you can view Arduino’s
output on your computer
• pinMode(pin, mode)
✓ Configures a digital pin to read (input) or write (output) a digital value
• digitalRead(pin)
✓ Reads a digital value (HIGH or LOW) on a pin set for input
• digitalWrite(pin, value)
✓ Writes the digital value (HIGH or LOW) to a pin set for output
A Typical Arduino Sketch

• Programs for Arduino are usually referred to as sketches.

• Sketches contain code—the instructions the board will carry out


• Code that needs to run only once (such as to set up the board for
your application) must be placed in the setup function.

• Code to be run continuously after the initial setup has finished goes
into the loop function
Using Simple Primitive Types (Variables)
• Arduino has different types of variables to efficiently represent
values. You want to know how to select and use these Arduino data
types.
Using Simple Primitive Types (Variables)
Using Simple Primitive Types (Variables)
• Variables declared using int will be suitable for numeric values if the
values do not exceed the range.
• Choose a type that specifically suits your application. This is especially
important if you are calling library functions that return values other
than int.
• bool (boolean) types have two possible values: true or false.
Using Floating-Point Numbers
• Floating-point numbers are used for values expressed with decimal
points (this is the way to represent fractional values).
void loop() {
float a = 123.456789; // Up to 7 digits bool isAGreaterThanB;
float b = -45.6789123; // Up to 7 digits
isAGreaterThanB = (a > b);
void setup() { a=a-50;
if (isAGreaterThanB) {
Serial.begin(9600);
Serial.println("Variable 'a' is greater
Serial.print("a: "); than variable 'b'");
Serial.println(a, 7); }
Serial.print("b: "); else {
Serial.println(b, 7);} Serial.println("Variable 'a' is not
greater than variable 'b'");
}
delay(2000);
}
Working with Groups of Values
int inputPins[] = {2, 3, 4, 5};
int ledPins[] = {10, 11, 12, 13};
void setup() {
• You want to create for (int i = 0; i < 4; i++)
and use a group of { pinMode(ledPins[i], OUTPUT);
values (called pinMode(inputPins[i], INPUT);
arrays). The arrays }
}
may be a simple void loop() {
list or they could for (int i = 0; i < 4; i++) {
have two or more int val;
dimensions. val = digitalRead(inputPins[i]);
if (val == LOW) {
digitalWrite(ledPins[i], HIGH);
delay(1000);
} else {
digitalWrite(ledPins[i], LOW);
delay(1000);
}
}
}
Using Arduino String Functionality
• You want to manipulate text. You need add bits together, and
determine the number of characters.
void setup() {
Serial.begin(9600);
Serial.println(text2.length());
String text1 = "This text, ";
Serial.println("Concatenated Text: " +
String text2 = "has more words!";
concatenatedText);
String concatenatedText = text1 + text2;
Serial.print("Number of Characters in
int numberOfCharacters =
Concatenated Text: ");
concatenatedText.length();
Serial.print(numberOfCharacters);
Serial.println("Text 1:" + text1);
}
Serial.print("Number of characters in Text 1:
");
void loop() {
Serial.println(text1.length());
// Nothing to do in the loop
Serial.println("Text 2:" + text2);
}
Serial.print("Number of characters in Text 2:
");
Using Arduino String Functionality
Function Description
strlen(str) Returns the length of the string (excluding the null terminator).
strcpy(dest, src) Copies the contents of the source string to the destination string.
strncpy(dest, src, n) Copies at most n characters from the source string to the destination string.
strcat(dest, src) Concatenates (appends) the source string to the destination string.
Concatenates (appends) at most n characters from the source string to the
strncat(dest, src, n)
destination string.
Compares two strings lexicographically; returns 0 if equal, a positive value if str1 >
strcmp(str1, str2)
str2, and a negative value if str1 < str2.
strncmp(str1, str2, n) Compares at most n characters of two strings lexicographically.
Returns a pointer to the first occurrence of character c in the string, or NULL if not
strchr(str, c)
found.
Returns a pointer to the first occurrence of substring substr in the string, or NULL if
strstr(str, substr)
not found.
strtok(str, delim) Breaks the string into a series of tokens using the specified delimiter characters.
Using C Character Strings
void setup() {
Serial.begin(9600);
char greeting[] = "Hello";
char name[] = " Arduino";
char combined[20]; // Assuming a size sufficient to hold both strings
strcpy(combined, greeting); // Copy the first string
strcat(combined, name); // Concatenate the second string
Serial.println("Combined String: ");
Serial.println(combined);
int length = strlen(combined);
Serial.print("Length of Combined String: ");
Serial.println(length);
char checkName[] = " Arduino";
int compareResult = strcmp(name, checkName);
if (compareResult == 0) {
Serial.println("name and checkName are equal.");
} else {
Serial.println("name and checkName are not equal.");
}
}
void loop() {}
Splitting Comma-Separated Text into Groups

• Tokenization: The process of dividing a string into tokens is called


tokenization. This is often done by identifying and extracting
substrings based on specified delimiters.

• Token: A token is a unit of information within a string. It can


represent a word, a number, a symbol, or any other meaningful
element.

• Tokenizing Function: In C and C++ programming, the ‘strtok’


function is commonly used for tokenization. It takes a string and a
set of delimiters as arguments and returns pointers to the
individual tokens within the string.
Splitting Comma-Separated Text into Groups
void setup() {
Serial.begin(9600);

// Example comma-separated text


char inputText[] = "apple,orange,banana,grape";

// Tokenize the input text using strtok


char *token = strtok(inputText, ",");

// Print each group


Serial.println("Splitting into groups:");
while (token != NULL) {
Serial.println(token);
token = strtok(NULL, ","); // Get the next token
}
}

void loop() {
// Nothing to do in the loop
}
Converting a Number to a String
• The Arduino String class automatically converts numerical values
when they are assigned to a String variable. You can combine
(concatenate) numeric values at the end of a string using the concat
function or the string + operator.
itoa and ltoa
• itoa and ltoa take three parameters:
➢ the value to convert
➢ the buffer that will hold the output string and
➢ the number base (10 for a decimal number, 16 for hex, and 2
for binary).
• Buffers are used as temporary storage to hold data before it is
processed, transferred, or manipulated.
void setup() {
Serial.begin(9600);
// Example numbers
int intValue = 123;
long longValue = 456789;
// Buffers to store the converted strings
char intBuffer[10];
char longBuffer[20];
// Convert integers to strings
itoa(intValue, intBuffer, 10);
ltoa(longValue, longBuffer, 10);
// Print the converted strings
Serial.print("Integer as String: ");
Serial.println(intBuffer);

Serial.print("Long Integer as String: ");


Serial.println(longBuffer);
}
void loop() {
}
Converting a String to a Number
• You need to convert a string to a number. Perhaps you have received
a value as a string over a communication link and you need to use this
as an integer or floating-point value.
• Another approach to converting text strings representing numbers is
to use the C language conversion function called atoi (for int
variables) or atol (for long variables).
• Functions like ‘atoi’, ‘atol’, ‘atof’, ‘strtoXXX’ are used to convert strings to
numbers.
• When using strtoXXX functions, know about the concept of base
(e.g., 10 for decimal, 16 for hexadecimal).
Converting a String to a Number
void setup() {
Serial.begin(9600);

// Example string containing a number


char numberString[] = "123";

// Convert string to integer using atoi


int convertedNumber = atoi(numberString);

// Print the converted number


Serial.print("Converted Number: ");
Serial.println(convertedNumber);
}

void loop() {
// Nothing to do in the loop
}
Error Handling During Conversion
If you need to handle errors during conversion, you might consider using ‘’strtol’’ for long integers or ‘’strtof’’ for
floating-point numbers.

Pointers: A pointer is a variable that stores the memory address of another variable. It "points" to the location
in memory where a value is stored.
• Declaration: int *ptr; \\declares a pointer to an integer.
• Initialization: int x = 10;
int *ptr = &x; \\initializes the pointer ptr with the address of variable x.
void setup() {
Serial.begin(9600);

// Example string containing a number


char numberString[] = "123abc";

// Convert string to long integer using strtol with error checking


char *endPtr;
long convertedNumber = strtol(numberString, &endPtr, 10);

if (*endPtr != '\0') {
Serial.println("Error: Invalid characters in the string.");
} else {
Serial.print("Converted Number: ");
Serial.println(convertedNumber);
}
}
void loop() {
// Nothing to do in the loop
}
Structuring Your Code into Functional Blocks
Function: A function is a program within a program, a defined
function can be called from anywhere in the sketch and it contains
its own variables and commands.
Example:
int ledPin=13; void flash(int numFlashes, int d)
int delayPeriod=250; {
void setup() for (int i=0; i<numFlashes; i++)
{ {
pinMode(ledPin,OUTPUT); digitalWrite(ledPin, HIGH);
} delay(d)
void loop() digitalWrite(ledPin, LOW);
{ delay(d);
flash(20, delayPeriod); }
delay(3000); }
}
Example
• Write down a sketch with a function that takes a parameter and
returns a value. The parameter determines the length of the LED on
and off times (in milliseconds). The function continues to flash the
LED until a button is pressed, and the number of times the LED
flashed is returned from the function.

const int ledPin = 13; // Pin connected to the LED


const int buttonPin = 2; // Pin connected to the button

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
Example
// Function to flash the LED based on the specified on/off void loop() {
times int onTime = 500; // On time in milliseconds
int flashLED(int onTime, int offTime) { int offTime = 500; // Off time in milliseconds
int flashCount = 0;
Serial.println("Press the button to stop flashing.");
while (digitalRead(buttonPin) == HIGH) {
digitalWrite(ledPin, HIGH); // Turn on the LED int totalFlashes = flashLED(onTime, offTime);
delay(onTime);
digitalWrite(ledPin, LOW); // Turn off the LED Serial.print("LED flashed ");
delay(offTime); Serial.print(totalFlashes);
Serial.println(" times.");
flashCount++; delay(1000); // Add a delay for visibility in the Serial
} Monitor
}
return flashCount;
}
Taking Actions Based on Conditions
• You want to execute a block of code only if a particular condition is
true. For example, you may want to light an LED if a switch is pressed
or if an analog value is greater than some threshold.
const int switchPin = 2; // Pin connected to the switch
const int analogPin = A0; // Analog pin connected to a sensor
const int ledPin = 13; // Pin connected to the LED
const int threshold = 500; // Analog threshold value

void setup() {
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void
Taking Actions Based on Conditions
loop() {
// Read the state of the switch
int switchState = digitalRead(switchPin);

// Read the analog sensor value


int analogValue = analogRead(analogPin);

// Check if the switch is pressed or analog value is greater than threshold


if (switchState == LOW || analogValue > threshold) {
// Turn on the LED
digitalWrite(ledPin, HIGH);
Serial.println("Switch is pressed or analog value is greater than threshold. LED is ON.");
} else {
// Turn off the LED
digitalWrite(ledPin, LOW);
Serial.println("Switch is not pressed and analog value is below threshold. LED is OFF.");
}

delay(100); // Add a small delay for stability


}
Repeating a Sequence of Statements
• You want to repeat a block of statements while an expression is true.
Repeating Statements with a Counter
• You want to repeat one or more statements a certain number of
times. The for loop is similar to the while loop, but you have more
control over the starting and ending conditions.
Breaking Out of Loops
Taking a Variety of Actions Based on a Single
Variable
Comparing Character and Numeric Values
• You want to determine the relationship between values.
Performing Logical Comparisons
int a = 5;
int b = 10;
if (a > 0 && b > 0) {
// This block will be executed if both a and b
are greater than 0
Serial.println("Both a and b are greater than
0");
}
int x = 7;
int y = 3;
int value = 42;
if (x > 5 || y > 5) {
// This block will be executed if either x or y is if (!(value == 0)) {
greater than 5 // This block will be executed if value is not
Serial.println("Either x or y is greater than 5"); equal to 0
} Serial.println("Value is not equal to 0");
}
Performing Bitwise Operations
Combining Operations and Assignment

You might also like