Arduino Programming-Lec-3
Arduino Programming-Lec-3
• 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
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);
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);
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.
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);