You are on page 1of 69
218124, 207 PM “The Arduino Handbook Learn Micracontroles for Embedded Systems The Arduino Handbook — Learn Microcontrollers for Embedded El eecodecamp orginewstne arduine handbook 5 October 2023 2 To ne Arduino Arduino is an open-source platform that combines hardware and software in designing and building electronic projects. Arduino can be applied in a variety of projects like: + Home automation. + Intemet of Things (loT). + Audio and music + Automated and remote controlled systems. + Automation in agriculture, + Electronic prototyping + Wearable devices, and so much more. The hardware part of Arduino comprises Arduino boards, input and output devices (including digital and analog pins, and sensors and actuators), shields, breadboards, jumper wires, and so on. These ‘components can be combined together to create dynamic and interactive projects, ntps:wawfreecodecamp.orginewsithe-arduine-handbookitchapter-$-how-{o-use-sensors-and.actuatorsr-arduino 1169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems The software is made up of the development tools used to write, debug, compile, and upload code to Arduino boards. Most Of the software tools can be found in the Arduino IDE (Integrated Development Environment). This handbook will help you understand how Arduino works. You'll learn about the Arduino boards, the components that make up a board, and how to connect devices to them Well talk about input and output peripherals which help the microcontroller (the brain of the Arduino board) process information coming from the physical environment, and send output based on programmed logic. You'll learn about the Arduino IDE, how to code using the Arduino programming language, and how to use sensors, actuators, and other components to build projects as you leam. You'll also learn about serial communication, which helps Arduino boards communicate with other computers. This handbook is written for makers (students, artists, hobbyists, programmers) who are beginners. Prerequisites Although it would be helpful, you don't need prior programming knowledge to use this handbook. You will learn the basics of Arduino programming from scratch. This can also serve as your introduction to programming, To make it beginner friendly, we won't talk about some aspects of electronics like current and voltage, resistance, circuits (series and parallel), and most basic electronic/electrical laws and requirements for students in STEM (Science, Technology, Engineering, Mathematics) fields Whether you have knowledge of these concepts or not, you can learn about Arduino using this handbook. If you know how to use a breadboard and a resistor, then that's all the knowledge on electronics you'll need to follow along. In summary, this handbook is for everyone. You don't need an engineering degree to become an Arduino maker! nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 2169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Table of Contents: Chapter 1: Getting Started with Arduino The Arduino development and design process comprises both hardware and software. So knowing how they work together is important for building the right foundation for your journey. In this chapter, you'll learn about the different components that make up the Arduino Uno board. You'll also learn how to install the Arduino IDE and set up your development environment. At the time of writing, a new Uno board was released — the Arduino Uno R4. This handbook will make use of the Uno R3 board, but you can follow along with either of them. The R4 board comes in two variants — Arduino Uno R4 WiFi and Arduino Uno R4 Minima — with cool additional features that you can read about here. Components of the Arduino Uno R3 Board There are many types of Arduino boards like Arduino Nano, Arduino Uno, Arduino Mega, Arduino Leonardo, and so on These boards have some common features — they all have digital and output pins, they're programmable, and they all have a microcontroller. But there are also some differences. Each board varies in size and shape, and usually has more or fewer components when compared to other boards. The common boards you'll come across as a beginner are the Nano, Uno, and Mega boards. The most commonly used is the Uno board, which we'll use for this handbook Here are some of the components you'll find on the Uno R3 board: + Apower port + USB connector. + Microcontroller (ATmega328). + Analog pins. + Digital pins. + Reset button. + TXand RX indicators. hips reecodecamp orginewsithe-arduino-handbookichapter--how-to-use-sensors.ane-actuators-t-arduino 218124, 207 PM “The Arduino Handbook Learn Micracontroles for Embedded Systems Arduino Uno R3 board (https://store.arduino.ce/products/arduino-uno-rev3) You'll make use of most of the components listed above as you progress through this handbook. How to Install and Set Up the Arduino IDE You can use the Arduino IDE to program Arduino boards. That is, you write the code in the IDE, then upload it to the board. In this section, you'll learn how to set up the IDE, and create your first Arduino program (also called an Arduino sketch). You can download the latest version of the Arduino IDE on the Arduino software download page. You can download the IDE for different operating systems — Windows, MacOS, and Linux. The installation process is similar for the operating systems listed above. Here's how to install it on a Windows machine: ntps:wawfreecodecamp.orginewsithe-arduine-handbookitchapter-$-how-{o-use-sensors-and.actuatorsr-arduino 4i69 218124, 207 PM “The Arduino Handbook — Learn Microcontrollers for Embedded Systems Step #1 — Download the Arduino IDE The first step is to download the IDE from the Arduino software download page. You should see a section of the page similar to the image below: Bet Arduino IDE 2.1.0 Re nn renee Pee ‘The new major release of the Arduino IDE is faster and even ‘more powerfull In addition to a more modern editor and a more responsive interface it features autocompletion, code ‘navigation, and even alive debugger. De eet ferent For more details, please refer to the Arduino IDE 2.0 documentation. Nightly builds with the latest bugtixes are available through the section below. ‘The Arduino IDE 2.0is open source and its source code is hosted on GitHub, (On the right side of the image above are different download options for specific operating systems, Make sure you download the option that suits your operating system "use the ZIP file option for Windows. If you decide to download an installer instead, then you can follow the installation steps after clicking the installation file. Step #2 — Unzip the Downloaded File Go on and unzip the downloaded file. This gives you access to all the resources needed to run the Arduino IDE, After unzipping the file, you should see files like these: ntps:twwwfreecodecamp org neweithe-arduine-handbookitchapter-$-how-to-use-sensors-and-actuators-in-ardulno 5169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems eos Application erent) oe eel ee fore nee [ice fens) Sees PIES) nd eee ID switshader ied [Boe R ect Image showing the files you should see To launch the Arduino IDE, click on the file that says “Arduino IDE” Step #3 — Overview of the Arduino IDE Now that you've downloaded and installed the Arduino IDE, the next part is to get familiar with the development environment. In the next section, you'll learn how to upload code to an Arduino Uno board using the IDE. Before that, let's have a look at some options youl find in the Arduino IDE. At the top left comer of, the IDE are five options — File, Edit, Sketch, Tools, Help: nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 6169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Fie Edt Sketch Too i) >) Select Board Ce Moe CMe} 1 oid setup() { ‘Screenshot showing these options (File, Edit, Sketch, Tools, Help) The “File” option lets you do different things like creating a new sketch (we'll talk about sketches in the next section), opening an existing sketch, Arduino practice examples for beginners, keyboard shortcuts, save options, and so on The “Edit” option gives you access to text formatting options like copy, paste, cut, commentuncomment code, font size options, text search options, and so on. You can use the “Sketch” option to verify and compile code, upload code to Arduino boards, optimize code, and add libraries. You can use the “Tools” option to manage libraries, format code, access the serial monitor and plotter, select an Arduino board and port to upload code to, choose a processor, and so on The “Help” option provides resources for troubleshooting, information on IDE updates, guides on “getting started", and so on. Next, let's look at some other parts and functionalities in the IDE that you'll ind useful. The image below, from the Arduino documentation, highlights them perfectly: nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 7189 218124, 207 PM “The Arduino Handbook Learn Micracontroles for Embedded Systems a : https:fidocs arduino. c/software/ide-v2itutorials/getting-started-ide-v2 + Verify/Upload: You can use these options to compile and upload code to Arduino boards You'll get error messages if the code doesn't compile as expected. + Select Board & Port: You can use this option to select a port and port number to upload your code too. The current version of the Arduino IDE automatically detects both boards and ports. + Sketchbook: This gives you access to all the sketches created in your computer, You can also access sketches saved on Arduino Cloud (mostly used for creating loT projects). + Boards Manager: The Arduino IDE comes with support for different boards. As you progress through your journey, you'll make use of different boards and some of them may not be supported by the IDE. The board manager tab lets you install and manage packages required to use these boards. + Library Manager: You can use libraries to extend certain functionalities in code. Through the library manager, you can install numerous libraries that'll help simplify the development process for you. + Debugger: This is used for real time testing and debugging of Arduino programs. + Search: You can use the search tool to find specific keywords in your code. + Open Serial Monitor: You can use the serial monitor to communicate with Arduino boards, debug and test code, visualize data from your boards, interact with user input, and so on. We'll look at the serial monitor in depth in a different chapter. + Open Serial Plotter: The serial plotter is mostly used for real-time visualization of numerical data, -ntps:wawfreecodecamp.orginewsithe-arduine-handbookitchapter-$-how-{o-use-sensors-and.actuatorsr-arduino 8169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems What Is an Arduino Sketch? We mentioned the term “sketch” a couple of times in the last section, but what is it? A sketch is a program written with the Arduino programming language. It's another way of referring to a code file written for Arduino projects. The Arduino programming language is built upon the C/C++ language so they both share similar ‘syntax and structure. You may come across resources that refer to Arduino code as “embedded C" or “embedded C++". How to Upload Code to an Arduino Board To upload code to an Arduino board, you'll need both hardware and software. The hardware is the board which is the Uno board in our case, and the software is the Arduino sketch in the IDE. Here are the steps: Step #1 — Connect the Arduino Board Connect the Arduino board to your computer using the USB cable. Without this step, you can't go further. Step #2 — Create a Sketch Now its time to launch the IDE and write some code. Here's a code example that makes an LED blink: int ledpin = 235 void setup() ¢ pintode(edPin, OUTPUT); > void 1o0p() digitalwrite(ledPin, HIGH); delay(1000); Gigitalurite(ledPin, Low); delay(1200); > Don't worry if you don't understand the code — we'll cover everything as we go further. hips reecodecamp orginewsithe-arduino-handbookitchapter--how-to-use-sensors.ane-actuators-t-arduino 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Step #3 — Select the Board and Port You can select the board to upload your code to from the IDE. Here's an image showing what that looks like: Select Board sketch_oct4 y Arduino Uno [cole] Reaeatraed ee ean ie Pruner eee Summon iD loop() { digitalWrite(ledPin, HIGH); CEs : digitalWrite(ledPin, LOW); Step #4 — Verify the Code You can use the verify button to compile the code and check for errors. If errors exist, youll get an error message to show you the possible cause. nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 10169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Se sketch_oct4a.ino ledPin = 13; Oe (ledPin, OUTPUT) ; (ledPin, (ledPin, Image showing the verify button Step #5 — Upload the Code You can upload the code using the upload button (the button after the verify button) If there are no errors in your code, these steps will help upload code to your board. If you've uploaded the code above, you should have the builtin LED (it is connected to pin 13 by design) on the Uno board blinking In the next chapter, you'll learn the basics of the Arduino programming language. Chapter 2: Basics of Arduino Programming Before we dive into creating our own sketches and tinkering, you have to understand the logic that make these boards work as expected. To do that, you'll have to know how to code using the Arduino programming language. As discussed in the last chapter, the Arduino language is built upon C/C++. You'll begin this chapter by learning the basics of programming. This will prepare you for every other chapter that involves writing code, nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino ‘189 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems I've created this chapter with beginners in mind. If you've never written code before then this can serve as a starting point for you. This doesn't mean you'll learn how to cade in C or C++. You'll be learning how to write Arduino code which shares similar syntax with those languages, At the end of this chapter, you should be able to understand and write Arduino code. Variables and Data Types in Arduino Variables and data types are used in most programming languages to store and manipulate data. You can think of variables as containers or storage units. Data types, like the name implies, are the type of data stored in variables. In Arduino programming, you must specify the data type of a variable before using it. That is: datatype variableNane = variablevalue There are different types of data types in Arduino, and welll discuss each one along with code examples. int Data Type in Arduino The int data type is used to store integer values. The Uno board has a 16-bit integer capacity so it can store values that fall within the range of -32,768 to 32,767. int redLeD = In the code above, we created an integer variable called redieo with a value of 6. The int data type can also store negative integers: int redLeo long Data Type in Arduino The long data type is similar to int but has a wider range of integer values. It has a 32-bit integer limit which falls within the range of -2,147,483,648 to 2,147,483,647. long largeNunber = 6900; float Data Type in Arduino The float data type can be used to store numbers with decimals, Float variables can store values up to 3.4028235E+38 and values as low as -3.4028235E+38, float nun = 10.53 nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 12169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Although the float data type is mainly used for decimal numbers, it can also accept whole numbers (integers without decimals). But itll always retum a float value. So if you store 10 ina float , itll return 10.00. String Data Type in Arduino You can use the String data type to store and manipulate text, You'll work with strings occasionally to display information in the form of text when building projects. Here's a code example: String greeting = "Hello World!*; The value of strings are nested within double quotation marks as can be seen in the code above. Note that when declaring a string, the "S" should always be in uppercase. char Data Type in Arduino The char data type stores single characters Here's an example: char alphabet = ‘A's This is different from the string data type that can store multiple characters. There are two main differences between char and string + char uses single quotes (‘A’) while string uses double quotes ("Arduino"). + char stores single characters while string stores multiple characters. char can also accept integer values equivalent to the ASCII value of letters: char charValue = 65; In the code above, we initialized a char variable with the value of 65. When printed to the serial ‘monitor (we'll talk about the serial monitor in Chapter 6: How to use the Serial Monitor in Arduino), A. will be retumed. Ais retumed because 65 has an ASCII character of A. bool and boolean Data Types in Arduino You can use both bool and boolean to store/denote boolean values of either true or false bool roontsCold = Falses nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 13169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Boolean values are mostly used with logical and comparison operators, and conditional statements {you'll learn about these later in this chapter) to manipulate and control different outcomes in an Arduino program. byte Data Type in Arduino The byte data type has an 8-bit unsigned integer limit that ranges from 0 to 255. Unsigned means that it can't store negative values. byte sensorValue = 200; The byte data type isn't the only data type that can be unsigned. You can also use the unsigned int, unsigned long, and unsigned char data types which all have their respective positive integer ranges. Operators in Arduino Operators are symbols or characters that can be used to perform certain operations on operands. An operand is simply any value(s) an operator acts on. There are different categories of operators in Arduino like: Arithmetic Operators Arithmetic operators are used to perform mathematical operations like addition, subtraction, division, ‘multiplication, and so on, Here are some arithmetic operators you should know: Addition(+) Operator The addition operator, denoted by the + symbol, adds two operands together: int a int © Serial.print(c); 5 Subtraction(-) Operator The subtraction operator subtracts the value of one operand from another operand. It is denoted by the - symbol nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 14169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems int a int © // we use subtraction operator to subtract b fron a below int c=b- ay Serial.print(c); Ws Multiplication (*) Operator You can use the multiplication operator ( = ) to multiply two operands: int a= 55 18; int b= 105 J/ wa use sultiplication operator to multiply a by b below int c= a * bj Serial.print(c); 138 Division(/) Operator The division operator divides one operand by another: int a int © = 19; // we use division operator to divide b by a below int c= b/ a; Serial.print(c); Wr Modulus (%) Operator ‘The modulus operator returns the remainder of a division between two operands: int a= 55 int = 20; J/ we use division operator to divide b by a below Ant c= bX aj Serial.print(c); We nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 15169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Increment (++) Operator The increment operator increases the value of a variable by 1 Ant num = 53 Serial .print(num); 6 Decrement (--) Operator The decrement operator decreases the value of a variable by 1 Ant num = 5; Serial .print(num); wa Assignment Operators Assignment operators are mainly used to assign values to variables. You can also use them to update the value of variables. The assignment ( - ) operator is used for assigning and updating variables. The - operator should not be confused for "equal to" — they aren't the same. We'll talk about the equal to ( == ) operator in the Comparison Operators section. Here's an example that shows how to use the assignment operator: int age = In the code above, we created a variable called age , and then assigned a value of 1 to it using the = operator. But this isn't the only way to assign or update the value of variables when using the = operator. You can also use compound assignment operators. Compound Assignment Operators Compound assignment operators let you combine arithmetic operators and the = operator, This method provides a shorter way of writing code. Here is an example: nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 16169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Serial.print(x) 38 In the code above, we created an x variable and assigned a value of 5 to it. But on the second line, you'd see that we combined the arithmetic addition ( + ) operator and the = operator to assign a new value to. x The line of code above is the same as this: ‘So compound operators combine two operators and let you do the same thing in a shorter way. There's nothing wrong with either method. Here are other compound operator examples: int a= 18; a -= 53 // Equivalent to a= a - 5 (a becones 5) int © = 18; /1 Equivalent to 6 = b +5 (b becones 50) 10; 11 Equivalent © 15 (€ becones 2) int d= 195 6 % 55 // Equivalent to d= d % 3 (d becones @) Comparison Operators You can use comparison operators to compare two values/operands. Comparison operators retum either true (1) or false (0) depending on the relationship between operands. Comparison operators can help you make decisions based on their return values. You'll see them a lot when we start building projects. Here are the comparison operators you'll come across occasionally Equal To (==) Operator This operator compares the values of two variables. If the values are the same, it returns true . If the values are not the same, it returns false . Here's an example: nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 189 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems int x = 19; int y = 55 Serial print( ” The return value of x == yi same. Remember that the value the code above is 0 ( fase ) because the two variables are not the operator returns 1 ( true ) only when both variables have the same Not Equal (!=) Operator The not equal operator checks whether two values have different values. It's does the opposite of the == operator. That means itll return 4 ( true ) if both values are not of the same value and 0 ( false )if both values are the same. Here's an example: int x = 105 int y = 55 Serial.print(x I= y) W/ veturns 1 Greater Than (>) Operator The greater than ( > ) operator checks if the operand on the left is greater than the operand on the right. If the left operand is greater, it returns 1. If the left operand is smaller, it returns 0. int x = 18) int y= Serial.print(x > y) W/ veturns 1 Less Than (<) Operator The less than ( < ) operator checks if the operand on the left is less than the operand on the lef. If the left operand is smaller, it returns 1. If the left operand is greater, it returns 0. int x = 20; int y= 55 Serial.print(x < y) I] returns @ nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 16169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Greater Than or Equal To (>=) Operator Just like the name, the >= operator checks if the operand on the left is either greater than or equal to the operand on the right. It retums 1 if the left operand is greater than or equal to the right operand, and 0 if isn't "Or" implies that either of the conditions can be used. If the left operand is not greater than the right operand but is equal to the right operand, youll stil get a value of 1. int x = 18; int y= 55 Serial.print(x >= y) Less Than or Equal To (<=) Operator The <= operator checks if the left operand is either less than or equal to the right operand. If the left operand is less than or equal to the right operand, it retums 1, and returns 0 if the left operand is neither less than nor equal to the right operand. int x = 18) int y Serial.print(x <= y) J) returns @ Logical Operators Logical operators are used in most programming languages to evaluate and determine the relationship between variables. Here are the three logical operators you should know for Arduino programming: Logical AND ( & ) Operator The logical AND ( && ) operator returns 1 if both statements are true. int x = 10 Serial.print((x > 5) a& (x > 3); J) returns 1 The expression above — (x > 5) @& (x > 3) —retums 1 because both statements are true. That is, x > 3 and x > 3 . Ifeither or both of those statements were false, then we'd have a return value of 0. nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 19169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Logical OR (||) Operator The logical OR ( || ) operator returns 1 if one of both statements is true. int x = 18; Sertal.print((x > 5) && (x > 15); W/ veturns 1 The code above returns 1 although one of the statements is false. This is because the || operator retums 1 if either or both statements are true. Logical NOT (!) Operator The NOT ( ! ) operator negates or reverses the value of its operand. If the operand statement is true, it returns false, and returns false if the operand is true. Here's an example: int x = 19; Serial.print(!(x > 5))s J) returns @ The code above returns 0, but why? x > 5 is true so the expected result is 1 We got 0 because the | operator reversed the return value of the operand from 0 to 1. Conditional Statements in Arduino You can use conditional statements to make decisions or execute code based on specific conditions. You can combine conditional statements and logic (like operators in the last section) to control how code is executed. Let's take a look at some conditional statements and how to use them: if Statement The if statement is used to execute code if a condition is true . Here's what the syntax looks like: if (condition) { 1/ code to be executed if condition is true ? In the syntax above, condition denotes a specified logic. If the condition is true then the code in the curly brackets will be executed. Here's an example: nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 20169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems int x= 55 if (xc 18) ¢ Serial.print("x is less than 10"); } J) xis less than 10 In the code above, we gave a condition— x < 10 —and a block of code within curly brackets that prints *x is less than 10°, The code in the curly brackets will only run if the condition is true. This is the same as saying "if x is less than 10 then print ‘x is less than 10! to the serial monitor’ Since x is less than 10, the condition evaluates as true and we get the message printed out. But what if the condition is false ? The code in the curly brackets won't run, so we'll need a different type of logic to handle situations like that. We can do this using the else statement. else Statement The else statements used to execute code if a condition is false Ant score = 205 Af (score > 58) { Serial.print(*You passed the exam!"); } else { Serial.print(*You have to rewrite the exan!"); J] You have to reurite the exam In the code above, the condition given is false . So the code for the else statement will be executed because the score variable is not greater than 50. Remember: the code for the else statement only runs when the condition is false . If the condition is true then the code forthe if statement will be executed. else if Statement You can use the else if statement to define multiple conditions to be checked. Here's the syntax: Af (condition) { // code to be executed if condition is true } else if (condition2){ 11 code to be executed if condition2 is true } else { II code to be executed if condition’ and condition2 are false nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 21169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems In the syntax above, there are two conditions (you can create more than two conditions). If condition is true , then code in the curly bracket for condition1 will be executed. Ifconditiont is false , then condition2 will be evaluated. If condition2 is true , its block of code will be executed. Ifboth conditiont and condition? are false ,the else statement’s code will be executed Ant score = 805 Af (score > 50) { Serial.print("You passed the exam!"); else if (score < 50) { Serial.print(*You have to rewrite the exar!” else { Serial.print(*No records for your exan score found!"); J You passed the exan! switch-case Statement In the last section, we saw how to create multiple conditions using cise if statements. Your code might become hard to read if you have many conditions. We can clean it up and make the code more readable using switch statements. Here's what the syntax looks like: switch (expression) { case 1 // Code to be executed if expression equals case 1 break; case 2: II Code to be executed if expression equals case 2 break; case 3 11 Code to be executed iF expression equals case 3 break; default // Code to be executed if expression doesn't match any case break; Let's break the syntax down: + The expression is compared to the value of each case + Whena case matches the expression , the code for that case is executed. + The break Keyword stops the switch statement's iteration once a match for the expression has been found, nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 22169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems + The code forthe default keyword is executed if none of the cases match the expression Here's an example: Aint day = 25 switen (day) ¢ case 1: Serial. print ("Monday"); print ("Tuesday"); print ("Wednesday"); print ("Thursday"); sprint ("Friday"); print ("Saturday"); print ("Sunday"); print ("Number out of range"); The code above prints "Tuesday" because the expression which has a value of 2 matches case 2 Loops in Arduino You can use loops to execute code repeatedly until a certain condition is met. You can also use loops to iterate over a collection of data and execute code on all elements of the collection. There are different type of loops you can use in Arduino like the for loop , while loop ,and do- while loop. Let's take a look at their syntax along with some practical examples: for loop You can use the for loop to iterate through a collection or execute code until a certain condition is, met. Itis commonly used when you know the number of times the loop is supposed to run. nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 23169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Here's the syntax’ for (initialization; condition; increment/decrenent) { 1 code to be executed ) There are three important keywords in the syntax above: + initialization denotes an initial variable (usually an integer) which specifies the starting point of the loop. + condition is used to control the number of times the loop is expected to run for. The loop stops when the condition is false + increment/decrement increases/decreases the value of the initial variable after every iteration, Here's an example to help you understand the keywords: for (int = 0; i ¢ 11; Serial.printn(i); > +) ul ul ul ul “ “ uw “ un Wu 30 In the loop above, we created an initial variable called 1 with a value of 0. The condition stated i < 11 which implies that the loop will continue to run as long as i is less than 11 Using the increment operator i++ , we increased the value of i by 1 every time the loop ran Lastly, we printed the value of i at every iteration. In the serial monitor, you'll notice the numbers from 0 to 10 printed out. This is because after the number 10, i is no longer less than 11 (the condition given), so the loop terminates. while loop The while loop works just like the for loop — it executes code as long as the given condition is, ‘true . But its often used when the number of times the loop is supposed to run is unknown. nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 24169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Here's the syntax’ while (condition) { 1 Code to be executed ? In the syntax above, the code will continue to run until the condition becomes false while Serial. So from the syntax above, datatype is the data type the function returns. Itcanbe int , string , and so on. A function that has no return statement uses the void type as its data type. The functionNane is the name given to the function. The name is used to call the function to execute the logic defined in the body of the function. You'd see words like "call", "fire", and "invoke" associated with functions. They all mean the same thing — to execute the function's logic. optionalParaneters are variables that you define when creating a function. They enable functions to accept external data which can be used within the function body. Function parameters are defined along with their data types. You'll understand this when we look at some examples. The body of the function is where all the logic goes to. What the function does when it is invoked is written in the body. Now that we've seen the different parts of a function, let's create some functions! How to Declare a Function with the void Type In the last chapter, we discussed the void Setup() and void loop() functions. They are two built- in functions that you'll use in every Arduino sketch. These functions are defined using the void keyword because they return nothing Here's what the syntax looks like for functions that use the void type: void functionNane(optionalParaneters) { 11 code logic } In the syntax above, functiontiane denotes the name of the function. We can use that name to call the function in order to execute the code defined in the function nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 28169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems optionalParameters are used to pass external data to the function while the code logic that runs when the function is called is written between the curly brackets. Here's an example: J) Function declaration void printNane(String userName) { Serial.printIn("Hello " = userName) ; } void setup() ¢ Serial .begin(9600); ) void loop) printNane("thechikara"); // function call delay (1000); In the code above, we created a function called printNiane which accepts a string parameter called userNane . The function's task is to print "Hello " along with whatever the parameter value is. Inthe void loop() , We called the function and passed a parameter to it: printNane("Thechikara") . In the serial monitor, you'll see "Hello Ihechikara” printed. To call a function, all you have to do is write the name of the function with parenthesis: printName() . Remember to pass in parameters when required: printNane("Thechikara" Using a parameter that has the wrong data type will result in an error. For instance, we defined a string parameter in our example. Using an integer will raise an error because the function expects a string. How to Declare a Function with a Return Data Type In this section, I'll use the int data type to show you how functions declared without the void type are used. The logic here is the same with other functions that use the return statement. nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 22169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems J) Function declaration int addNuns(int 2, int b) int result = 2 +b; return results > void setup() ¢ Serial .begin(9600) ; } void loop) Serial.println(addNuns(2, 1€)); // function call delay (1008); In the code above, we declared a function with the int type: int addNums(int a, int 6) (...} This implies that the function is expected to return an integer value. The function's logic adds the value of the two parameters ( 2 and b ) and returns their sum, We used the return statement to return the sum of the parameters We can now say that the task of the addNuns function is to return the sum of two given parameters. This can be seen when we used the function in the void loop() Serial.printn(acdNums(2, 1€)); We called the function with two parameters and got their sum printed out in the serial monitor. What You Should Know About the return Statement In the last two sections, we saw how to use functions in two different ways — functions that use the return statement and functions that don't use it, But what if you used the return statementin a void function? Would that break the code? The answer is no. I'l explain why. The main use of the return keyword is to return a value from the function, and then terminate the function. Consider the example below: int addNums(int 2, int b) ( int result = a 4b; Serial.println(result); return results Serial.printIn("Hello World”); nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 30169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems The function above takes in two parameters — a and b — and returns their sum. You'll notice that we printed "Hello World” after the return statement. The part of the code that comes after the return statement will not be executed because the function terminates/stops its operation once it sees a return statement So you should always remember that anything that comes after the return statement will be ignored You can use the return statement in void functions but it is a convention not to. We simply use the void keyword to define functions that have no use for the return statement. Commonly Used Built-in Functions in Arduino Sketch In this section, we'll discuss some of the commonly used built-in functions you'll come across when writing or reading Arduino code. We'll make use of them in most of the upcoming chapters of this handbook, We'll begin with the two main parts of an Arduino sketch —the setup() and loop() functions. setup() and loop() Functions in Arduino You can use the setup() function to configure analog and digital pins, initialize variables, and do other setup functionalities. The setup() function is executed once — when the board is powered on or reset. The 1oop() function runs continuously. This part of the sketch is where you write all the code logic. You can use the loop() function to give the Arduino board instructions on different components and sensors. void setup() ¢ > void loop) ¢ pinMode() Function in Arduino The pinviode() function is used to configure pins as input or output pins. It can also be used to configure a resistor to act as either a pull-up or pull-down resistor. You'll understand more about this function in the Sensors and Actuators chapter. nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 31169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Syntax pintode(pin, node) * pin denotes the pin number on an Arduino board. + mode denotes the configuration of the pin which can be INPUT, OUTPUT, or INPUT_PULLUP. digitalRead() Function in Arduino You can use the digitalnead() function to read the state of digital pins. It returns either 0 ( Low ) or 1 ( HIGH ), Syntax digitalRead(pin) Inthe code above, pin denotes the pin number on an Arduino board. digitalwrite() Function in Arduino The digitalurite() function assigns or writes values (either ixct or Low ) to digital pins. Syntax digitalWrite(pin, value) + pin denotes the pin number on an Arduino board. + value denotes the value to be assigned to pin .Canbe HIGH or Low analogRead() Function in Arduino The analogkead() function reads values from analog pins and returns values that fall within the range of 0 and 1023. Syntax ‘analogkead (pin) Inthe code above, pin denotes the pin number on an Arduino board. analogWrite() Function in Arduino This function writes or assigns an analog value to a pin. nips reecodecamp orginewsithe-arduino-handbooki¥chapter-S-how-tossse-sensors-and-actuatrs-in-arduino 32169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Syntax aralogersve(pin, value) + pin denotes the pin number on an Arduino board, + value denotes the value to be assigned to pin . Range from 0 to 255 Serial Functions in Arduino Serial communication enables an Arduino board to communicate with the computer and other devices using the built-in serial monitor, Here are some of the commonly used functions: Serial. begin() The Serial.begin() function initializes serial communication. Itis the first function you use when ‘working with the serial monitor. The function takes in a baud rate as its parameter. In this case, baud rate represents the rate or speed of data transfer in serial communication. Here's the syntax: Serial .begin(baudRate) Serial.print() and Serial.print1n() You can use the print() and printin() functions to print data to the serial monitor. print(val) printin(val) In the code above, val denotes the value to be printed, We'll talk more about serial communication in Chapter 6: How to use the Serial Monitor in Arduino, delay() Function in Arduino You can use the delay() function to pause the Arduino program for a specified amount of time. Here's what the syntax looks like: delay(ns) In the code above, ns denotes the specified time in milliseconds, nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 33169 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems Chapter 3: How to Use Digital Pins in Arduino Digital pins are used to send and receive digital signals in two states — HIGH and Low . The digital pins on a Arduino board can be configured as either input or output pins. These states can also be represented using numbers (1 for 1GH and 0 for Lowi ), or in volts (V) (5V for Hic and OV for Low ). The number and arrangement of pins differ in various Arduino boards, but they serve the same purpose. So if you understand how to use them in this chapter, you won't have a problem working with them in other boards. ‘The Uno board has 14 digital pins numbered from 0 to 13. Although each pin can be configured to serve as either a digital input or output pin, some of them come with extra functionalities like: + Pins 0 (RX) and 1 (TX) enable the Arduino board to communicate serially. RX receives while TX sends. + Pins that have the tilde (~) symbol beside them support PWM (Pulse Width Modulation) signals. This means that you can use these pins like analog pins (to receive analog values). + Pins 2 and 3 can be used for interrupt-based functionalities. How to Configure Digital Pins as Input or Output Pins When a digital pin is configured as an INPUT pin, it serves as a point for receiving information from ‘components. This way you get data from sensors, electronic components, and so on. You can use the pinsode() function to configure a pin to serve as either an INPUT or OUTPUT pin. Note that the pins on an Uno board are set to INPUT by default so if you don't specify prior to using them, they'll serve as input pins. In this section, you'll learn how to use digital pins as both input and output pins. You'll start by learning about them individually, and then see how to combine input and output signals to build a mini project. Welll start with INPUT. Digital Pins as INPUT The information or signal sent to input pins can be read using the digitalRead() function. In this section, you'll learn how to configure and read signals from a digital input pin using different built-in functions We'll use the following hardware components nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 4169 218124, 207 PM “The Arduino Handbook — Learn Microcontrollers for Embedded Systems Arduino Uno. Breadboard. Pushbutton. Jumper wires. Here's the diagram for the connection: Configuration diagram — INPUT Here's the code: Ant pushatn = 75 Ant push_btn_state; void setup()¢ pintode(pushBtn, INPUT_PULLUP); Serial. begin(9608) ; y void 1o0p(){ push_ptn_state = digitalRead(pushstn); Serial printIn(push_btn_state); delay(1208); > Let's break the code down, We started by creating two integer variables — pushbtn and push_btn_state : int pushBtn = 75 int push_btn_state; ntps:twwwfreecodecamp org neweithe-arduine-handbookitchapter-$-how-to-use-sensors-and-actuators-in-ardulno 218/24, 207 PM ‘The Arduino Handaook ~ Learn Microcontrollers for Embedded Systems pushin Was assigned a value of 7. We used this value to denote pin 7 on the Arduino board. We declared the push_btn_state variable but didn't assign any value to it because we'll use it to store the value of the push button later. In our setup() function, we configured the push button to act as an input pin using the pintode() function: pinode(pushBtn, TNPUT_PULLUP); The function took in two parameters — the pushstn variable which denoted pin 7, and INPUT_PULLUP which sets the pin as an input with a pull-up resistor. We also initialized the serial monitor using Serial. begin(36ee) AX this point, we've configured the Arduino software and hardware to recognize pin 7 as an input pit Next, we used the digitalRead() function to read signals coming from pin 7. Remember the push_btn_state variable we created? That's where we stored the signal: push_bte_state = digit Read (pushBtn) ; After that, we printed the value being read from pin 7 to the serial monitor using Serial.printIn(push_ptn_state); When you open the serial monitor, you'll see 1 being printed out repeatedly. This is the initial state of the pushbutton using a pull-up resistor. When you press down the pushbutton, the value will become 0. When you release the button, the value will become 1 Odenotes Low while 1 denotes Hci . With this example, you should understand how to configure, read, and display signals from an input pin. Digital Pins as OUTPUT The main use of an output pin is to send out signals. Since we're working with digital output, we can send either HIGH (SV) or Low (OV) signals. We can do this for digital pins using the digitalwrite() function. In this section, well use a LED (Light Emitting Diode) to demonstrate how to configure and send signals to components. Here are the components we'll use: + Arduino Uno, + Red LED. + 1k Ohm resistor, + Jumper wires. nips. reecodecamp orginewsithe-arduino-handbooki¥chapterS-how-tossse-sensors-and-actuatrs-in-arduino 36169

You might also like