0% found this document useful (0 votes)
11 views17 pages

Programming and Interfacing With Microcontroller 1

Uploaded by

tnagalaxmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views17 pages

Programming and Interfacing With Microcontroller 1

Uploaded by

tnagalaxmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming and Interfacing with Microcontroller

UNIT-I
Introduction – History - Creative Coding Platforms - Open Source Platforms – PIC - Arduino,
Sketch, Raspberry Pi, Iterative coding methodology – Python Programming - Mobile phones
and similar devices - Arm Devices - Getting used to Arduino - Sensor Characterization:
Safety, Basic Electronics (circuit theory, measurements, parts identification) Sensors and
Software: Understanding Processing Code Structure, variables and flow control, Interfacing
to the Real World
Introduction to Coding Platforms
Coding platforms are online tools and environments that allow users to write, test, and
debug code in various programming languages. These platforms are widely used by
developers, students, and educators for learning, practicing coding skills, participating in
competitions, and preparing for technical interviews.
They typically offer features like:
 Interactive code editors
 Compiler and runtime support for multiple languages
 Problem-solving challenges
 Code submission and automated testing
 Gamification through points, badges, and leader boards
Creative coding refers to writing code primarily for creative expression — such as digital
art, generative visuals, music, animations, and interactive experiences. Unlike traditional
software development, creative coding often values aesthetics, exploration, and
experimentation over efficiency or functionality.

Early Foundations (1980s–1990s)

 Processing the roots: The foundations of creative coding trace back to the ideas of
visual programming and early computer art, including work by pioneers like
Harold Cohen (creator of AARON) and institutions like MIT Media Lab.
 Languages like Logo (with its turtle graphics) introduced many young learners to
visual expression through code.

Processing (2001)

 Processing was a game-changer. Created by Casey Reas and Ben Fry, it is an open-
source programming language and IDE built on Java, designed specifically for artists
and designers.
 Its simple syntax and visual output made it highly accessible for non-programmers
interested in digital art.
 It inspired a huge community of artists, educators, and students around the world.

OpenFrameworks (2005) & Cinder (2010)

 OpenFrameworks and Cinder were developed as powerful C++ toolkits for creative
coding.
 They offer more low-level control and performance than Processing, making them
popular for installations, real-time visuals, and multimedia performances.

Web-Based Platforms (2010s–Present)

 The shift to the browser and web technologies led to platforms like:
o p5.js (2014): A JavaScript version of Processing, maintaining its accessibility
and community spirit.
o Three.js: A JavaScript library for 3D graphics using WebGL, widely used in
interactive and immersive web projects.
o Tone.js: For creative sound synthesis and music-making in the browser

Online Creative Coding Communities

 Open Processing: A sharing platform for p5.js and Processing sketches. Like
YouTube for creative code.
 Glitch: A friendly platform for building and remixing full web apps, popular among
creative developers.
 Replit: While general-purpose, it supports collaborative, creative, and interactive
coding projects.
 ShaderToy: A platform focused on GLSL (OpenGL Shading Language) for creating
stunning visual effects with code.

AI and Generative Art (2020s–Present)

 Integration of AI into creative workflows is now reshaping creative coding:


o Tools like RunwayML, Magenta (by Google), and Playform use machine
learning for generative art, music, and design.
o Platforms like TouchDesigner are used for real-time visuals in immersive
installations, often blending traditional creative coding with AI and data
streams.

Summary Table

Era Key Platforms Focus

1980s–1990s Logo, Turtle Graphics Educational, simple visuals

2001–2010 Processing, OpenFrameworks, Cinder Visual arts, interactive design

2010s p5.js, Three.js, OpenProcessing Web-based creative coding

ShaderToy, RunwayML, Glitch, Real-time visuals, AI art, immersive


2020s
TouchDesigner media

Open-source platforms are tools, software, or hardware projects whose source code or
design is freely available for anyone to use, modify, and distribute. In the context of PIC,
these platforms help developers program and build systems with PIC microcontrollers
without relying only on proprietary software.
PIC Platform:

PIC stands for Peripheral Interface Controller, though it’s now more commonly referred
to simply as PIC microcontroller. The PIC platform refers to the ecosystem around these
microcontrollers, including:

 PIC Microcontroller Families (e.g., PIC10, PIC12, PIC16, PIC18, PIC24, and
dsPIC)
 Development Tools (hardware and software)
 Programming and Debugging Interfaces
 Software Libraries and IDEs

