The Arduino Platform and C Programming
Arduino Course Overview
The Arduino platform is an open-source system for developing digital devices and
interactive objects that can sense and control their environment. This course covers:
• Arduino Physical Board: Learn its components, libraries, and integrated
development environment (IDE).
• Shields: Understand smaller boards that extend Arduino’s functions (e.g., sensing
light/heat, GPS tracking, user interface displays).
• Programming with C: Control external devices by accessing board pins through
software.
Learning Objectives
1. Understand the composition of the Arduino development board.
2. Learn to program the board's firmware.
3. Read and interpret board schematics.
4. Install and use the Arduino IDE.
5. Comprehend the role of shields and libraries.
6. Compile, run, and debug Arduino programs.
7. Master key C programming concepts:
o Variables, types, and operators.
o Conditionals, loops, and functions.
o Global variables and their implications.
8. Differentiate between digital and analog pins.
9. Explain debugging processes and UART serial communication.
10. Understand the Arduino Serial Library for communication.
Prerequisites
• No prior knowledge or experience is required.
Recommended Hardware and Software
• Hardware: Arduino Uno Rev 3 Ultimate Starter Kit ($54.99 USD via Vilros).
• Software: Arduino IDE (Free download from Arduino’s official website).
• For those without physical hardware, use the web-based Arduino simulator at
123d.circuits.io (free account required).
Module 1: Objectives
Here’s a concise set of notes based on the Module 1 objectives:
1. Arduino Development Board Composition:
o Understand the different components of the Arduino board.
o Learn how these components work together to support programming and
interaction with external devices.
2. Programming the Firmware:
o Explore what firmware is and how it allows the board to function.
o Learn the process of uploading and managing firmware for optimal
performance.
3. Reading Board Schematics:
o Develop the skill to read and interpret technical diagrams (schematics) of the
Arduino board.
4. Installing the Arduino IDE:
o Learn how to download, install, and set up the Arduino IDE.
o Get familiar with the IDE’s interface and essential tools.
5. Understanding Shields:
o Gain insights into what shields are, their functionality, and how they expand
the board’s capabilities.
o Learn how shields add features like sensors, displays, or communication
modules.
6. Role of Libraries:
o Understand the importance of software libraries for using shields.
o Learn how libraries simplify programming and extend functionality.
Module 1: Arduino Environment Overview
Here are the key points based on the transcript:
1. Introduction to Arduino IDE:
o The IDE is the software interface where you:
▪ Write code.
▪ Compile the code.
▪ Upload the code to the Arduino board.
2. Arduino Board:
o The board contains a chip and firmware that execute the uploaded code.
o It is a critical part of the Arduino environment.
3. Arduino Shields:
o Shields are add-on hardware components that stack onto the main Arduino
board.
o They extend the board’s functionality (e.g., sensing or communication).
o Shields are used via specific libraries, which simplify programming and
integration.
4. Three Main Components of the Arduino Environment:
o The IDE: For programming.
o The Board: For running programs and interacting with the physical world.
o The Shields: For additional features and functionalities.
Module 1: Arduino Environment Notes
Here is a detailed summary of the content:
1. Arduino Environment Overview
The Arduino environment consists of:
• Arduino Development Board: The core hardware with an 8-bit microcontroller.
• Arduino IDE: Software for coding and programming the board.
• Shields: Add-on hardware components for extended functionality.
2. Arduino Development Board
• Equipped with an 8-bit microcontroller (e.g., ATmega328).
• USB interface for connecting to a computer:
o USB port transfers code from your computer to the board.
o A built-in chip handles USB communication.
• Bootloader software: Facilitates USB programming.
• I/O Pins (Input/Output):
o These connect the microcontroller to external devices.
o Pins are physically accessible through holes on the board, allowing easy
wiring.
3. Arduino IDE (Integrated Development Environment)
• Used for:
o Writing and compiling code.
o Uploading programs to the Arduino board.
• Features of the IDE:
o Cross compiler: Converts code to a format the microcontroller can
understand.
o Debugger and simulator tools for testing.
o Programmer to upload executable code.
• Available for multiple platforms (Windows, Linux, Mac).
• Open-source software written in Java, allowing customization if needed.
4. Arduino Shields
• Shields are hardware modules stacked onto the Arduino board.
• Purpose:
o Simplify the integration of complex devices (e.g., Ethernet controller,
sensors).
o Pre-wired connections reduce the need for hardware expertise.
o Paired with libraries that provide ready-to-use functions for interaction.
• Example: Ethernet Controller Shield
o Pre-wired board for Ethernet functionality.
o Comes with libraries to manage Ethernet communication efficiently.
5. Open-Source Design
• Arduino hardware and software are open source:
o Hardware: Schematic diagrams are available on arduino.cc.
o Software: The IDE is open source, enabling modifications.
6. Other Components on the Board
• Reset Button: Resets the device.
• Power Options:
o USB power (sufficient for most tasks).
o External power (via coaxial jack) for high-power tasks like running motors.
Detailed Notes on Arduino Board Components
1. Input/Output (I/O) Pins
• Location: Highlighted at the top and bottom of the board.
• Functionality: Connect the microcontroller chip to external devices via wired
connections.
• Pin Types:
o Digital I/O Pins: Handle digital signals (0V for logic 0, 5V for logic 1).
o Analog Input Pins: Accept a range of voltage values (not limited to 0V or 5V).
The microcontroller can interpret these analog signals.
▪ Note: The board does not directly generate analog outputs, but it can
process analog inputs via a built-in analog-to-digital converter (ADC).
2. Power and Reset Pins
• Power Pins:
o Provide 5V and 3.3V power outputs.
o Ground (GND) pins ensure a common ground connection for circuits.
• Reset Pin: Resets the board to its initial state, restarting the code execution.
3. Microcontrollers on the Board
• Main Microcontroller (ATmega328):
o Executes user-written programs (application code).
o Stores firmware for basic operations and functionality.
• USB Communication Microcontroller (ATmega16U2):
o Manages communication between the USB interface and the main
processor.
o Handles data transfer using the USB protocol.
o Users do not directly modify this microcontroller or its firmware.
4. Types of Code on the Microcontroller
• Application Code:
o Written by the user to implement specific functionalities.
o Example: A system that senses soil moisture and waters plants accordingly.
• Firmware:
o Pre-installed low-level code that supports essential operations (e.g., USB
communication, power management, reset functionality).
o Users typically do not modify firmware.
5. Features and Functions
• USB Interface: Allows connection to a computer for programming.
• Power Options: Includes USB power and external power via a coaxial jack.
• Open Source Design:
o Hardware schematics and software (IDE) are open source, enabling
customization.
o The large community provides additional resources and support.
6. Perspective on Firmware vs. Application Code
• Firmware: Code already on the microcontroller, often seen as background support
for core operations.
• Application Code: User-created programs for specific purposes.
• Subjective Distinction:
o For a product end-user, application code may be considered firmware if it is
not intended for modification.
Notes on Programming the Arduino Firmware
1. Bootloader Basics
• The bootloader is a type of firmware stored on the microcontroller (ATmega328).
• Purpose:
o Manages USB communication for uploading code to the microcontroller.
o Allows programming of flash memory and EEPROM (non-volatile memory) to
store your application code.
o Handles resets and background system processes.
• Key Limitation: The bootloader cannot reprogram itself. To update or replace the
bootloader, an alternative programming route is required.
2. In-Circuit Serial Programming (ICSP)
• Definition: ICSP is an interface on the Arduino board used for programming the
firmware directly.
• When to Use:
o Required for tasks such as updating the bootloader or firmware.
o Not used for regular application code programming (which is done via USB
and Arduino IDE).
• Components:
o Two ICSP headers on the Arduino board:
▪ One for the ATmega328 (main microcontroller).
▪ One for the ATmega16U2 (handles USB communication).
3. ICSP Programming Process
• Requirements:
o A special programmer device is necessary to connect to the ICSP pins.
o Additional software is used to program the firmware or bootloader.
• Steps:
1. Connect the programmer to the ICSP header corresponding to the desired
processor (ATmega328 or ATmega16U2).
2. Use the programmer and software to directly modify the firmware or
bootloader.
4. Context in this Class
• ICSP programming is not part of the course scope.
• The class focuses on programming application code using the standard USB and
Arduino IDE route.
• Understanding the ICSP and bootloader is valuable for advanced tasks, such as
bootloader updates or security patches.
5. Key Insights
• Two Processors on the Board:
o ATmega328: The main processor that runs application code.
o ATmega16U2: Manages USB communication, independent of user
application code.
• Firmware vs. Bootloader:
o Firmware includes background operational code (e.g., USB communication
protocols).
o The bootloader is a specific type of firmware that facilitates programming the
microcontroller.
Notes on Arduino Schematics
1. Importance of Schematics
• Definition: A schematic is a diagram that displays the components of a device and
how they are wired together.
• Usefulness:
o Essential for replicating or modifying hardware designs.
o Often used in DIY projects to show the wiring and component connections.
o Reading schematics is a valuable skill for building or troubleshooting
hardware systems.
2. Arduino Uno Rev 3 Schematic
• Availability: Open-source schematics can be downloaded from the Arduino
website.
• Purpose:
o Shows how components on the Arduino Uno board are connected.
o Enables users to build or modify their own circuits based on the design.
• Key Note: The schematic layout is designed for readability and does not reflect the
compact physical layout of the actual board.
3. Major Components Highlighted in the Schematic
• Microcontrollers:
o ATmega328: The main processor you program for tasks.
o ATmega16U2: Handles USB communication.
• Pins on the Board:
o Power Pins: Provide 5V, 3.3V, and ground connections for external devices.
o Analog Input Pins: Receive analog signals (non-binary values).
o Digital I/O Pins: Transmit and receive binary signals (0 or 1).
• Other Components:
o Power Connector: Supplies power to the board.
o ICSP Headers (ICSP1 & ICSP2): Allow firmware programming for both
processors.
o USB Connector: Provides a communication interface with a computer.
4. Key Observations
• The physical layout of components on the board differs from their arrangement in
the schematic. The schematic focuses on clarity rather than compactness.
• Smaller components like resistors, LEDs, and capacitors are part of the schematic
but not detailed here.
5. Learning Applications
• Schematics help users understand the wiring and functionality of the board
components.
• Provides a foundation for advanced projects or troubleshooting issues.
Notes on the Arduino Microcontroller and IDE
1. ATmega328 Microcontroller Overview
• Specifications:
o Type: 8-bit microcontroller.
o Operating Voltage: 5V (pins handle signals between 0-5V).
o Input Voltage (External Power): Recommended range is 7-12V (steps down
to 5V internally).
o Digital I/O Pins: 14 pins (labeled 0-13).
o Analog Input Pins: 6 pins (labeled A0-A5).
o DC Current Limits:
▪ I/O Pins: Max 40mA (sufficient for small components like LEDs).
▪ 3.3V Pin: Max current output is limited; unsuitable for high-power
devices like motors.
• Memory:
o Flash Memory (32 KB): Non-volatile storage for user programs.
o SRAM (3 KB): Volatile memory used during program execution (cleared when
power is off).
o EEPROM (1 KB): Non-volatile memory for storing small amounts of data,
accessible byte-by-byte.
• Performance:
o Clock Speed: 16 MHz (16 million cycles per second, adequate for embedded
tasks).
• Cost:
o Microcontroller cost: ~$1.50.
o Arduino Uno board cost: ~$35-$40, providing additional components for
convenience.
2. The Arduino IDE (Integrated Development Environment)
• Purpose: A software platform for writing, compiling, and uploading code to the
Arduino board.
• Main Interface Components:
1. Text Editor: Area to write and edit code.
2. Menu Options: File management and various IDE commands.
3. Top-Row Buttons: Quick access to common actions:
▪ Verify: Compiles the code to check for syntax and compile errors.
▪ Upload: Compiles and uploads the code to the Arduino board
(requires the board to be connected).
▪ New: Creates a new sketch/program.
▪ Open: Opens an existing sketch.
▪ Save: Saves the current sketch.
▪ Serial Monitor: Opens a communication window between the
Arduino and your computer (discussed further in Module 2).
4. Message Area: Displays compilation errors or other system messages.
• Installation and Use:
o Downloadable from Arduino.cc.
o Compatible with Windows, Mac, and Linux operating systems.
o Includes tools such as a compiler, debugger, and program uploader.
3. The Serial Monitor
• Purpose: Facilitates communication between the Arduino board and your
computer.
• Use Cases:
o Input text to send data to the Arduino.
o View output data sent from the Arduino (e.g., sensor readings, debug
messages).
• Key Limitation: Embedded devices like Arduino do not have built-in screens or
keyboards. The Serial Monitor bridges this gap, acting as a virtual console.
4. Summary of Key Features
• Efficient Yet Affordable: The ATmega328 microcontroller is inexpensive and
sufficient for most embedded applications.
• Memory Management: Limited memory requires optimization for code and data
storage.
• Ease of Use: The Arduino IDE simplifies programming through an intuitive interface
and helpful tools like Serial Monitor.
Notes on Compiling, Debugging, and the Serial Monitor
1. Compiling and Uploading Code
• Compilation Options:
o Verify: Compiles the code to check for syntax and compile errors without
uploading it to the Arduino board.
o Upload: Combines compilation and uploading of the executable code to the
board.
• Message Window:
o Displays the status of compilation.
o Shows either:
▪ Completion messages like “Compile Complete” or “Done Uploading.”
▪ Errors with details such as line numbers for easier debugging.
2. Handling Compilation Errors
• Locating Errors:
o Errors are reported with corresponding line numbers in the code.
o The text editor highlights the problematic line in pink to help you pinpoint the
issue.
• C Language Quirks:
o Errors may cascade, generating multiple error messages even if only one
issue exists.
o Example:
▪ Incorrect syntax on a line (e.g., extra characters like XX) may also
cause errors on subsequent lines.
▪ Focus on fixing the first error and recompile; other errors may resolve
automatically.
3. Serial Monitor Overview
• Purpose: Acts as a virtual interface for communication between the computer and
the Arduino.
• Components:
o Main Window: Displays messages from the Arduino (e.g., results of
computations or debug messages).
o Input Field: Allows users to send text data to the Arduino by typing and
pressing "Send."
• Functionality:
o Write code to send messages to the Serial Monitor using the serial.print
function.
o Receive input from the Serial Monitor in your Arduino code to interact
dynamically with your device.
4. Practical Use of Serial Monitor
• Emulates a keyboard and screen interface for embedded systems (which typically
lack displays and keyboards).
• Supports both:
o Sending data to the Arduino (e.g., controlling an LED via user input).
o Receiving data from the Arduino (e.g., debugging messages or sensor
readings).
5. Debugging Process
• Steps:
1. Use the message window and error highlights in the IDE to locate errors.
2. Start fixing issues with the first error reported, as subsequent errors may be
a result of the initial mistake.
3. Recompile after resolving errors; some errors may disappear in subsequent
compilations.
Notes on Arduino Shields
1. What Are Arduino Shields?
• Definition: Shields are add-on boards (also called daughterboards) that stack onto
the Arduino board to expand its functionality.
• Purpose: Simplify the integration of complex external devices (e.g., Ethernet
controllers, displays, synthesizers) without requiring detailed hardware knowledge.
• Benefits:
o Shields handle the wiring and hardware complexities.
o Each shield comes with pre-written libraries, making programming easy and
user-friendly.
2. Features and Advantages
• Pre-Wired Connections:
o Shields are designed to align perfectly with Arduino's pin layout.
o They physically stack on top of the Arduino board, connecting directly to its
pins via holes along the edges.
• Libraries:
o Every shield includes associated libraries containing pre-written functions.
o Functions simplify tasks like Internet access or data visualization without the
need for understanding underlying hardware intricacies.
• Open Source Design:
o Most shield designs are open source, allowing for transparency and
customization.
o Shields can be purchased pre-made for convenience.
3. Examples of Shields
• Ethernet Shield:
o Adds Ethernet connectivity for Internet access via a wired connection.
o Library functions enable simple operations like connect(IP_address,
port_number) to establish a connection.
• Color LCD Shield:
o Adds a screen for graphical display.
o Includes a processor to communicate with and control the LCD.
• Synthesizer Shield:
o Generates MIDI music and connects to speakers.
o Useful for creating audio applications.
4. Why Shields Are Popular
• Arduino shields make complex hardware interfaces (e.g., Ethernet controllers)
accessible by abstracting away low-level implementation details.
• Large variety available for diverse applications:
o Sensors, displays, communication modules, motor drivers, and more.
• Resources for shields, such as a comprehensive list, are available on platforms like
shieldlist.org.
5. Example of a Library Function
• Connect Function for Ethernet Shield:
o Function: connect(IP_address, port_number)
o User Perspective: Simple and intuitive—opens a remote connection with a
few inputs.
o Internal Complexity: The implementation involves intricate code that
manages the Ethernet protocol and chip functionality, which is hidden from
the user.
Notes on Arduino Basic Setup
1. Setting Up the Arduino IDE
• Downloading the IDE:
o Go to the official Arduino website: arduino.cc.
o Navigate to the software section (arduino.cc/en/Main/Software) and
download the appropriate installer for your operating system (Windows, Mac,
Linux).
• Installing the IDE:
o Run the installer and follow the prompts.
o Accept installation of any drivers (e.g., USB drivers). These drivers enable
communication between your computer and the Arduino board.
o The installation process is user-friendly and has improved over time.
2. Connecting Your Arduino Board
• Use a USB cable to connect the Arduino board to your computer.
• Launch the Arduino IDE:
o You may find a desktop icon or search for "Arduino" on your computer.
• The IDE will open with a blank sketch, providing a template for writing code.
3. Verifying Setup with the Blink Example
• Purpose: Run a sample program (Blink) to confirm your setup is working correctly.
• Steps:
1. Open the Blink example:
▪ Navigate to File > Examples > Basics > Blink.
▪ This will open a new window with the Blink program preloaded.
2. Check the Board:
▪ Go to Tools > Board and select your board (e.g., Arduino Uno).
▪ The IDE might auto-detect the board, but manually select if needed.
3. Select the Serial Port:
▪ Navigate to Tools > Port.
▪ The system should map your Arduino to a COM port (e.g., COM3 or
COM5 on Windows).
▪ Select the listed port. If unsure, test one and retry if it fails.
▪ If no port is listed, USB drivers may not be installed correctly.
4. Upload the Blink program:
▪ Press the Upload button in the IDE.
▪ The program will compile (error-free) and upload to the board.
5. Observe the Results:
▪ After uploading, the LED near pin 13 on the Arduino should blink once
every second.
4. Key Troubleshooting Tips
• Serial Port Issue:
o If no port is detected, reinstall the USB drivers.
• Multiple COM Ports:
o Test different ports if multiple options are displayed.
• Blink Program Not Running:
o Ensure the correct board and port are selected in the Tools menu.
5. Why the Blink Example Matters
• Provides a quick sanity check to ensure:
o The IDE is installed properly.
o Drivers are functioning.
Module 2 Objectives Notes
Here’s a breakdown of the Module 2 objectives for clarity:
1. Compile and Run a Program:
o Practice compiling code using the "Verify" button in the Arduino IDE.
o Successfully upload the program to the Arduino board and ensure it
executes.
2. Name C Variables and Types:
o Learn about variable declaration in C, including:
▪ Primitive Types: int, float, char, double, etc.
▪ Complex Types: Arrays, pointers, and structs.
3. Name Common C Operators:
o Understand the following operator categories:
▪ Arithmetic Operators: +, -, *, /, %.
▪ Relational Operators: ==, !=, <, >, <=, >=.
▪ Logical Operators: &&, ||, !.
▪ Assignment Operators: =, +=, -=, etc.
4. Use Conditionals and Loops:
o Implement decision-making structures:
▪ Conditionals: if, else if, else, switch-case.
▪ Loops: for, while, do-while for repetitive tasks.
5. Explain Functions, Their Definition and Invocation:
o Learn about function structure:
▪ Definition: Specify return type, function name, and parameters.
▪ Invocation: Call a function by passing arguments.
Explain the Implications of Global Variables:
• Understand the scope of variables:
o Global Variables:
▪ Declared outside functions and accessible throughout the program.
▪ Convenient but can cause unintended side effects if modified by
multiple functions.
o Local Variables:
▪ Declared within functions and accessible only within that scope.
Notes on Setting Up Your Environment for C Programming
1. Focus of Module 2
• This module focuses on C programming basics, including syntax and structure. The
content is applicable to a variety of environments beyond Arduino, such as desktop
or laptop setups.
2. Setting Up Your Environment
• Required Tools:
1. Text Editor: Use a programming-friendly text editor for writing C code.
▪ Recommended Options:
▪ GNU Emacs: Free and open-source, supports C syntax
highlighting and formatting.
▪ Notepad++: Lightweight and user-friendly, also free and open-
source.
▪ Available at GNU.org.
2. C Compiler:
▪ Use GCC (GNU Compiler Collection) for compiling C code. GCC is
open-source and widely supported.
▪ Platforms:
▪ Linux and MacOS: GCC comes pre-installed.
▪ Windows: Requires manual installation.
3. Debugger (Optional):
▪ GDB (GNU Debugger): Useful for debugging, though not covered in-
depth in this module.
• Integrated Development Environments (IDEs):
o Alternative to using separate tools (text editor + compiler).
o Popular IDE Options:
▪ Eclipse: Free, combines text editor, compiler, and debugger in one
interface. Requires Java Runtime Environment (JRE).
▪ Microsoft Visual Studio: Feature-rich but not free.
▪ Arduino IDE: Specifically for Arduino programming.
3. Writing and Running a C Program
• "Hello, World" Example Program:
o The traditional starting program in C, used to print "Hello, World" to the
screen.
o Arduinos lack screens, so you’ll use a desktop or laptop for this example.
• Steps:
1. Write Code:
▪ Use your text editor to write the program.
▪ Save the file with a .c extension (e.g., hello.c
4. Key Tips
• Command Line:
o Useful for manual compilation and running programs.
o Commands may vary slightly across operating systems:
▪ Use ls for directory listing on Linux/Mac, or dir on Windows.
o Include ./ before the executable name to run the program on Linux/Mac.
• GUI IDEs: Eclipse or Visual Studio are convenient if you prefer graphical tools over
command-line operations.
Notes on Breaking Down the "Hello, World" Program
1. Include Statement
• Syntax: #include <stdio.h>
o The # symbol indicates a compiler directive, which is not executable code
but an instruction for the compiler.
o #include includes the header file stdio.h at the top of the code, essentially
copying and pasting the contents of the file into the program.
o Purpose: stdio.h is part of the standard C library, providing essential
input/output functions like printf.
2. Purpose of Header Files
• The header file defines function prototypes, outlining the inputs and outputs of
library functions without including their full implementation.
• Example:
o To use printf (which prints text to the screen), you must include stdio.h.
5. Execution Flow
• The program begins at main and executes each instruction inside its scope
sequentially unless control flow (e.g., loops, conditionals) alters the sequence.
6. Special Characters in Strings
• \n: Moves to the next line (carriage return).
• Other examples include \t (tab) and \\ (backslash).
• These are useful for formatting text output, even on embedded systems like Arduino
when printing via Serial Monitor.
7. Applicability to Arduino
• While the printf function is not directly usable on Arduino (no screen), concepts like
string manipulation and special characters are useful for serial communication
(e.g., debugging via Serial Monitor).
Variables in Programming
1. Definition:
o Variables are names that represent values in a program, similar to algebra.
o Example: x = 5, x = y + 2 (where x and y are substitutes for values).
2. Variable Types:
o A type defines the kind of data the variable will hold (e.g., integer, float).
o Examples:
▪ int x; means x will hold an integer.
▪ float y; means y will hold a floating-point number.
3. Purpose of Types:
o Memory Allocation: Type determines the amount of memory a variable
requires.
▪ Example:
▪ On a 32-bit machine:
▪ Integer (int) = 4 bytes.
▪ Floating point (float) = ~4 or 8 bytes.
o Arithmetic Operations: Arithmetic is performed differently based on the
type.
▪ Integer and floating-point operations use separate hardware units.
4. Declaration:
o In C, variables must be declared before use.
o Example: int x;, float y;.
5. Common Variable Types:
o char (1 byte): Represents characters, standard across platforms.
o int (16 or 32 bits): Commonly used for integers.
o float and double: Used for floating-point numbers (larger and slower).
▪ Often avoided in embedded systems due to performance and
memory concerns.
6. Naming Rules for Variables:
o Must begin with a non-numerical character (e.g., int testvar1 is valid, but int
1testvar is not).
o Cannot use reserved keywords (e.g., if, else, while).
C Operators Overview
1. Constants:
o #define is a compiler directive used to define constants.
▪ Example: #define ANSWER 42 substitutes ANSWER with 42.
o It performs macro substitution during the pre-processing step.
o Can define constants for numbers or characters (e.g., #define TERMINATOR
'x').
o ASCII and Unicode tables map characters to numbers (e.g., ASCII x = 41).
2. Arithmetic Operators:
o Standard operators: + (add), - (subtract), * (multiply), / (divide).
o % (modulo): Returns the remainder of division.
▪ Example: 9 % 2 = 1, 9 % 3 = 0.
3. Increment & Decrement:
o x++ (increment) and x-- (decrement) adjust the value of x by 1.
4. Relational (Comparison) Operators:
o == (equal to), < (less than), > (greater than), and similar operators.
o = (single equal): Used for assignment, not comparison.
o == (double equal): Used to test equality in conditions (e.g., if(x == 1)).
5. Logical Operators (Boolean Logic):
o && (AND): True if both conditions are true.
o || (OR): True if at least one condition is true.
o ! (NOT): Inverts the truth value.
▪ Example:
▪ A && !B: True if A is true and B is false.
6. Behavior of Logical Operators:
o Treats arguments as binary values (true or false).
o Non-zero values are considered true, and 0 is false.
Conditional Operations in C
1. Conditional Programming:
o Many programs include conditionals to control code execution based on
specific conditions.
o Without conditionals, programs execute line by line.
Behavior of switch Without break:
• Without break, the code "falls through" and executes subsequent cases.
• Use break to ensure mutual exclusivity.
1. Important Notes:
o Always use break in switch cases unless intentional fall-through behavior is
required.
o Be mindful of curly braces for grouped statements in if blocks.
Looping and Loop Control Constructs
1. Definition:
o Looping involves performing a task repeatedly in code.
o Examples: Iterating through arrays or performing repeated evaluations.
o Common in Arduino and other systems where processes run continuously.
2. Types of Loops in C:
o For Loop
o While Loop
o Do-While Loop
3. Key Components of Loops:
o Initialization: Set an initial condition (e.g., int i = 0).
o Increment/Step: Update a variable in each iteration (e.g., i++).
o Conditional Check: End condition to exit the loop.
Topic: Functions in C
• Purpose of Functions:
o Encapsulate a group of instructions under a single name for easy reuse.
o Essential for simplifying code, especially in platforms like Arduino.
Key Concepts and Examples:
1. Definition and Examples:
o A function groups instructions and can be reused by calling its name (e.g.,
foo()).
o Example:
▪ Code in main executes instructions and manages variables (x, y, z).
▪ A function foo() encapsulates these instructions, making the code
cleaner. main now calls foo() instead of directly including the
operations.
2. Function Call and Execution:
o Calling foo() runs the instructions encapsulated in the function.
o Both versions (direct main execution vs. function call) achieve the same
result but differ in organization.
Advantages of Using Functions:
1. Reusability:
o Avoids writing repeated code by calling the function multiple times.
o Example: Instead of duplicating the same instructions 100 times, you call
foo() 100 times.
2. Improved Code Organization:
o Makes the code more structured and easier to understand.
3. Meaningful Naming:
o Function names should reflect their purpose (e.g., connect() for networking,
not foo()).
o Meaningful names allow programmers to understand the purpose of a
function without examining its implementation.
Additional Notes:
• Comparison with Arduino Libraries:
o Similar to functions like connect() in Arduino, where a meaningful name
conveys the purpose (e.g., connecting to the internet).
• Function Definition Requirements:
o A function must be defined before it is used.
Topic: Functions in C
• Purpose and Overview:
o Functions group instructions under a single name for reuse.
o They simplify coding by reducing redundancy and making the code more
readable and maintainable.
Key Concepts (Continued):
1. Functions with Arguments:
o Arguments allow functions to operate on different inputs, making them more
generic and versatile.
o Example:
▪ A function without arguments (e.g., foo()) can only work with
predefined values (like y = 2, z = 3).
▪ A function with arguments (e.g., foo(int a, int b)) can take inputs like
foo(2, 3) or foo(1, 2) and perform the same operations with those
numbers.
o Defining Functions with Arguments:
▪ The arguments and their types are listed in the function definition
(e.g., int a, int b within parentheses after the function name).
▪ In the function call, the inputs are provided in parentheses (e.g., foo(2,
3)).
2. Returning Values from Functions:
o Functions can return results to the caller, making them more useful for
further processing.
o Example:
▪ On the left: A function like foo() prints the result directly (e.g., printf is
inside the function).
▪ On the right: foo() returns a value (e.g., return x;), which the caller
(e.g., main) assigns to a variable (p = foo()) and processes further (e.g.,
prints p).
Benefits of Using Arguments and Return Values:
1. Enhanced Reusability:
o Functions become adaptable for a wide range of inputs (e.g., average(a, b)
can average any two numbers provided as arguments).
2. Improved Modularity:
o Return values allow separation of tasks:
▪ The function performs calculations and returns the result.
▪ The caller decides what to do with the result (e.g., printing, storing).
3. Flexibility:
o Functions can be reused in various contexts with different arguments.
Function Definition Structure:
1. Arguments:
o Declared in parentheses after the function name (e.g., void foo(int a, int b)).
o Specify the data type of each argument.
2. Return Values:
o Use the return statement to send a value back to the caller.
o The function must specify its return type (e.g., int foo() returns an integer).
Conclusion:
• Functions in C are highly versatile tools that simplify code, enhance reusability, and
make programs easier to understand.
• They can take arguments for flexibility and return values for modularity.
• Proper naming conventions and structure are essential for creating clear and
effective functions.
Notes on Variables and Global Variables
Local Variables
• Declared inside a function and limited to that function.
• Scope: Exists only during the execution of the function where defined.
o Example: int i inside foo() exists only in foo(). The main() function cannot
access i.
• Each function has its own variables:
o Example: int i in foo() and int x in bar() are independent.
Global Variables
• Declared outside of any function and accessible by multiple functions.
o Example: int global_i defined globally.
• Steps to Make a Global Variable:
1. Declare the variable outside of any function.
2. Use the extern keyword in functions where the variable will be accessed
(optional in simple programs).
▪ Example: extern int global_i; in foo().
• Global variables can be shared among functions but come with potential risks:
o If a function like foo() writes an incorrect value to a global variable, it can
negatively affect other functions like bar() that rely on it.
Challenges of Using Global Variables
• Debugging Complexity:
o Global variables create hidden connections between functions.
o Bugs can propagate easily across functions, making debugging harder.
• Modularity Loss:
o Programs are less compartmentalized, and the programmer needs to track
global interactions.
• Best Practices:
o Avoid global variables when possible, especially in large programs with
multiple files.
o Use local variables or function arguments for better modularity.
Arduino Sketches and Global Variables
• Arduino sketches often use global variables for simplicity.
• Extern declarations may be skipped if the global variable is declared at the top of the
same file as the functions.