10/03/2024 UNIT 1 INTRODUCTION TO ARDUINO MR. HARSHAL VAIDYA ASSISTANT PROFESSOR 1
10/03/2024 UNIT 1: INTRODUCTION TO ARDUINO 2 COURSE OBJECTIVE: 1. To understand arduino IDE; an open source platform and its basic programming features COURSE OUTCOME: CO1: APPLY Programming concepts to UNDERSTAND Role of microprocessor and Microcontroller in embedded systems
10/03/2024 EMBEDDED SYSTEMS 3 ■ Hard to Define ■ As, it constantly evolves with advances in technology and dramatic decreases in the cost of implementing various hardware and software components. ■ An embedded system is a system that has software embedded into computer-hardware, which makes a system dedicated for an application or specific part of an application or product or part of a larger system. ■ An embedded system is one that has a dedicated purpose software embedded in a computer hardware. ■ Based on Microprocessors or microcontrollers (embedded controllers).
10/03/2024 MICROPROCESSOR (MPU OR UP) 4 ■ MPU (CPU) ■ Read instructions ■ Process binary data A microprocessor is a computer processor which incorporates the functions of a computer's central processing unit (CPU) on a single integrated circuit (IC),or at most a few integrated circuits. They execute instructions, perform arithmetic and logic operations, and manage data flow within a system.
10/03/2024 MICROPROCESSOR-BASED SYSTEMS 5
10/03/2024 MICROCONTROLLERS (UC) 6 ■ more specialized devices designed to control and monitor specific functions in embedded systems contains ■ Microprocessor (MPU) ■ Memory ■ I/O (Input/output) ports ■ Support Devices ■Timers ■A/D converter ■Serial I/O
10/03/2024 MCU-BASED SYSTEM 7
10/03/2024 DIFFERENCES BETWEEN C AND P Μ Μ 8 μC μP
10/03/2024 9 Parameters Microprocessor Microcontroller 1. Function and Purpose: Primarily designed to execute general- purpose instructions and perform arithmetic and logic operations. It serves as the CPU of a computer system and is capable of running a variety of applications. Specifically designed to control a dedicated task or function within an embedded system. It integrates a CPU, memory, and various peripherals on a single chip, making it suitable for specific applications 2. Complexity Generally more powerful and complex, capable of handling complex computations and multitasking. It's designed to support a wide range of applications and software. Typically less powerful and less complex, as it's optimized for a specific task or set of tasks. Its resources are tailored to its intended application. 3. Power Consumption: May consume more power due to its higher processing capabilities and the need for external components. Designed for low power consumption, making it suitable for battery-operated devices and applications where energy efficiency is critical. 4. Peripherals: Relies on external components for peripheral support such as memory, input/output (I/O) ports, timers, and communication interfaces. Integrates essential peripherals like timers, I/O ports, analog-to-digital converters, communication interfaces (e.g., UART, SPI, I2C), and sometimes even specific hardware components (e.g., PWM generators) directly on the chip. 5. Cost Tends to be costlier due to its higher processing power and capabilities. more cost-effective, as it's optimized for specific tasks and may not require as much processing power as a microprocessor. 6. Applications: Used in computers, laptops, servers, and high-performance computing systems Found in embedded systems, consumer electronics, industrial automation, automotive control systems, medical devices, and more.
10/03/2024 Embedded systems play a pivotal role in today's interconnected world by providing dedicated functionality and intelligence to a wide range of devices, often operating behind the scenes without the user's direct awareness. These systems combine hardware and software to perform specific tasks efficiently and reliably, enabling the automation, control, and optimization of various processes. ROLE OF EMBEDDED SYSTEMS 10
10/03/2024 Here's a more detailed description of the role of embedded systems: 1.Task-Specific Functionality: Embedded systems are designed to fulfill specific functions or tasks within a larger system.Whether it's monitoring temperature in an industrial setting, controlling the engine of a car, or managing the user interface of a home appliance, embedded systems excel at executing tasks with precision. 2. Real-Time Control: Many embedded systems require real-time responsiveness, meaning they must process and respond to inputs within strict time constraints. For example, an anti-lock braking system in a car needs to react instantly to changing road conditions to ensure safe braking. ROLE OF EMBEDDED SYSTEMS 11
10/03/2024 3. Efficiency and Resource Optimization: Embedded systems are often resource-constrained, meaning they operate with limited processing power, memory, and energy resources. Engineers meticulously design these systems to achieve optimal performance while keeping resource usage to a minimum, leading to energy-efficient and cost-effective solutions. 4. Interconnectivity: With the rise of the Internet of Things (IoT), embedded systems are becoming increasingly interconnected.They communicate with other devices, networks, and cloud services, enabling data collection, analysis, and remote control.This interconnectedness has transformed industries such as home automation, industrial automation, healthcare, and agriculture. ROLE OF EMBEDDED SYSTEMS 12
10/03/2024 5. Reliability and Safety: Many embedded systems operate in safety- critical environments, where failures can have serious consequences.These systems undergo rigorous testing and validation to ensure reliability, safety, and adherence to industry standards. 6. Customization: Embedded systems can be customized to fit the specific requirements of a particular application.This adaptability allows manufacturers to create products that cater to niche markets and unique use cases. ROLE OF EMBEDDED SYSTEMS 13
10/03/2024 7. Ubiquitous Presence: Embedded systems are all around us, from smartphones and wearable devices to household appliances, medical equipment, transportation systems, and manufacturing machinery.They contribute to enhancing our daily lives, improving efficiency, and advancing technology. 8. Remote Monitoring and Control: Embedded systems enable remote monitoring and control of equipment and processes.This capability is essential in scenarios such as remote environmental monitoring, remote maintenance of machinery, and even space exploration. 9. Innovation: The field of embedded systems is dynamic and innovative, driving advancements in areas like robotics, automation, artificial intelligence, and machine learning.These systems are at the core of technological breakthroughs that shape the future. ROLE OF EMBEDDED SYSTEMS 14
10/03/2024 OPEN SOURCE EMBEDDED PLATFORMS 15 ■ Open source platform that can be freely used, changed and shared by anyone. ■ Open source software is made by many people and distributed under licenses that comply with the open source definition. ■ Hardware is also undergoing an open source revolution. The developer provides CAD files to the user. ■ Licensed under CERN or TAPR open h/w license.
10/03/2024 OPEN SOURCE EMBEDDED PLATFORMS : EXAMPLES 16 ■ Arduino ■ Banana Pi ■ BeagleBone Black ■ Panda board ■ OLinuXino
10/03/2024 Cost-Effective: Open source embedded platforms often come at a lower cost compared to proprietary solutions, making them accessible to a wide range of individuals and organizations. Innovation: The open nature of these platforms encourages innovation, as developers from different backgrounds can collaborate to create novel applications and features. Rapid Prototyping: Open source embedded platforms facilitate rapid prototyping and experimentation, allowing developers to quickly validate ideas and concepts. Diverse Ecosystem: The open source model leads to the growth of a diverse ecosystem of software libraries, tools, and extensions, enhancing the capabilities of these platforms. OPEN SOURCE EMBEDDED PLATFORMS ADVANTAGES 17
10/03/2024 WHAT IS ARDUINO 18 ■ Arduino is a movement, not a microcontroller: ■ Founded by Massimo Banzi and David Cuartielles in 2005 ■ Arduino is an open-source electronics platform based on easy-to-use hardware (uC) and software (IDE). ■ Arduino is open source hardware and software. ■ Hardware based on Microcontroller and Software based on Processing Programming IDE. ■ Arduino was designed for designers who want to incorporate physical computing into their designs without having knowledge of electrical & electronics. ■ Arduino makes your life simple by hiding away most of the complexities of programming microcontrollers.
10/03/2024 WHY ARDUINO 19 ■ Easy to use Hardware Platform ■ Ease of programming ■ Ease of Interfacing of Real life peripherals ■ Open source and extensible hardware ■ Open source and extensible software ■ Low Cost ■ Multiplatform environment
10/03/2024 FLAVORS OF ARDUINO H/W 20 resented By: Mr. Shridhar Dudam 14
10/03/2024 ARDUINO BOARDS 21 Arduino Uno Arduino Lily pad Arduino Mega Arduino Nano Arduino Ethernet
10/03/2024 TYPICAL ARDUINO UNO BOARD 22
10/03/2024 ATMEGA328 INTERNAL ARCHITECTURE 23
10/03/2024 Features ATmega328/P Microcontroller 8-bit family Architecture RISC Flash (Bytes) 32K SRAM (Bytes) 2K EEPROM (Bytes) 1K General Purpose I/O Lines 23 SPI 2 TWI (I2C) 1 USART 1 ADC 10-bit 15kSPS ADC Channels 8 8-bit Timer/ Counters 2 16-bit Timer/ Counters 1 Operating Voltage 1.8V-5.5V PWM Channels 6 Six Sleep Modes Idle ADC Noise Reduction Power-save Power-down Standby Extended standby 24
10/03/2024 ARDUINO IDE 25 • IDE stands for Integrated Development Environment. • open-source software, used to write and upload code to Arduino boards. • supports the programming languages C/C++. • Code is case sensitive • Statements are commands and must end with a semi-colon • Comments follow a // or begin with /* and end with */ See: http://arduino.cc/en/Guide/Environment for more information
10/03/2024 ARDUINO IDE : IMPORTANT ICONS 26 Link for more details: https://www.javatpoint.com/arduino-ide
10/03/2024 ARDUINO IDE : IMPORTANT ICONS 27 Upload  compiles and runs our code written on the screen and uploads the code to the connected board.  Before uploading the sketch, we need to make sure that the correct board and ports are selected.  We also need a USB connection to connect the board and the computer. click on the Upload button present on the toolbar.  If the uploading is failed, it will display the message in the error window. Open  opens the already created file. The selected file will be opened in the current window. Save  used to save the current sketch or code. New  used to create a new sketch or opens a new window. Verify  used to check the compilation error of the sketch or the written code. Serial Monitor  The serial monitor button is present on the right corner of the toolbar. It opens the serial monitor.
10/03/2024 SKETCH AND SKETCHBOOK 28 ■ Programs in Arduino called as sketches ■ Sketches must saved in the directory. ■ Arduino IDE uses the concept of a sketchbook: ■ A standard place to store programs (or sketches). ■ IDE automatically creates directory for the sketchbook. ■ Sketches were saved with a .ino file extension.
10/03/2024 ARDUINO IDE : SKETCH STRUCTURE 29
10/03/2024 ARDUINO IDE- OVERVIEW 30 1.Toolbar: The toolbar contains buttons for common actions such as opening, saving, and uploading code. It also houses buttons for verifying code (checking for errors) and opening the Serial Monitor. 2.Code Editor: The central area of the IDE is the code editor, where users write their Arduino code. Syntax highlighting, line numbers, and auto-indentation aid in code readability and writing. 3.Status Bar: The status bar at the bottom of the IDE provides useful information, including the current board, COM port, and upload progress. 4.Library Manager: This tool allows users to search for, install, and manage libraries to extend the capabilities of their projects without having to write code from scratch.
10/03/2024 ARDUINO IDE- OVERVIEW 31 5. Serial Monitor: The Serial Monitor is crucial for debugging and communicating with the Arduino board. It displays data sent from the board via the "Serial" object in the code. 6.Board Selector: Users can choose the specific Arduino board they are working with from the "Tools" menu. This selection configures the IDE for the correct compilation and upload settings. 7.Examples: The IDE provides a range of example sketches accessible through the "File" > "Examples" menu. These examples demonstrate how to use various sensors, components, and functionalities.
10/03/2024 Features: 1.Code Editor: The core feature of the Arduino IDE is its code editor, which provides syntax highlighting, auto-indentation, and code completion for a more efficient coding experience. 2.Library Management: Arduino IDE comes with a vast collection of libraries that offer pre-written code for various sensors, actuators, and functionalities. It also allows users to easily add and manage external libraries to expand the capabilities of their projects. 3.Serial Monitor: The Serial Monitor is a built-in tool that enables bidirectional communication between the Arduino board and the computer. It's essential for debugging and monitoring data exchange between the two. ARDUINO IDE- FEATURES 32
10/03/2024 4.Board Manager: Arduino supports a variety of hardware platforms beyond its core boards. The Board Manager simplifies the process of adding support for different Arduino-compatible boards and platforms. 5.Examples and Tutorials: The IDE includes a range of example sketches and tutorials that help users understand different aspects of programming and interfacing with hardware components. 6.Code Upload: Arduino IDE allows users to compile their code and upload it directly to their Arduino board using a USB connection. This seamless process makes it easy to test and run projects. 7.Version Control: While not as feature-rich as dedicated version control systems, the Arduino IDE offers basic version control features, allowing users to save and manage different versions of their code. ARDUINO IDE- FEATURES 33
10/03/2024 ARDUINO PROGRAMMING ENVIRONMENT 34 ■ Arduino uses Object Oriented Programming. ■ Arduino is programmed with C and C++. ■ All Arduino libraries are made using C++ in order to be easily reusable ■ The native library is designed for a very elementary and global purpose. ■ Arduino programs can be divided in ■ Structure (includes Conditional Statements) ■ Values (variables and constants) ■ Functions.
10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 35 ■ used to store a value or information so that we can refer to or/and manipulate it at a later stage during the life of the Arduino sketch. ■ Memory is set aside for storing the variable and the variable is given a name which allows us to access it in the sketch. ■ Before using variables, all variables must be declared. ■ After declaration, variable can used to store value by setting the values.
10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 36 Data type Size in Bytes Description char 1 Byte (8 bit) It stores 8 bit numerical ASCII value of characters like alphabets, symbols etc. It can also store a signed number that is in range of -128 to 127. Character literals are written in single quotes like 'a', '#' etc and their ASCII numerical is stored at corresponding variable location. unsigned char 1 Byte (8 bit) It can store 8 bit numerical ASCII values of characters, symbols etc and can also store any unsigned number in range of 0 to 255. Character literals are written in single quotes like 'a', '#' etc and their ASCII numerical is stored at corresponding variable location. int 2 Bytes (16 bits) Stores a 2 byte(16 bits) signed integer value that is in range of -32,768 to 32,767. unsigned int 2 Bytes (16 bits) Stores an unsigned integer value of 2 bytes(16 bits) that is in range of 0 to 65,535.
10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 37 Data type Size in Bytes Description short 2 Bytes (16 bits) Stores a 2 byte(16 bits) signed integer value that is in range of -32,768 to 32,767. unsigned short 2 Bytes (16 bits) Stores an unsigned integer value of 2 bytes(16 bits) that is in range of 0 to 65,535. long 4 Bytes Stores a 4 byte (32 bit) signed integer value that is in range of -2,147,483,648 to 2,147,483,647. unsigned long 4 Bytes Stores an unsigned 4 byte(32 bit) integer that is in range of 0 to 4,294,967,295 (232 - 1 ). float 4 Bytes Stores a signed 4 byte(32-bit) value that is integer or a value with decimal point (say 12.15) that is in range of -3.4028235E+38 to 3.4028235E+38. double 4 Bytes Same as float.
10/03/2024 DEFINING A VARIABLE 38 ■ The standard form of variable definition is: Variable_Datatype Variable_Name; ■ Variable_Datatype can be int or float depending on the type of variable you want. ■ Variable_Name is the name of the variable. The variable is referenced or used by its name later in the program. ■ By giving the variable a type and name, space is made available in memory for this variable.
10/03/2024 HOW TO NAME A VARIABLE 39 ■ You can give a variable any name as long as it sticks to the rules set out below. It is best to give variables meaningful names that help you and others understand the sketch better. 1. Variables can consist of both uppercase (A-Z) and lowercase(a-z) letters. 2. Variables can contain numbers 0 to 9, but cannot start with a number. 3. Variables may not have the same names as Arduino language keywords, e.g. you cannot have a variable named float. 4. Variables must have unique names, i.e. you cannot have two variables with the same name. 5. Variable names are case-sensitive, so Count and count are two different variables. 6. Variables may not contain any special characters, except the underscore (_).
1. pinMode(): need to set its mode as either INPUT or OUTPUT using the pinMode() function. It is used under void setup() loop. Syntax: pinMode(pin, mode) For example: pinMode(13, OUTPUT); // Sets digital pin 13 as an output pinMode(A0, INPUT); // Sets analog pin A0 as an input 2. digitalWrite(): For digital pins configured as OUTPUT, you can use the digitalWrite() function to set the pin's state to HIGH or LOW. It is used in main loop. Before using this command, digital pin must be set as output pin using command pinMode(). Syntax: digitalWrite(pin, value) For example: digitalWrite(13, HIGH); // Sets digital pin 13 to HIGH (5V) digitalWrite(13, LOW); // Sets digital pin 13 to LOW (0V) PROGRAMMING CONCEPTS: FUNCTIONS
3.digitalRead() : For digital pins configured as INPUT, you can use the digitalRead() function to read the pin's state. It is used in main loop. Before using this command, digital pin must be set as output pin using command pinMode(). Syntax: digitalRead(pin) Example: int value = digitalRead(2); // Reads the state of digital pin 2 (HIGH or LOW) 4. analogRead(): For analog pins, you can use the analogRead() function to read the analog voltage and convert it to a digital value: Syntax: analogRead(pin) Example: int analogValue = analogRead(A0); // Reads the analog value from pin A0 5. analogWrite(): the analogWrite() function used for generating PWM on Digital Pin, vary intensity of LED or vary motor speed Syntax: analogWrite(pin,value) Example: analogWrite(11,digitalInput); // Write Analog output in pin 11 PROGRAMMING CONCEPTS: FUNCTIONS
6. Serial.begin(): The Serial.begin() sets the baud rate for serial data communication. The baud rate signifies the data rate in bits per second. The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc. The Serial.begin( ) is declared in two formats, which are shown below: i) begin( speed ) ii) begin( speed, config) Where, serial: It signifies the serial port object. speed: It signifies the baud rate or bps (bits per second) rate. It allows long data types. config: It sets the stop, parity, and data bits.  Example void setup ( ) { Serial.begin(4800); } void loop ( ) { } PROGRAMMING CONCEPTS: FUNCTIONS
7. Serial.read() : The Serial.read( ) in Arduino reads the incoming serial data in the Arduino. The int data type is used here. It returns the first data byte of the arriving serial data. It also returns -1 when no data is available on the serial port. The syntax used in the Arduino programming is Serial.read( ), Where, serial: It signifies the serial port object. The data is stored in the form of bytes, where 1 byte = 8 bits. Let's understand with an example. int arrivingdatabyte; void setup( ) { Serial.begin(9600); } void loop( ) { if(Serial.available( ) > 0) { arrivingdatabyte = Serial.read( ); // It will read the incoming or arrivi ng data byte Serial.print("data byte received:"); Serial.println(arrivingdatabyte); } } PROGRAMMING CONCEPTS: FUNCTIONS
8. Serial.write(): It sends the binary data to the serial port in Arduino. The data through Serial.write is sent as a series of bytes or a single byte. If we want to send the digits of numbers represented by the characters, we need to use the Serial.print( ) function instead of Serial.write( ). The Serial.write( ) function will return the number of written bytes. The Serial.write( ) is declared in three formats, which are shown below:  write(str)  write(value)  write(buffer, len) Where, Serial: It signifies the serial port object. str: The str means string, which sends the data as a series of bytes. buffer: It is an array that is used to send the data as a series of bytes. value: It sends the data to the Arduino as a single byte. len: It signifies the number of bytes, which can be sent from the array. Example void setup( ) { Serial.begin(14400); } void loop( ) { Serial.write(55); // the specified value is 55. // Serial.write( ) send the data as a byte with this value (55). int Bytestosend = Serial.write( " Arduino" ); // It sends the Arduino string. //The length of the string is a return parameter in this function. } PROGRAMMING CONCEPTS: FUNCTIONS
9. delay() function The delay()function pauses the program or task for a specified duration of time. The time is specified inside the open and closed parentheses in milliseconds. Where, 1 second = 1000 milliseconds The program waits for a specified duration before proceeding onto the next line of the code. The delay( ) function allows the unsigned long data type in the code. We can create many sketches using the short and long delays depending on the requirements in the project. It does not disable any interrupts. But, the delay( ) function has some drawbacks.  Example void setup ( ) { Serial.begin ( 4800); // opens the serial port and set the bits per rate to 4800 } void loop ( ) { Serial.print(" Welcome"); delay(1000); Serial.println("to delay"); // It will print 'to delay' followed by a new line. delay ( 500); // delay of 0.5 seconds between each printed line. } PROGRAMMING CONCEPTS: FUNCTIONS
10/03/2024 STRUCTURE 46 ■ From global conditional control structures to more specific ones. ■ Basic Structure ■ setup() ■ loop() ■ Control Structures (Conditional Statements) ■ if , if...else and switch case ■ for, while and do... while ■ break and continue ■ return ■ goto
10/03/2024 ARDUINO IDE : SKETCH STRUCTURE 47
10/03/2024 CONDITIONAL STATEMENTS 48
10/03/2024 CONDITIONAL STATEMENTS 49 1. If Conditional Statement: ■ most basic form of conditional statement. It checks if a condition is true. ■ If it is, the program executes a block of code. ■ Syntax: if (condition) { // code to execute if condition is true } ■ if condition is true, the if code block executes. ■ If false, the execution moves to the next block to check.
10/03/2024 CONDITIONAL STATEMENTS 50 1. If Conditional Statement:
10/03/2024 CONDITIONAL STATEMENTS 51 1. If Conditional Statement: Use Cases: ■ Checking a single condition and executing code based on its result. ■ Performing actions based on user input. Applications: ■ Validating user inputs. ■ Basic decision-making in algorithms. Advantages: ■ Simple and straightforward. ■ Useful for handling basic decision logic. Disadvantages: ■ Limited to checking only one condition at a time. ■ Not suitable for complex
10/03/2024 CONDITIONAL STATEMENTS 52 1. If Conditional Statement: int a = 6; // initiaization of values to variables a and b int b = 4; void setup() { Serial.begin(9600); } void loop() { if (a > b ) { Serial.println( " a is greater than b "); } if (b > a ) { Serial.println( " b is greater than a "); } }
10/03/2024 CONDITIONAL STATEMENTS 53 2. If-Else Conditional Statement: ■ extends the if statement by adding an else clause. ■ If the condition is false, the program executes the code in the else block. ■ Syntax: if (condition) { // code to execute if condition is true } else { // code to execute if condition is false } ■ if condition is true, the if code block executes. ■ If false, the execution moves to the else block.
10/03/2024 CONDITIONAL STATEMENTS 54 2. If-Else Conditional Statement :
10/03/2024 CONDITIONAL STATEMENTS 55 2. If-Else Conditional Statement : Use Cases: ■ Executing one block of code if a condition is true and another block if it’s false. ■ Handling binary decisions. Applications: ■ Error handling: For example, displaying an error message if user input is invalid. ■ Program flow control: Directing program execution based on conditions. Advantages: ■ Handles binary decisions efficiently.. ■ Clear and concise syntax. Disadvantages: ■ Limited to binary decisions. ■ May become verbose in complex scenarios
10/03/2024 CONDITIONAL STATEMENTS 56 2. If-Else Conditional Statement :
10/03/2024 CONDITIONAL STATEMENTS 57 3. if-Else if Conditional Statement: ■ allows for multiple conditions to be checked in sequence. ■ if condition is false, the program checks the next else if condition, and so on. ■ Syntax: if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition2 is true } else { // code to execute if all conditions are false } ■ In else if statements, the conditions are checked from the top-down, if the first block returns true, the second and the third blocks will not be checked, but if the first if block returns false, the second block will be checked. This checking continues until a block returns a true outcome.
10/03/2024 CONDITIONAL STATEMENTS 58 3. if-Else if Conditional Statement:
10/03/2024 CONDITIONAL STATEMENTS 59 3. if-Else if Conditional Statement: Use Cases: ■ Handling multiple conditions sequentially. ■ Implementing multi-way decision logic. Applications: ■ Implementing menu selection logic. ■ Categorizing data based on multiple criteria. Advantages: ■ Allows handling multiple conditions in a structured manner. ■ Reduces the need for nested if-else statements. Disadvantages: ■ Can become lengthy and harder to maintain with many conditions. ■ The order of conditions matters; incorrect ordering can lead to unexpected behavior.
10/03/2024 CONDITIONAL STATEMENTS 60 3. if-Else if Conditional Statement: int i = 2; int j = 3; void setup ( ) { Serial.begin(9600); } void loop ( ) { if ( i > j ) { Serial.println( " I is greater "); } else if ( i < j ) { Serial.println( " J is greater " ); } else { Serial.println( " Both are equal " ); } }
10/03/2024 CONDITIONAL STATEMENTS 61 4. Switch Conditional Statement: ■ used when you need to check a variable against a series of values. ■ often used as a more readable alternative to a long if-else if chain. ■ each block is terminated by a break keyword. ■ The statements in switch are expressed with cases ■ Syntax: switch (variable) { case value1: // code to execute if variable equals value1 break; case value2: // code to execute if variable equals value2 break; default: // code to execute if variable doesn't match any value }
10/03/2024 CONDITIONAL STATEMENTS 62 4. Switch Conditional Statement:
10/03/2024 CONDITIONAL STATEMENTS 63 4. Switch Conditional Statement: Use Cases: ■ Selecting one of many code blocks to execute based on the value of a variable. ■ Handling multiple cases efficiently. Applications: ■ Processing user choices in a menu. ■ Implementing state machines. Advantages: ■ Provides a clean and efficient way to handle multiple cases. ■ Improves code readability when dealing with many conditions. Disadvantages: ■ Limited to equality comparisons, cannot use range checks or complex conditions.. ■ Lack of fall-through control can lead to unintentional bugs if not used carefully.
10/03/2024 CONDITIONAL STATEMENTS 64 4. Switch Conditional Statement: void setup() { Serial.begin(9600); int a = 1; switch(a) // the case matching the value in the declared variable wi ll run { case 1: Serial.println(" Case 1 matches"); // the value of variable matches with the value in case 1. // The message associated with case 1 will be printed break; case 2: Serial.println(" Case 2 matches"); break; default: Serial.println(" default matches"); break; } } void loop() { }
10/03/2024 Loop statement : for loop 65 ■ Syntax ■ example CONDITIONAL STATEMENTS ■ statements inside the curly brackets under for loop are executed repeatedly according to the specified condition. An increment counter in the for loop is used to increment or decrement the loop repetitions. ■ The for statement is commonly used for repetitive task or operation or to operate on the group of data/pins in combination with arrays.
10/03/2024 CONDITIONAL STATEMENTS 66 ■ Syntax ■ Example Loop statement : while loop ■ the conditional loop that continues to execute the code inside the parentheses until the specified condition becomes false. ■ never exit until the tested condition is changed or made to stop. ■ The common use of a while loop in Arduino includes sensor testing, calibration (calibrating the input of sensor), variable increment, etc.
10/03/2024 67
10/03/2024 STRUCTURE : OPERATORS 68 Arithmetic Operators Comparison Operators = (assignment operator) == (equal to) + (addition) != (not equal to) - (subtraction) < (less than) * (multiplication) > (greater than) / (division) <= (less than or equal to) % (modulo) >= (greater than or equal to) Bitwise Operators Compound Operators & (bitwise and) ++ (increment) | (bitwise or) -- (decrement) ^ (bitwise xor) += (compound addition) ~ (bitwise not) -= (compound subtraction) << (bitshift left) *= (compound multiplication) >> (bitshift right) /= (compound division) %= (compound modulo) &= (compound bitwise and) |= (compound bitwise or)
10/03/2024 STRUCTURE : OPERATORS 69 Boolean Operators Pointer Access Operators && (and) || (or) ! (not) * dereference operator & reference operator
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 70 GPIO (General Purpose Input/Output) ■ software controlled interface found on Microcontrollers and some Microprocessor ICs or interface chipsets ■ one or more pins on the IC which have no special purpose in themselves, but which facilitate an optional ability for device designers to create an interface/connection between the IC and a peripheral component by programming some hardware registers. Some basic GPIO capabilities are : ■ GPIO Pins can be enabled or disabled as needed ■ Output values are writable (high=1, low=0) ■ Input values are readable (high=1, low=0) ■ Inputs can often be used as IRQ (Interrupt Request) signals, Edge triggered or Level triggered. Such IRQs may be configurable to wake the system from a low power state
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 71 GPIO Input Output Modes ■High Impedance / Floating / Hi-Z / Tri-Stated ■Input Mode with Pull-Up or Pull- Down ■Output Mode with Open Drain ■Output Mode with Push Pull
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 72 High Impedance / Floating / Hi-Z / Tri-Stated ■When a GPIO pin put into a High Impedance state, effectively gets disconnected from the external interface. ■ The basic concept is to effectively remove the device’s influence from the rest of the circuit. ■If more than one device is electrically connected to another device, putting a pin into the Hi-Z state is often used to prevent short circuits, or one device driving high (logical 1) against another device driving low (logical 0).
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 73 Input Mode with Pull-Up or Pull-Down ■When a GPIO pin is used with an Internal or External Pull -Up or Pull-Down Resistor to ensure a known state of logic. ■It is used typically with a switch or input device such that whenever the switch is pressed or input comes it toggles the logic level. ■Pull-Up ensures a well-defined Logic Level of High = 1. A Pull-Up resistor usually connects the pin to Vcc. ■It holds the logic too High when no other active input comes. ■Pull-Down ensures a well-defined Logic Level of Low = 1. A Pull-Down resistor usually connects the pin to GND. ■It holds the logic to Low when no other active input comes.
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 74 Output Mode with Open Drain ■An Open Drain output can take two states Low Impedance and High Impedance. In a Low Impedance state, it can sink current. It is like a switch that is either connected to the ground or open. ■The MOSFET has three terminals called: gate, source, and drain. In an open-drain configuration, the source is grounded, the gate is driven internally, and the drain is the pin (i.e. not connected to external hardware). When the Gate is driven, Drain gets connected with the Source and the PIN gets a Logic Low = 0. Otherwise, the PIN remains at High-Z state which is useless until a Pull-Up is used.
10/03/2024 CONCEPT OF GPIO IN ATMEGA328 BASED ARDUINO BOARD 75 Output Mode with Push Pull A Push-Pull output is capable of both sourcing and sinking current. ■When the top transistor [PMOS] will be activated, the output PIN will be HIGH and act as a Source. When the NMOS below will be on, the output PIN is driven LOW and act as a Sink. It is a complementary logic and only once MOS will be activated at a time.

Unit 1 Introduction to Arduino Board.pptx

  • 1.
    10/03/2024 UNIT 1 INTRODUCTION TOARDUINO MR. HARSHAL VAIDYA ASSISTANT PROFESSOR 1
  • 2.
    10/03/2024 UNIT 1: INTRODUCTIONTO ARDUINO 2 COURSE OBJECTIVE: 1. To understand arduino IDE; an open source platform and its basic programming features COURSE OUTCOME: CO1: APPLY Programming concepts to UNDERSTAND Role of microprocessor and Microcontroller in embedded systems
  • 3.
    10/03/2024 EMBEDDED SYSTEMS 3 ■ Hardto Define ■ As, it constantly evolves with advances in technology and dramatic decreases in the cost of implementing various hardware and software components. ■ An embedded system is a system that has software embedded into computer-hardware, which makes a system dedicated for an application or specific part of an application or product or part of a larger system. ■ An embedded system is one that has a dedicated purpose software embedded in a computer hardware. ■ Based on Microprocessors or microcontrollers (embedded controllers).
  • 4.
    10/03/2024 MICROPROCESSOR (MPU ORUP) 4 ■ MPU (CPU) ■ Read instructions ■ Process binary data A microprocessor is a computer processor which incorporates the functions of a computer's central processing unit (CPU) on a single integrated circuit (IC),or at most a few integrated circuits. They execute instructions, perform arithmetic and logic operations, and manage data flow within a system.
  • 5.
  • 6.
    10/03/2024 MICROCONTROLLERS (UC) 6 ■ morespecialized devices designed to control and monitor specific functions in embedded systems contains ■ Microprocessor (MPU) ■ Memory ■ I/O (Input/output) ports ■ Support Devices ■Timers ■A/D converter ■Serial I/O
  • 7.
  • 8.
    10/03/2024 DIFFERENCES BETWEEN CAND P Μ Μ 8 μC μP
  • 9.
    10/03/2024 9 Parameters MicroprocessorMicrocontroller 1. Function and Purpose: Primarily designed to execute general- purpose instructions and perform arithmetic and logic operations. It serves as the CPU of a computer system and is capable of running a variety of applications. Specifically designed to control a dedicated task or function within an embedded system. It integrates a CPU, memory, and various peripherals on a single chip, making it suitable for specific applications 2. Complexity Generally more powerful and complex, capable of handling complex computations and multitasking. It's designed to support a wide range of applications and software. Typically less powerful and less complex, as it's optimized for a specific task or set of tasks. Its resources are tailored to its intended application. 3. Power Consumption: May consume more power due to its higher processing capabilities and the need for external components. Designed for low power consumption, making it suitable for battery-operated devices and applications where energy efficiency is critical. 4. Peripherals: Relies on external components for peripheral support such as memory, input/output (I/O) ports, timers, and communication interfaces. Integrates essential peripherals like timers, I/O ports, analog-to-digital converters, communication interfaces (e.g., UART, SPI, I2C), and sometimes even specific hardware components (e.g., PWM generators) directly on the chip. 5. Cost Tends to be costlier due to its higher processing power and capabilities. more cost-effective, as it's optimized for specific tasks and may not require as much processing power as a microprocessor. 6. Applications: Used in computers, laptops, servers, and high-performance computing systems Found in embedded systems, consumer electronics, industrial automation, automotive control systems, medical devices, and more.
  • 10.
    10/03/2024 Embedded systems playa pivotal role in today's interconnected world by providing dedicated functionality and intelligence to a wide range of devices, often operating behind the scenes without the user's direct awareness. These systems combine hardware and software to perform specific tasks efficiently and reliably, enabling the automation, control, and optimization of various processes. ROLE OF EMBEDDED SYSTEMS 10
  • 11.
    10/03/2024 Here's a moredetailed description of the role of embedded systems: 1.Task-Specific Functionality: Embedded systems are designed to fulfill specific functions or tasks within a larger system.Whether it's monitoring temperature in an industrial setting, controlling the engine of a car, or managing the user interface of a home appliance, embedded systems excel at executing tasks with precision. 2. Real-Time Control: Many embedded systems require real-time responsiveness, meaning they must process and respond to inputs within strict time constraints. For example, an anti-lock braking system in a car needs to react instantly to changing road conditions to ensure safe braking. ROLE OF EMBEDDED SYSTEMS 11
  • 12.
    10/03/2024 3. Efficiency andResource Optimization: Embedded systems are often resource-constrained, meaning they operate with limited processing power, memory, and energy resources. Engineers meticulously design these systems to achieve optimal performance while keeping resource usage to a minimum, leading to energy-efficient and cost-effective solutions. 4. Interconnectivity: With the rise of the Internet of Things (IoT), embedded systems are becoming increasingly interconnected.They communicate with other devices, networks, and cloud services, enabling data collection, analysis, and remote control.This interconnectedness has transformed industries such as home automation, industrial automation, healthcare, and agriculture. ROLE OF EMBEDDED SYSTEMS 12
  • 13.
    10/03/2024 5. Reliability andSafety: Many embedded systems operate in safety- critical environments, where failures can have serious consequences.These systems undergo rigorous testing and validation to ensure reliability, safety, and adherence to industry standards. 6. Customization: Embedded systems can be customized to fit the specific requirements of a particular application.This adaptability allows manufacturers to create products that cater to niche markets and unique use cases. ROLE OF EMBEDDED SYSTEMS 13
  • 14.
    10/03/2024 7. Ubiquitous Presence:Embedded systems are all around us, from smartphones and wearable devices to household appliances, medical equipment, transportation systems, and manufacturing machinery.They contribute to enhancing our daily lives, improving efficiency, and advancing technology. 8. Remote Monitoring and Control: Embedded systems enable remote monitoring and control of equipment and processes.This capability is essential in scenarios such as remote environmental monitoring, remote maintenance of machinery, and even space exploration. 9. Innovation: The field of embedded systems is dynamic and innovative, driving advancements in areas like robotics, automation, artificial intelligence, and machine learning.These systems are at the core of technological breakthroughs that shape the future. ROLE OF EMBEDDED SYSTEMS 14
  • 15.
    10/03/2024 OPEN SOURCE EMBEDDEDPLATFORMS 15 ■ Open source platform that can be freely used, changed and shared by anyone. ■ Open source software is made by many people and distributed under licenses that comply with the open source definition. ■ Hardware is also undergoing an open source revolution. The developer provides CAD files to the user. ■ Licensed under CERN or TAPR open h/w license.
  • 16.
    10/03/2024 OPEN SOURCE EMBEDDEDPLATFORMS : EXAMPLES 16 ■ Arduino ■ Banana Pi ■ BeagleBone Black ■ Panda board ■ OLinuXino
  • 17.
    10/03/2024 Cost-Effective: Open sourceembedded platforms often come at a lower cost compared to proprietary solutions, making them accessible to a wide range of individuals and organizations. Innovation: The open nature of these platforms encourages innovation, as developers from different backgrounds can collaborate to create novel applications and features. Rapid Prototyping: Open source embedded platforms facilitate rapid prototyping and experimentation, allowing developers to quickly validate ideas and concepts. Diverse Ecosystem: The open source model leads to the growth of a diverse ecosystem of software libraries, tools, and extensions, enhancing the capabilities of these platforms. OPEN SOURCE EMBEDDED PLATFORMS ADVANTAGES 17
  • 18.
    10/03/2024 WHAT IS ARDUINO 18 ■Arduino is a movement, not a microcontroller: ■ Founded by Massimo Banzi and David Cuartielles in 2005 ■ Arduino is an open-source electronics platform based on easy-to-use hardware (uC) and software (IDE). ■ Arduino is open source hardware and software. ■ Hardware based on Microcontroller and Software based on Processing Programming IDE. ■ Arduino was designed for designers who want to incorporate physical computing into their designs without having knowledge of electrical & electronics. ■ Arduino makes your life simple by hiding away most of the complexities of programming microcontrollers.
  • 19.
    10/03/2024 WHY ARDUINO 19 ■ Easyto use Hardware Platform ■ Ease of programming ■ Ease of Interfacing of Real life peripherals ■ Open source and extensible hardware ■ Open source and extensible software ■ Low Cost ■ Multiplatform environment
  • 20.
    10/03/2024 FLAVORS OF ARDUINOH/W 20 resented By: Mr. Shridhar Dudam 14
  • 21.
    10/03/2024 ARDUINO BOARDS 21 Arduino Uno ArduinoLily pad Arduino Mega Arduino Nano Arduino Ethernet
  • 22.
  • 23.
  • 24.
    10/03/2024 Features ATmega328/P Microcontroller 8-bitfamily Architecture RISC Flash (Bytes) 32K SRAM (Bytes) 2K EEPROM (Bytes) 1K General Purpose I/O Lines 23 SPI 2 TWI (I2C) 1 USART 1 ADC 10-bit 15kSPS ADC Channels 8 8-bit Timer/ Counters 2 16-bit Timer/ Counters 1 Operating Voltage 1.8V-5.5V PWM Channels 6 Six Sleep Modes Idle ADC Noise Reduction Power-save Power-down Standby Extended standby 24
  • 25.
    10/03/2024 ARDUINO IDE 25 • IDEstands for Integrated Development Environment. • open-source software, used to write and upload code to Arduino boards. • supports the programming languages C/C++. • Code is case sensitive • Statements are commands and must end with a semi-colon • Comments follow a // or begin with /* and end with */ See: http://arduino.cc/en/Guide/Environment for more information
  • 26.
    10/03/2024 ARDUINO IDE :IMPORTANT ICONS 26 Link for more details: https://www.javatpoint.com/arduino-ide
  • 27.
    10/03/2024 ARDUINO IDE :IMPORTANT ICONS 27 Upload  compiles and runs our code written on the screen and uploads the code to the connected board.  Before uploading the sketch, we need to make sure that the correct board and ports are selected.  We also need a USB connection to connect the board and the computer. click on the Upload button present on the toolbar.  If the uploading is failed, it will display the message in the error window. Open  opens the already created file. The selected file will be opened in the current window. Save  used to save the current sketch or code. New  used to create a new sketch or opens a new window. Verify  used to check the compilation error of the sketch or the written code. Serial Monitor  The serial monitor button is present on the right corner of the toolbar. It opens the serial monitor.
  • 28.
    10/03/2024 SKETCH AND SKETCHBOOK 28 ■Programs in Arduino called as sketches ■ Sketches must saved in the directory. ■ Arduino IDE uses the concept of a sketchbook: ■ A standard place to store programs (or sketches). ■ IDE automatically creates directory for the sketchbook. ■ Sketches were saved with a .ino file extension.
  • 29.
    10/03/2024 ARDUINO IDE :SKETCH STRUCTURE 29
  • 30.
    10/03/2024 ARDUINO IDE- OVERVIEW 30 1.Toolbar:The toolbar contains buttons for common actions such as opening, saving, and uploading code. It also houses buttons for verifying code (checking for errors) and opening the Serial Monitor. 2.Code Editor: The central area of the IDE is the code editor, where users write their Arduino code. Syntax highlighting, line numbers, and auto-indentation aid in code readability and writing. 3.Status Bar: The status bar at the bottom of the IDE provides useful information, including the current board, COM port, and upload progress. 4.Library Manager: This tool allows users to search for, install, and manage libraries to extend the capabilities of their projects without having to write code from scratch.
  • 31.
    10/03/2024 ARDUINO IDE- OVERVIEW 31 5.Serial Monitor: The Serial Monitor is crucial for debugging and communicating with the Arduino board. It displays data sent from the board via the "Serial" object in the code. 6.Board Selector: Users can choose the specific Arduino board they are working with from the "Tools" menu. This selection configures the IDE for the correct compilation and upload settings. 7.Examples: The IDE provides a range of example sketches accessible through the "File" > "Examples" menu. These examples demonstrate how to use various sensors, components, and functionalities.
  • 32.
    10/03/2024 Features: 1.Code Editor: Thecore feature of the Arduino IDE is its code editor, which provides syntax highlighting, auto-indentation, and code completion for a more efficient coding experience. 2.Library Management: Arduino IDE comes with a vast collection of libraries that offer pre-written code for various sensors, actuators, and functionalities. It also allows users to easily add and manage external libraries to expand the capabilities of their projects. 3.Serial Monitor: The Serial Monitor is a built-in tool that enables bidirectional communication between the Arduino board and the computer. It's essential for debugging and monitoring data exchange between the two. ARDUINO IDE- FEATURES 32
  • 33.
    10/03/2024 4.Board Manager: Arduinosupports a variety of hardware platforms beyond its core boards. The Board Manager simplifies the process of adding support for different Arduino-compatible boards and platforms. 5.Examples and Tutorials: The IDE includes a range of example sketches and tutorials that help users understand different aspects of programming and interfacing with hardware components. 6.Code Upload: Arduino IDE allows users to compile their code and upload it directly to their Arduino board using a USB connection. This seamless process makes it easy to test and run projects. 7.Version Control: While not as feature-rich as dedicated version control systems, the Arduino IDE offers basic version control features, allowing users to save and manage different versions of their code. ARDUINO IDE- FEATURES 33
  • 34.
    10/03/2024 ARDUINO PROGRAMMING ENVIRONMENT 34 ■Arduino uses Object Oriented Programming. ■ Arduino is programmed with C and C++. ■ All Arduino libraries are made using C++ in order to be easily reusable ■ The native library is designed for a very elementary and global purpose. ■ Arduino programs can be divided in ■ Structure (includes Conditional Statements) ■ Values (variables and constants) ■ Functions.
  • 35.
    10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 35 ■used to store a value or information so that we can refer to or/and manipulate it at a later stage during the life of the Arduino sketch. ■ Memory is set aside for storing the variable and the variable is given a name which allows us to access it in the sketch. ■ Before using variables, all variables must be declared. ■ After declaration, variable can used to store value by setting the values.
  • 36.
    10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 36 Datatype Size in Bytes Description char 1 Byte (8 bit) It stores 8 bit numerical ASCII value of characters like alphabets, symbols etc. It can also store a signed number that is in range of -128 to 127. Character literals are written in single quotes like 'a', '#' etc and their ASCII numerical is stored at corresponding variable location. unsigned char 1 Byte (8 bit) It can store 8 bit numerical ASCII values of characters, symbols etc and can also store any unsigned number in range of 0 to 255. Character literals are written in single quotes like 'a', '#' etc and their ASCII numerical is stored at corresponding variable location. int 2 Bytes (16 bits) Stores a 2 byte(16 bits) signed integer value that is in range of -32,768 to 32,767. unsigned int 2 Bytes (16 bits) Stores an unsigned integer value of 2 bytes(16 bits) that is in range of 0 to 65,535.
  • 37.
    10/03/2024 PROGRAMMING CONCEPTS: VARIABLES 37 Datatype Size in Bytes Description short 2 Bytes (16 bits) Stores a 2 byte(16 bits) signed integer value that is in range of -32,768 to 32,767. unsigned short 2 Bytes (16 bits) Stores an unsigned integer value of 2 bytes(16 bits) that is in range of 0 to 65,535. long 4 Bytes Stores a 4 byte (32 bit) signed integer value that is in range of -2,147,483,648 to 2,147,483,647. unsigned long 4 Bytes Stores an unsigned 4 byte(32 bit) integer that is in range of 0 to 4,294,967,295 (232 - 1 ). float 4 Bytes Stores a signed 4 byte(32-bit) value that is integer or a value with decimal point (say 12.15) that is in range of -3.4028235E+38 to 3.4028235E+38. double 4 Bytes Same as float.
  • 38.
    10/03/2024 DEFINING A VARIABLE 38 ■The standard form of variable definition is: Variable_Datatype Variable_Name; ■ Variable_Datatype can be int or float depending on the type of variable you want. ■ Variable_Name is the name of the variable. The variable is referenced or used by its name later in the program. ■ By giving the variable a type and name, space is made available in memory for this variable.
  • 39.
    10/03/2024 HOW TO NAMEA VARIABLE 39 ■ You can give a variable any name as long as it sticks to the rules set out below. It is best to give variables meaningful names that help you and others understand the sketch better. 1. Variables can consist of both uppercase (A-Z) and lowercase(a-z) letters. 2. Variables can contain numbers 0 to 9, but cannot start with a number. 3. Variables may not have the same names as Arduino language keywords, e.g. you cannot have a variable named float. 4. Variables must have unique names, i.e. you cannot have two variables with the same name. 5. Variable names are case-sensitive, so Count and count are two different variables. 6. Variables may not contain any special characters, except the underscore (_).
  • 40.
    1. pinMode(): needto set its mode as either INPUT or OUTPUT using the pinMode() function. It is used under void setup() loop. Syntax: pinMode(pin, mode) For example: pinMode(13, OUTPUT); // Sets digital pin 13 as an output pinMode(A0, INPUT); // Sets analog pin A0 as an input 2. digitalWrite(): For digital pins configured as OUTPUT, you can use the digitalWrite() function to set the pin's state to HIGH or LOW. It is used in main loop. Before using this command, digital pin must be set as output pin using command pinMode(). Syntax: digitalWrite(pin, value) For example: digitalWrite(13, HIGH); // Sets digital pin 13 to HIGH (5V) digitalWrite(13, LOW); // Sets digital pin 13 to LOW (0V) PROGRAMMING CONCEPTS: FUNCTIONS
  • 41.
    3.digitalRead() : Fordigital pins configured as INPUT, you can use the digitalRead() function to read the pin's state. It is used in main loop. Before using this command, digital pin must be set as output pin using command pinMode(). Syntax: digitalRead(pin) Example: int value = digitalRead(2); // Reads the state of digital pin 2 (HIGH or LOW) 4. analogRead(): For analog pins, you can use the analogRead() function to read the analog voltage and convert it to a digital value: Syntax: analogRead(pin) Example: int analogValue = analogRead(A0); // Reads the analog value from pin A0 5. analogWrite(): the analogWrite() function used for generating PWM on Digital Pin, vary intensity of LED or vary motor speed Syntax: analogWrite(pin,value) Example: analogWrite(11,digitalInput); // Write Analog output in pin 11 PROGRAMMING CONCEPTS: FUNCTIONS
  • 42.
    6. Serial.begin(): TheSerial.begin() sets the baud rate for serial data communication. The baud rate signifies the data rate in bits per second. The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc. The Serial.begin( ) is declared in two formats, which are shown below: i) begin( speed ) ii) begin( speed, config) Where, serial: It signifies the serial port object. speed: It signifies the baud rate or bps (bits per second) rate. It allows long data types. config: It sets the stop, parity, and data bits.  Example void setup ( ) { Serial.begin(4800); } void loop ( ) { } PROGRAMMING CONCEPTS: FUNCTIONS
  • 43.
    7. Serial.read() :The Serial.read( ) in Arduino reads the incoming serial data in the Arduino. The int data type is used here. It returns the first data byte of the arriving serial data. It also returns -1 when no data is available on the serial port. The syntax used in the Arduino programming is Serial.read( ), Where, serial: It signifies the serial port object. The data is stored in the form of bytes, where 1 byte = 8 bits. Let's understand with an example. int arrivingdatabyte; void setup( ) { Serial.begin(9600); } void loop( ) { if(Serial.available( ) > 0) { arrivingdatabyte = Serial.read( ); // It will read the incoming or arrivi ng data byte Serial.print("data byte received:"); Serial.println(arrivingdatabyte); } } PROGRAMMING CONCEPTS: FUNCTIONS
  • 44.
    8. Serial.write(): Itsends the binary data to the serial port in Arduino. The data through Serial.write is sent as a series of bytes or a single byte. If we want to send the digits of numbers represented by the characters, we need to use the Serial.print( ) function instead of Serial.write( ). The Serial.write( ) function will return the number of written bytes. The Serial.write( ) is declared in three formats, which are shown below:  write(str)  write(value)  write(buffer, len) Where, Serial: It signifies the serial port object. str: The str means string, which sends the data as a series of bytes. buffer: It is an array that is used to send the data as a series of bytes. value: It sends the data to the Arduino as a single byte. len: It signifies the number of bytes, which can be sent from the array. Example void setup( ) { Serial.begin(14400); } void loop( ) { Serial.write(55); // the specified value is 55. // Serial.write( ) send the data as a byte with this value (55). int Bytestosend = Serial.write( " Arduino" ); // It sends the Arduino string. //The length of the string is a return parameter in this function. } PROGRAMMING CONCEPTS: FUNCTIONS
  • 45.
    9. delay() function Thedelay()function pauses the program or task for a specified duration of time. The time is specified inside the open and closed parentheses in milliseconds. Where, 1 second = 1000 milliseconds The program waits for a specified duration before proceeding onto the next line of the code. The delay( ) function allows the unsigned long data type in the code. We can create many sketches using the short and long delays depending on the requirements in the project. It does not disable any interrupts. But, the delay( ) function has some drawbacks.  Example void setup ( ) { Serial.begin ( 4800); // opens the serial port and set the bits per rate to 4800 } void loop ( ) { Serial.print(" Welcome"); delay(1000); Serial.println("to delay"); // It will print 'to delay' followed by a new line. delay ( 500); // delay of 0.5 seconds between each printed line. } PROGRAMMING CONCEPTS: FUNCTIONS
  • 46.
    10/03/2024 STRUCTURE 46 ■ From globalconditional control structures to more specific ones. ■ Basic Structure ■ setup() ■ loop() ■ Control Structures (Conditional Statements) ■ if , if...else and switch case ■ for, while and do... while ■ break and continue ■ return ■ goto
  • 47.
    10/03/2024 ARDUINO IDE :SKETCH STRUCTURE 47
  • 48.
  • 49.
    10/03/2024 CONDITIONAL STATEMENTS 49 1. IfConditional Statement: ■ most basic form of conditional statement. It checks if a condition is true. ■ If it is, the program executes a block of code. ■ Syntax: if (condition) { // code to execute if condition is true } ■ if condition is true, the if code block executes. ■ If false, the execution moves to the next block to check.
  • 50.
  • 51.
    10/03/2024 CONDITIONAL STATEMENTS 51 1. IfConditional Statement: Use Cases: ■ Checking a single condition and executing code based on its result. ■ Performing actions based on user input. Applications: ■ Validating user inputs. ■ Basic decision-making in algorithms. Advantages: ■ Simple and straightforward. ■ Useful for handling basic decision logic. Disadvantages: ■ Limited to checking only one condition at a time. ■ Not suitable for complex
  • 52.
    10/03/2024 CONDITIONAL STATEMENTS 52 1. IfConditional Statement: int a = 6; // initiaization of values to variables a and b int b = 4; void setup() { Serial.begin(9600); } void loop() { if (a > b ) { Serial.println( " a is greater than b "); } if (b > a ) { Serial.println( " b is greater than a "); } }
  • 53.
    10/03/2024 CONDITIONAL STATEMENTS 53 2. If-ElseConditional Statement: ■ extends the if statement by adding an else clause. ■ If the condition is false, the program executes the code in the else block. ■ Syntax: if (condition) { // code to execute if condition is true } else { // code to execute if condition is false } ■ if condition is true, the if code block executes. ■ If false, the execution moves to the else block.
  • 54.
  • 55.
    10/03/2024 CONDITIONAL STATEMENTS 55 2. If-ElseConditional Statement : Use Cases: ■ Executing one block of code if a condition is true and another block if it’s false. ■ Handling binary decisions. Applications: ■ Error handling: For example, displaying an error message if user input is invalid. ■ Program flow control: Directing program execution based on conditions. Advantages: ■ Handles binary decisions efficiently.. ■ Clear and concise syntax. Disadvantages: ■ Limited to binary decisions. ■ May become verbose in complex scenarios
  • 56.
  • 57.
    10/03/2024 CONDITIONAL STATEMENTS 57 3. if-Elseif Conditional Statement: ■ allows for multiple conditions to be checked in sequence. ■ if condition is false, the program checks the next else if condition, and so on. ■ Syntax: if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition2 is true } else { // code to execute if all conditions are false } ■ In else if statements, the conditions are checked from the top-down, if the first block returns true, the second and the third blocks will not be checked, but if the first if block returns false, the second block will be checked. This checking continues until a block returns a true outcome.
  • 58.
  • 59.
    10/03/2024 CONDITIONAL STATEMENTS 59 3. if-Elseif Conditional Statement: Use Cases: ■ Handling multiple conditions sequentially. ■ Implementing multi-way decision logic. Applications: ■ Implementing menu selection logic. ■ Categorizing data based on multiple criteria. Advantages: ■ Allows handling multiple conditions in a structured manner. ■ Reduces the need for nested if-else statements. Disadvantages: ■ Can become lengthy and harder to maintain with many conditions. ■ The order of conditions matters; incorrect ordering can lead to unexpected behavior.
  • 60.
    10/03/2024 CONDITIONAL STATEMENTS 60 3. if-Elseif Conditional Statement: int i = 2; int j = 3; void setup ( ) { Serial.begin(9600); } void loop ( ) { if ( i > j ) { Serial.println( " I is greater "); } else if ( i < j ) { Serial.println( " J is greater " ); } else { Serial.println( " Both are equal " ); } }
  • 61.
    10/03/2024 CONDITIONAL STATEMENTS 61 4. SwitchConditional Statement: ■ used when you need to check a variable against a series of values. ■ often used as a more readable alternative to a long if-else if chain. ■ each block is terminated by a break keyword. ■ The statements in switch are expressed with cases ■ Syntax: switch (variable) { case value1: // code to execute if variable equals value1 break; case value2: // code to execute if variable equals value2 break; default: // code to execute if variable doesn't match any value }
  • 62.
  • 63.
    10/03/2024 CONDITIONAL STATEMENTS 63 4. SwitchConditional Statement: Use Cases: ■ Selecting one of many code blocks to execute based on the value of a variable. ■ Handling multiple cases efficiently. Applications: ■ Processing user choices in a menu. ■ Implementing state machines. Advantages: ■ Provides a clean and efficient way to handle multiple cases. ■ Improves code readability when dealing with many conditions. Disadvantages: ■ Limited to equality comparisons, cannot use range checks or complex conditions.. ■ Lack of fall-through control can lead to unintentional bugs if not used carefully.
  • 64.
    10/03/2024 CONDITIONAL STATEMENTS 64 4. SwitchConditional Statement: void setup() { Serial.begin(9600); int a = 1; switch(a) // the case matching the value in the declared variable wi ll run { case 1: Serial.println(" Case 1 matches"); // the value of variable matches with the value in case 1. // The message associated with case 1 will be printed break; case 2: Serial.println(" Case 2 matches"); break; default: Serial.println(" default matches"); break; } } void loop() { }
  • 65.
    10/03/2024 Loop statement :for loop 65 ■ Syntax ■ example CONDITIONAL STATEMENTS ■ statements inside the curly brackets under for loop are executed repeatedly according to the specified condition. An increment counter in the for loop is used to increment or decrement the loop repetitions. ■ The for statement is commonly used for repetitive task or operation or to operate on the group of data/pins in combination with arrays.
  • 66.
    10/03/2024 CONDITIONAL STATEMENTS 66 ■ Syntax ■Example Loop statement : while loop ■ the conditional loop that continues to execute the code inside the parentheses until the specified condition becomes false. ■ never exit until the tested condition is changed or made to stop. ■ The common use of a while loop in Arduino includes sensor testing, calibration (calibrating the input of sensor), variable increment, etc.
  • 67.
  • 68.
    10/03/2024 STRUCTURE : OPERATORS 68 ArithmeticOperators Comparison Operators = (assignment operator) == (equal to) + (addition) != (not equal to) - (subtraction) < (less than) * (multiplication) > (greater than) / (division) <= (less than or equal to) % (modulo) >= (greater than or equal to) Bitwise Operators Compound Operators & (bitwise and) ++ (increment) | (bitwise or) -- (decrement) ^ (bitwise xor) += (compound addition) ~ (bitwise not) -= (compound subtraction) << (bitshift left) *= (compound multiplication) >> (bitshift right) /= (compound division) %= (compound modulo) &= (compound bitwise and) |= (compound bitwise or)
  • 69.
    10/03/2024 STRUCTURE : OPERATORS 69 BooleanOperators Pointer Access Operators && (and) || (or) ! (not) * dereference operator & reference operator
  • 70.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 70 GPIO (General Purpose Input/Output) ■ software controlled interface found on Microcontrollers and some Microprocessor ICs or interface chipsets ■ one or more pins on the IC which have no special purpose in themselves, but which facilitate an optional ability for device designers to create an interface/connection between the IC and a peripheral component by programming some hardware registers. Some basic GPIO capabilities are : ■ GPIO Pins can be enabled or disabled as needed ■ Output values are writable (high=1, low=0) ■ Input values are readable (high=1, low=0) ■ Inputs can often be used as IRQ (Interrupt Request) signals, Edge triggered or Level triggered. Such IRQs may be configurable to wake the system from a low power state
  • 71.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 71 GPIO Input Output Modes ■High Impedance / Floating / Hi-Z / Tri-Stated ■Input Mode with Pull-Up or Pull- Down ■Output Mode with Open Drain ■Output Mode with Push Pull
  • 72.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 72 High Impedance / Floating / Hi-Z / Tri-Stated ■When a GPIO pin put into a High Impedance state, effectively gets disconnected from the external interface. ■ The basic concept is to effectively remove the device’s influence from the rest of the circuit. ■If more than one device is electrically connected to another device, putting a pin into the Hi-Z state is often used to prevent short circuits, or one device driving high (logical 1) against another device driving low (logical 0).
  • 73.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 73 Input Mode with Pull-Up or Pull-Down ■When a GPIO pin is used with an Internal or External Pull -Up or Pull-Down Resistor to ensure a known state of logic. ■It is used typically with a switch or input device such that whenever the switch is pressed or input comes it toggles the logic level. ■Pull-Up ensures a well-defined Logic Level of High = 1. A Pull-Up resistor usually connects the pin to Vcc. ■It holds the logic too High when no other active input comes. ■Pull-Down ensures a well-defined Logic Level of Low = 1. A Pull-Down resistor usually connects the pin to GND. ■It holds the logic to Low when no other active input comes.
  • 74.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 74 Output Mode with Open Drain ■An Open Drain output can take two states Low Impedance and High Impedance. In a Low Impedance state, it can sink current. It is like a switch that is either connected to the ground or open. ■The MOSFET has three terminals called: gate, source, and drain. In an open-drain configuration, the source is grounded, the gate is driven internally, and the drain is the pin (i.e. not connected to external hardware). When the Gate is driven, Drain gets connected with the Source and the PIN gets a Logic Low = 0. Otherwise, the PIN remains at High-Z state which is useless until a Pull-Up is used.
  • 75.
    10/03/2024 CONCEPT OF GPIOIN ATMEGA328 BASED ARDUINO BOARD 75 Output Mode with Push Pull A Push-Pull output is capable of both sourcing and sinking current. ■When the top transistor [PMOS] will be activated, the output PIN will be HIGH and act as a Source. When the NMOS below will be on, the output PIN is driven LOW and act as a Sink. It is a complementary logic and only once MOS will be activated at a time.