Key Features of PIC Microcontrollers:

1. Wide Range of Models: From low-cost 8-bit MCUs to more powerful 16- and 32-bit
MCUs.
2. Low Power Consumption: Designed for battery-powered or energy-efficient
devices.
3. Integrated Peripherals: Timers, ADCs, UART, I2C, SPI, PWM, and more.
4. Ease of Use: Supported by user-friendly development tools.
5. Scalability: Easy to move between devices in the same family.

Development Environment

1. MPLAB X IDE: Official integrated development environment from Microchip.


2. XC Compilers: C compilers optimized for different PIC families (XC8, XC16,
XC32).
3. MPLAB Code Configurator (MCC): GUI tool to auto-generate initialization code.
4. Programmers/Debuggers:
o PICkit (e.g., PICkit 4)
o ICD (In-Circuit Debugger)
o Curiosity Boards (easy entry-level development boards)

Applications of the PIC Platform

 Home automation
 Automotive systems
 Industrial control
 Consumer electronics
 IoT devices
 Robotics and embedded systems education

MPLAB X IDE:

MPLAB X IDE is the official integrated development environment (IDE) from Microchip Technology
used to program and debug PIC microcontrollers and dsPIC Digital Signal Controllers.

It’s built on the NetBeans platform and runs on Windows, macOS, and Linux.
Key Features of MPLAB X IDE:

 Project Management: Handles multiple configurations and devices in one workspace.

 Device Support: Compatible with a wide range of Microchip devices.

 Code Editing: Includes syntax highlighting, code completion, and refactoring tools.

 Debugging: Step-by-step execution, breakpoints, watch variables, and more.

 Simulator Support: Simulate your code even without hardware.

Peripheral Visualization: View real-time peripheral register states during debugging.

MPLAB Code Configurator (MCC)

MCC is a plugin for MPLAB X IDE that auto-generates C code for initialization and configuration of
microcontroller peripherals.

Why MCC is Awesome:

 GUI-Based Configuration: No need to memorize register settings.


 Drag-and-Drop Interface: Set up peripherals like UART, ADC, Timers, I2C, etc.
 Real-Time Validation: Warns about incompatible settings.
 Code Generation: Creates boilerplate and driver code with comments and function calls.

Great for beginners AND experts — speeds up development and reduces human error.

MPLAB Code Configurator (MCC)

MCC is a plugin for MPLAB X IDE that auto-generates C code for initialization and configuration of
microcontroller peripherals.

Why MCC is Awesome:

 GUI-Based Configuration: No need to memorize register settings.


 Drag-and-Drop Interface: Set up peripherals like UART, ADC, Timers, I2C, etc.
 Real-Time Validation: Warns about incompatible settings.
 Code Generation: Creates boilerplate and driver code with comments and function calls.

Great for beginners AND experts — speeds up development and reduces human error.

MPLAB Programmers and Debuggers

These tools allow you to upload code, debug in real-time, and program devices in-circuit:

1. PICkit 4 (Latest in the PICkit series)

 Budget-friendly
 USB-powered
 Supports a wide range of devices
 Can be used for debugging and programming

2. MPLAB ICD 4 (In-Circuit Debugger)

 Faster programming/debugging
 More advanced than PICkit
 Ideal for professional use

3. Curiosity Boards

 Development boards with on-board debugger


 No need for external PICkit
 Great for learning and prototyping

How It All Fits Together:

1. Design your project in MPLAB X IDE


2. Use MCC to configure the peripherals
3. Compile using XC compiler (e.g., XC8)
4. Program/debug using PICkit, ICD, or Curiosity board

Arduino Sketch:

An Arduino sketch is the name given to the program written for Arduino boards. It's the code that
tells the Arduino what to do—like turning on LEDs, reading sensors, controlling motors, etc.

Key Points About an Arduino Sketch:

1. File Type

 Sketches are saved with a .ino file extension.


 Example: blinking_led.ino

Structure

An Arduino sketch has two main functions:

cpp
CopyEdit
void setup() {
// runs once when the Arduino is powered on or reset
}

void loop() {
// runs continuously in a loop after setup() finishes
}

 setup(): Used to initialize settings, like setting pin modes.


 loop(): Where the main code goes; it keeps running over and over.
3. Basic Example

Here’s a simple sketch to blink an LED on pin 13:

cpp
CopyEdit
void setup() {
pinMode(13, OUTPUT); // Set pin 13 as output
}

void loop() {
digitalWrite(13, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(13, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
}
4. Upload Process

 The sketch is written in the Arduino IDE.


 When you hit Upload, the IDE compiles the sketch and sends it to the Arduino via USB.

5. Language Used

 Arduino uses a simplified version of C/C++.


 It has built-in functions (like digitalWrite, analogRead, etc.) that make hardware
programming easier.

Raspberry pi:

The Raspberry Pi is a small, affordable, single-board computer developed by the


Raspberry Pi Foundation. It was originally created to promote computer science education,
but it’s now widely used in DIY projects, robotics, programming, IoT, and even small-scale
servers.

Key Features

 Size: About the size of a credit card.


 Cost: Very affordable (typically $5–$70 depending on the model).
 OS: Runs a Linux-based OS (mainly Raspberry Pi OS, formerly Raspbian).
 Connectivity: Has USB ports, HDMI, Wi-Fi, Bluetooth (on newer models), Ethernet.
 GPIO Pins: General-Purpose Input/Output pins for connecting sensors, LEDs, motors, etc.

Common Models
Model Description

Raspberry Pi 4 Powerful version with up to 8GB RAM, 4K support

Raspberry Pi 3 Still capable, has Wi-Fi and Bluetooth built-in

Raspberry Pi Zero Very small and cheap, great for compact projects

Raspberry Pi 5 Latest version (as of 2024), faster CPU, PCIe support


What Can You Do With It?

 Learn programming (Python, C, Java, etc.)


 Build DIY electronics projects
 Create a retro gaming console (e.g., with RetroPie)
 Set up a home server or media center (e.g., with Plex or Kodi)
 Automate home tasks (smart lights, sensors, cameras)
 Learn Linux and computer basics

Basic Hardware Ports

 USB Ports – Connect keyboard, mouse, or USB drives.


 HDMI Port – Connect to a monitor or TV.
 Ethernet Port – For wired internet (on some models).
 Audio Jack – For speakers or headphones.
 MicroSD Slot – Used as the hard drive (stores OS and files).
 GPIO Pins – For electronics projects.

Operating System

Most common OS: Raspberry Pi OS

Others include: Ubuntu, Kali Linux, LibreELEC, Windows IoT Core

Programming on Raspberry Pi

You can write code directly on the Pi using:

 Python (most common)


 C/C++
 Java
 Scratch (for kids)
 Node.js, etc.

Iterative Coding Methodology: Iterative coding is a development approach where


software is built and improved step by step, through repeated cycles (iterations). Each
cycle involves designing, coding, testing, and refining a small part of the program.

It’s like writing your code in layers—starting with something basic that works, then adding
features, improving performance, or fixing bugs in each new version.

How It Works

1. Start small: Write a simple version of the program that works (a "minimum viable version").
2. Test it: Make sure it runs and does what it should.
3. Get feedback or reflect: What can be improved or added?
4. Refine or expand: Make improvements or add features.
5. Repeat: Go through the process again with the next goal in mind.
Iterative Coding Cycle
Plan → Code → Test → Review → Improve → (repeat)
Benefits

 Early working version: You get something functional early on.


 Easy to debug: Errors are easier to spot when code is added in small parts.
 Flexible: You can change direction based on feedback.
 Continuous learning: You understand your own code better as you go.

Real-World Example

Let’s say you’re building a calculator app:

1. First iteration: Make it add two numbers.


2. Second iteration: Add subtraction.
3. Third iteration: Add multiplication and division.
4. Fourth iteration: Add a GUI interface.

What is Python?

Python is a high-level, interpreted programming language known for its simplicity, readability, and
versatility. It’s great for both beginners and professionals.

Key Features

 Easy to read & write – Looks like plain English


 Interpreted – Runs line by line (no need to compile)
 Dynamically typed – No need to declare variable types
 Large standard library – Built-in tools for many tasks
 Cross-platform – Works on Windows, Mac, Linux, etc.

What Can You Do With Python?

 Web development (e.g., Django, Flask)


 Data analysis & visualization (e.g., Pandas, Matplotlib)
 Machine learning & AI (e.g., TensorFlow, scikit-learn)
 Automation & scripting
 Game development (e.g., Pygame)
 Internet of Things (IoT) with Raspberry Pi

Simple Example
python
CopyEdit
# This program prints "Hello, world!"
print("Hello, world!")
Popular Libraries

 NumPy – for math & arrays


 Pandas – for data analysis
 Tkinter – for GUI apps
 Requests – for web access
 Matplotlib – for plotting graphs

Mobile Phones

What are they?

Mobile phones are portable electronic devices used primarily for communication—calls, texts, and
now, much more.

Modern Mobile Phones (Smartphones)

 Touchscreen interface
 Run on operating systems like Android or iOS
 Access the internet via Wi-Fi or mobile data
 Support apps for messaging, gaming, productivity, and more
 Have cameras, GPS, sensors, and more

Smart Devices

What are they?

Smart devices are electronic gadgets that can connect, share data, and often be controlled
remotely. They are part of the Internet of Things (IoT).

🏠 Common Smart Devices

 Smartwatches – show notifications, track health


 Smart TVs – stream content, connect to internet
 Smart speakers – like Amazon Echo (Alexa), Google Nest (Assistant)
 Smart bulbs & thermostats – controlled via phone or voice
 Smart appliances – fridges, washing machines with app controls

Common Features of Smart Devices

 Wi-Fi/Bluetooth connectivity
 App integration (control via phone)
 Voice control (Alexa, Google Assistant, Siri)
 Automation (e.g., lights turn on at sunset)
 Data sharing for analytics or syncing
How They Work Together

Smartphones often act as a control center for other smart devices. For example:

 Use your phone to adjust your smart thermostat


 Get a phone notification from a smart doorbell camera
 Control your lights or music with your voice through your phone or smart speaker

What Are ARM Devices?

ARM devices are electronic devices powered by ARM processors — a type of CPU architecture
designed by ARM Holdings. ARM stands for Advanced RISC Machine.

These processors are widely used in mobile phones, tablets, smartwatches, Raspberry Pi, and many
IoT devices, because they are small, energy-efficient, and powerful.

Key Features of ARM

 RISC-based architecture (Reduced Instruction Set Computing)


→ Uses simpler instructions, which makes it faster and more efficient
 Lowpowerconsumption
→ Perfect for battery-powered devices
 Highperformance
→ Modern ARM chips can handle complex tasks like video editing, gaming, and AI

Where Are ARM Chips Used?


Device Type Examples

Smartphones iPhone, Samsung Galaxy, etc.

Tablets iPad, Android tablets

Single-board PCs Raspberry Pi

Wearables Smartwatches, fitness trackers

Embedded systems Smart home gadgets, robotics

Laptops (recent) Apple M1/M2/M3 Macs, ARM Chromebooks

Popular ARM-Based Processors

 Snapdragon (by Qualcomm)


 Apple A-series / M-series
 Exynos (by Samsung)
 MediaTek chips
 Broadcom (used in Raspberry Pi)
ARM vs x86 (like Intel/AMD)
Feature ARM x86 (Intel/AMD)

Power Usage Very low Higher

Performance Excellent for mobile Excellent for desktops

Use Case Phones, tablets, IoT PCs, laptops, servers

Instruction Set RISC (simple) CISC (complex)

Sensor characterization is the process of understanding how a sensor behaves:

 What kind of data it gives


 How accurate and reliable that data is
 How to interpret its output correctly using Arduino

Why Is It Important?

Before using a sensor in a real project (like a weather station or robot), you need to know:

 What values it gives under different conditions


 How fast and how often it gives those values
 What voltage or digital signal it outputs
 How stable and trustworthy the data is

Part 1: Getting Used to Arduino

Arduino is an open-source electronics platform based on easy-to-use hardware and software. It’s
perfect for beginners to learn about microcontrollers and electronics.

Steps to Get Comfortable with Arduino:

1. Set Up Your Environment:


o Download and install the Arduino IDE from the official site.
o Connect your Arduino board (like Uno, Nano, etc.) via USB.
o Select the correct board and COM port in the IDE.
2. Start with Basic Examples:
o Try the “Blink” example (File > Examples > Basics > Blink) to flash an LED. This
teaches you about digital output.
o Move on to other examples like:
 DigitalReadSerial – Read a button.
 AnalogReadSerial – Read a sensor or potentiometer.
3. Learn the Basics of the Arduino Language: Arduino uses a C/C++-like language.
o pinMode() – to set pin direction.
o digitalWrite() / digitalRead() – to control/read digital pins.
o analogRead() / analogWrite() – to read sensors or control things like motors.
4. Play with Hardware:
o Use basic components: LEDs, resistors, buttons, potentiometers, buzzers.
o Then try sensors: temperature, light (LDR), distance (ultrasonic), etc.
5. Use Serial Monitor for Debugging:
o Use Serial.begin(9600); and Serial.println() to print values to your PC.

Part 2: Sensor Characterization

Sensor characterization means understanding how a sensor behaves and how its output relates to
what it’s measuring. This is crucial if you want accurate and reliable readings.

Steps to Characterize a Sensor:

1. Understand the Sensor Type:


o Is it analog (like an LDR or thermistor) or digital (like a DHT11 temperature sensor)?
o Check the datasheet for info on operating voltage, range, and output format.
2. Connect and Read Values:
o For analog sensors: Use analogRead().
o For digital sensors: Use appropriate libraries or protocols (I2C, SPI, etc.).
3. Record Output vs. Physical Value:
o Example: If you're using a light sensor (LDR), expose it to different light levels and
record analogRead() values.
o Compare with real-world units if possible (lux, degrees Celsius, etc.).
4. Create a Calibration Curve:
o Plot sensor readings vs. actual values.
o Fit a mathematical model (e.g., linear, logarithmic) to convert raw readings into
meaningful units.
5. Identify Key Characteristics:
o Sensitivity – how much the output changes with input.
o Range – the minimum and maximum measurable input.
o Response Time – how fast the sensor reacts.
o Linearity – how straight the input-output relationship is.
6. Implement in Code:
o Use formulas or lookup tables in your Arduino code to convert raw values to
calibrated results.

Example:

Let’s say you’re using an LM35 temperature sensor:

 Connect VCC to 5V, GND to GND, and output to A0.


 Read the analog value:

cpp
CopyEdit
int raw = analogRead(A0);
float voltage = raw * (5.0 / 1023.0);
float temperatureC = voltage * 100; // LM35 gives 10mV/°C
Serial.println(temperatureC);
Sensor Characterization: A Full Overview

Sensor characterization is the process of understanding how a sensor behaves—how it responds to


different physical inputs and how to interpret its outputs.
To do this properly and safely, we need to consider three areas:

1. Safety

Safety is always the first step when working with electronics and sensors.

Key Safety Practices:

 Power Off Before Wiring: Always disconnect power before changing connections.
 Use Correct Voltage: Supplying more voltage than a sensor can handle can damage it (and
your Arduino).
 Avoid Shorts: Ensure no wires are accidentally touching or crossing.
 Use Resistors Where Needed: Especially with LEDs, buttons, and some sensors (e.g., voltage
dividers).
 Check Polarity: Don’t reverse VCC and GND—this can instantly destroy a component.

2. Basic Electronics Essentials

Understanding core electronics helps with proper sensor connection and data interpretation.

Components Identification:

 Resistors – control current flow.


 Capacitors – store electrical charge.
 Diodes/LEDs – one-way current flow / light-emitting.
 Transistors – amplify/switch signals.
 Sensors – detect physical properties (temperature, light, sound, etc.)

Circuit Theory Basics:

 Ohm’s Law: V = I × R
(Voltage = Current × Resistance)
 Series vs Parallel Circuits:
o Series: Current is same everywhere.
o Parallel: Voltage is same across branches.
 Voltage Dividers:
o Used with analog sensors like thermistors or LDRs.
o Formula:
Vout = Vin × (R2 / (R1 + R2))

Measurements (using multimeter):

 Voltage (V) – measure across components.


 Current (A) – measure in series with the circuit.
 Resistance (Ω) – measure when the component is not powered.
 Continuity Test – check if a wire or trace is unbroken.

3. Understanding & Characterizing Sensors


What is a Sensor?

A device that converts physical phenomena (temperature, light, pressure, etc.) into an electrical
signal.

Characterizing a Sensor Involves:

1. Identifying the Sensor Type:


o Analog: Outputs a voltage between 0–5V (or 0–3.3V).
o Digital: Outputs HIGH/LOW or data via protocol (I2C, SPI, OneWire).
o Passive: Needs external circuitry (e.g., thermistors).
o Active: Has built-in signal processing (e.g., DHT11).
2. Wiring & Reading:
o Use datasheet to find correct pinout.
o Connect to Arduino and start reading values (analogRead or library functions).
3. Data Collection:
o Expose the sensor to a known range of conditions.
o Record the sensor output at each step.
4. Create a Response Curve:
o Plot sensor output vs. physical input (e.g., volts vs temperature).
o Fit a trendline or apply a formula for conversion.
5. Check These Characteristics:
o Accuracy: How close is it to the real value?
o Precision: How consistent is the reading?
o Resolution: Smallest detectable change.
o Sensitivity: Change in output per unit change of input.
o Linearity: Is the relationship between input and output linear?
o Response Time: How fast it reacts to change?

Example: Thermistor (Temperature Sensor)

 Uses a voltage divider circuit.


 Output is analog voltage based on temperature.
 Characterization steps:
o Build voltage divider circuit with thermistor and fixed resistor.
o Measure analog voltage at various known temperatures.
o Convert voltage to resistance, then use a formula (e.g., Steinhart-Hart equation) to
get temperature.

Tools Use:

 Multimeter – for voltage, resistance, current.


 Breadboard & Jumper Wires – easy testing.
 Arduino – reads sensor data.
 Serial Monitor – view live data.
 Plotting Software – Excel, Google Sheets, or Arduino serial plotter for graphs.

Software for Arduino: Getting Hands-On


1. Understanding Processing Code Structure

In Arduino, your code is written in a simplified C/C++ language. Every program is called a "sketch"
and follows this basic structure:

cpp
CopyEdit
void setup() {
// runs once when the Arduino starts
}

void loop() {
// runs repeatedly forever
}
What Each Part Does:

 setup() – Used to initialize things like pin modes, serial communication, sensors, etc.
 loop() – Where your main program runs over and over again.

Example:
cpp
CopyEdit
void setup() {
pinMode(13, OUTPUT); // set pin 13 as output
}

void loop() {
digitalWrite(13, HIGH); // turn LED on
delay(1000); // wait 1 second
digitalWrite(13, LOW); // turn LED off
delay(1000); // wait 1 second
}

This code blinks an LED every second.

2. Variables and Flow Control

Variables

Variables are used to store data (numbers, text, etc.) that your program uses.

Type Description Example


int Integer (-32,768 to 32,767) int count = 5;
float Decimal numbers float temp = 23.4;

bool Boolean (true/false) bool isOn = true;

char Single character char letter = 'A';

String Text string String name = "Ayo";

Flow Control

These are the tools that let your program make decisions and repeat actions:
 if, else – Decision-making

cpp
CopyEdit
if (temp > 30) {
// turn on fan
} else {
// fan stays off
}

 for loop – Run a block of code a fixed number of times

cpp
CopyEdit
for (int i = 0; i < 10; i++) {
// do something 10 times
}

 while loop – Repeat while a condition is true

cpp
CopyEdit
while (digitalRead(buttonPin) == LOW) {
// wait for button to be pressed
}

 switch-case – Efficient multiple-choice control

cpp
CopyEdit
switch (mode) {
case 1: // do something; break;
case 2: // do something else; break;
}

3. Interfacing to the Real World

This is where things get exciting! You write software to interact with the physical world using inputs
(sensors) and outputs (actuators).

Inputs: Reading the World

 Analog sensors – temperature sensors, light sensors, etc.

cpp
CopyEdit
int lightLevel = analogRead(A0);

 Digital sensors – buttons, PIR motion sensors, etc.

cpp
CopyEdit
bool motion = digitalRead(2);
Outputs: Controlling Things

 LEDs – light up to show feedback.


 Buzzers – sound notifications.
 Motors/Relays – move things or switch devices.

cpp
CopyEdit
digitalWrite(5, HIGH); // turn on motor
Communication with the PC

 Use the Serial Monitor:

cpp
CopyEdit
Serial.begin(9600); // start serial
Serial.println(lightLevel); // print value

This is super useful for debugging and data visualization.

Example: Basic Sensor + Output Flow


cpp
CopyEdit
int sensorPin = A0;
int ledPin = 13;
int threshold = 500;

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

void loop() {
int sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);

if (sensorValue > threshold) {


digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}

delay(100);
}

You might also like