Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 77

Chapter 2

Microcontroller Fundamental and Programming


System on chip
• A System on Chip (SoC), also known as a system-
on-a-chip or SOC, is an integrated circuit (IC) that
incorporates most or all of the components required
for a complete electronic system or product on a
single chip. These components typically include a
central processing unit (CPU), memory,
input/output interfaces, and various hardware
accelerators or peripheral devices. SoCs are
commonly used in a wide range of applications,
from mobile devices and consumer electronics to
embedded systems and IoT (Internet of Things)
devices.
• Key characteristics and components of a System on Chip
include:
1. Central Processing Unit (CPU): The CPU is the primary
processing unit responsible for executing instructions and
performing calculations. SoCs often feature one or more CPU
cores, with architectures like ARM, x86, or RISC-V commonly
used.
2. Memory: SoCs integrate various types of memory, including
RAM (Random Access Memory) for temporary data storage
and Flash memory for program storage. These memory
components are essential for the proper functioning of the
device.
3. Input/Output Interfaces: SoCs provide interfaces for
connecting to various peripherals and external devices. These
interfaces can include USB ports, Ethernet, Wi-Fi, Bluetooth,
HDMI, GPIO (General Purpose Input/Output) pins, and more,
depending on the intended application.
4. Hardware Accelerators: Many SoCs incorporate specialized hardware
accelerators to offload specific tasks from the CPU, such as graphics
processing units (GPUs), digital signal processors (DSPs), video codecs,
and cryptographic accelerators. These accelerators improve performance
and power efficiency for specific workloads.
5. Power Management: SoCs often include power management units (PMUs)
to efficiently control power consumption by managing voltage and
frequency scaling and putting unused components into low-power states.
6. Peripherals: SoCs can include a wide range of peripheral components, such
as audio codecs, camera interfaces, touch screen controllers, sensors
(accelerometers, gyroscopes, etc.), and more, depending on the target
application.
7. Interconnects: SoCs feature on-chip interconnects that facilitate
communication between different components on the chip. These
interconnects are designed to minimize latency and optimize data transfer
within the SoC.
8. Security Features: In modern SoCs, security is a critical concern. They
may include hardware-based security features such as cryptographic
engines, secure boot mechanisms, and hardware-based root of trust to
protect against unauthorized access and data breaches.
Microcontrollers

The cloud architecture is divided into 2 parts


i.e.
1.Frontend
2.Backend
• Microcontrollers are compact integrated circuits (ICs) that are
designed to perform specific tasks or control various hardware
components in embedded systems. They are a fundamental part of
many electronic devices and are commonly found in appliances,
automotive systems, consumer electronics, industrial machines, and
more. Here are some key characteristics and components of
microcontrollers:
1. Central Processing Unit (CPU): Microcontrollers have a CPU that
executes instructions and performs computations. These CPUs are
typically optimized for specific tasks and may have limited
processing power compared to general-purpose CPUs.
2. Memory: Microcontrollers have two primary types of memory:
1. Program Memory (Flash or ROM): This is where the firmware or
program code is stored. It's non-volatile, meaning the code remains intact
even when power is removed.
2. Data Memory (RAM): This is used for temporary data storage during
program execution. It's volatile and loses its content when power is turned
off.
3. Input/Output (I/O) Pins: Microcontrollers have pins
that can be used for interfacing with the external world.
These pins can be configured as inputs or outputs to
connect to sensors, displays, actuators, and other
peripheral devices.
4. Peripherals: Microcontrollers often include various built-in
peripherals to facilitate specific functions, such as timers,
counters, communication interfaces (UART, SPI, I2C),
analog-to-digital converters (ADC), and pulse-width
modulation (PWM) controllers.
5. Clock Source: Microcontrollers require a clock source to
synchronize their operations. This clock can be external or
generated internally.
6. Power Supply: Microcontrollers typically operate on low
voltage levels and have specific power requirements.
7. Interrupts: They support interrupts to allow the processor
• Microcontrollers come in a wide range of types and
architectures, each tailored for specific applications.
Common microcontroller families include:
• 8-bit Microcontrollers: These are popular for simple and
low-cost applications.
• 16-bit Microcontrollers: Offering more processing power
and memory, these are used in a wide range of applications.
• 32-bit Microcontrollers: With even more processing
power and memory, these are suitable for complex tasks
and often used in industrial automation and consumer
electronics.
• Microcontrollers are programmed using low-level
languages like C or assembly language, and they are
usually programmed to perform a specific set of tasks.
Program development for microcontrollers often involves
writing code, compiling it, and then flashing it onto the
Programming Microcontrollers
• Programming microcontrollers involves writing code that tells the
microcontroller what tasks to perform. This code is typically
written in low-level languages like C or assembly language.
Here's a basic overview of how to program microcontrollers:
1. Set Up Your Development Environment:
1. Install the necessary software tools provided by the microcontroller
manufacturer, such as an Integrated Development Environment (IDE) or
command-line tools.
2. Connect your microcontroller board to your computer using a
programming cable or interface.
2. Write Your Code:
1. Use a text editor or the IDE to write your program in a language
compatible with the microcontroller's architecture. Common languages
include C, C++, and assembly language.
2. Your code should define the tasks the microcontroller needs to perform,
such as reading sensors, controlling outputs, and making decisions
based on input data.
3. Compile or Assemble Your Code:
1. Use a compiler (for high-level languages like C or C++) or an
assembler (for assembly language) to convert your human-readable
code into machine code that the microcontroller can understand.
2. The output is usually a binary file (hex file) that contains the program
in a format suitable for the microcontroller.
4. Load the Code onto the Microcontroller:
1. Use a programmer tool or the microcontroller's built-in bootloader (if
available) to transfer the compiled code onto the microcontroller's
memory. This is often done via a USB cable or other communication
methods.
2. The code is stored in the microcontroller's program memory (often
flash memory).
5. Testing and Debugging:
1. Test your program on the microcontroller to ensure it functions as
expected.
2. Debug any issues or errors in your code by using debugging tools
provided by the IDE or by adding debugging statements to your code.
6. Iterate and Refine:
1.Continue refining your code and testing it until the
microcontroller performs its intended tasks
correctly and efficiently.
2.Be prepared to make adjustments and
improvements as needed.
7.Deploy and Use:
1.Once your code is working well, you can deploy
the microcontroller in its target application. This
could be in a product, device, or system where it
performs its designed function.
Arduino Platform

• The Arduino platform is an open-source electronics development


platform that simplifies the process of creating interactive and
programmable electronic projects. It is designed to be accessible to
both beginners and experienced makers, making it a popular choice for
hobbyists, students, and professionals. Here's an overview of the
Arduino platform:
1. Hardware:
1. Arduino Boards: These are the physical hardware platforms that form the
core of the Arduino ecosystem. Examples include the Arduino Uno, Arduino
Nano, and Arduino Mega. These boards typically consist of a
microcontroller, input/output pins, and various built-in components.
2. Shields: These are additional boards that can be stacked on top of Arduino
boards to extend their functionality. Shields are available for various
purposes, such as adding Wi-Fi, Ethernet, or display capabilities.
3. Sensors and Modules: A wide range of sensors and modules are compatible
with Arduino, allowing you to add capabilities like temperature sensing,
motion detection, and GPS to your projects.
• Software:
• Arduino IDE (Integrated Development Environment): The
Arduino IDE is a user-friendly software tool that allows you to
write, compile, and upload code to Arduino boards. It uses a
simplified version of C/C++ programming language.
• Arduino Libraries: The platform provides a rich collection of
libraries that simplify interfacing with sensors, displays, and
other hardware components. These libraries save time and effort
by providing pre-written code for common tasks.
• Community Support: Arduino has a large and active online
community where you can find tutorials, code examples, and
troubleshooting assistance.
• Programming: Arduino programming is beginner-friendly and
uses a simple structure with two main functions:
setup() for initialization and loop() for continuous . You write code in the
Arduino IDE, connect your board to your computer via USB, and then
upload the code to the board
• Compatibility: Arduino is compatible with various
operating systems, including Windows, macOS, and
Linux. It can also work with popular programming
languages like Python, allowing for diverse project
integration.
• Projects: Arduino can be used to create a wide range
of projects, from simple LED blinking exercises to
complex robotics, home automation, and IoT
(Internet of Things) applications.
• Open Source: Arduino is open-source, meaning that
the design files and software are freely available for
anyone to use, modify, and distribute. This openness
has led to a vast and active community of users and
contributors.
Arduino Software Setup the IDE
• Setting up the Arduino IDE (Integrated Development
Environment) is a straightforward process. The Arduino
IDE is the software you use to write, compile, and upload
code to your Arduino board. Here's how to set it up:
• Step 1: Download the Arduino IDE
1. Go to the official Arduino website:
https://www.arduino.cc/en/software.
2. Choose the version of the Arduino IDE that matches your
computer's operating system (Windows, macOS, or
Linux). Click the download link to get the installer.
• Step 2: Install the Arduino IDE
1. Run the installer you downloaded in Step 1.
2. Follow the installation prompts, and when asked, choose the
installation location on your computer. The default location is
usually fine.
• Step 3: Open the Arduino IDE
1. Once the installation is complete, launch the Arduino IDE.
• Step 4: Configure Arduino IDE for Your Board
1. In the Arduino IDE, go to the "Tools" menu.
2. Select "Board" and choose the specific Arduino board you are
using. For example, if you're using an Arduino Uno, select
"Arduino/Genuino Uno."
3. Next, go to the "Port" submenu and choose the serial port that
corresponds to your connected Arduino board. If you're unsure
which port to select, you can check it by disconnecting and
reconnecting your Arduino board and seeing which port appears.
• Step 5: Test Your Setup
1.To ensure your setup is working correctly, you can
try a simple test. Go to "File" > "Examples" >
"01.Basics" > "Blink." This will open a sample
program that makes the onboard LED on your
Arduino board blink.
2.Click the right-arrow button (Upload) in the
Arduino IDE to compile and upload the code to
your Arduino board. If everything is set up
correctly, you should see the LED on your board
start to blink.
Writing Arduino Software
• An Arduino sketch is a program written in the
Arduino programming language. It's essentially
the code that defines the behavior and
functionality of your Arduino board. Here's a
breakdown of the key elements and structure of
an Arduino sketch:
1) Setup Function (setup()):
The setup() function is where you initialize things that need to be
set up once when your Arduino starts running.
It's called automatically by the Arduino once when the board is
powered on or reset. You might use it to configure pins, initialize
sensors, or perform any other one-time setup tasks.
2) Loop Function loop():
• The Loop() function is where you define the main logic
of your program.
• It runs continuously after the setup() function and repeats
over and over as long as the Arduino is powered on.
• You place the code for your program's ongoing tasks
within this function.
3) Comments:
• Comments in an Arduino sketch start with // for single-
line comments or are enclosed within /* */ for multi-line
comments.
• Comments are used to explain your code, provide
context, or make notes for yourself and others who might
read the code.
4) Statements and Expressions:
• Statements are individual lines of code that perform specific
actions, such as turning on an LED or reading a sensor.
• Expressions are combinations of variables, operators, and
constants that produce a value.
5) Variables:
• Variables are used to store data. In Arduino, you declare
variables with a data type (e.g., int , float, Boolean) and a
name (e.g int temperature)
6) Functions:
• You can define your own functions in an Arduino sketch.
Functions are reusable blocks of code that perform specific
tasks.
• For example, you might create a custom function to control a
motor or calculate a distance from a sensor reading.
7) Libraries:
• Arduino sketches often use libraries, which are pre-written collections of code
that provide additional functionality.
• Libraries can simplify tasks like working with displays, sensors, or
communication protocols (e.g., using the Wire library for I2C communication).
• // This is a comment
int ledPin = 13; // Declare a variable to store the LED pin number

void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}

void loop() {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
• }
Arduino sketch
• An Arduino sketch is a program written in the
Arduino programming language, which is
based on C/C++. It's used to control and
interact with Arduino microcontrollers.
Some Basic Example
• Reading a Button State This code reads the state of a button connected to
digital pin 2 and turns on the built-in LED when the button is pressed.

int buttonPin = 2; // Connect a button to digital pin 2


int ledPin = 13; // Use the built-in LED
void setup() {
pinMode(buttonPin, INPUT); // Set the button pin as an input
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}
void loop() {
int buttonState = digitalRead(buttonPin); // Read the button state

if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn on the LED if the button is pressed
} else {
digitalWrite(ledPin, LOW); // Turn off the LED if the button is not pressed
}
Trying the code on an Arduino Emulator -
Extending Arduino
• To try the code on an Arduino emulator, you can use various
online Arduino simulators that allow you to write, upload,
and run Arduino sketches virtually. One such emulator is
Tinkercad Circuits (previously known as Autodesk
Circuits). Here are the steps to run your code using
Tinkercad Circuits:
1. Visit the Tinkercad Circuits Website: Go to the Tinkercad
Circuits website (https://www.tinkercad.com/circuits/) and
create an account if you don't have one already.
2. Create a New Circuit: Once you're logged in, click on
"Create New Circuit" to start a new project.
3. Add Components: In the circuit editor, you can add
the components you need. To replicate the LED
blinking example, you'll need an Arduino board and
an LED. Search for "Arduino" and "LED" in the
components panel and add them to your workspace.
4. Connect Components: Connect the LED to the
Arduino board, just like you would in a physical
circuit. Connect the longer leg (anode) of the LED to a
digital pin (e.g., pin 13) on the Arduino and the shorter
leg (cathode) to a resistor, and then connect the other
end of the resistor to the Arduino's GND (ground) pin.
5. Write the Sketch: Click on the Arduino board to open
the code editor. You can copy and paste your Arduino
sketch into the editor.
6. Verify and Run: Click the "Start Simulation"
button (a triangle play button) to run your code. You
should see the LED on the virtual Arduino board
start blinking.
• Tinkercad Circuits will simulate the behavior of
the Arduino code, allowing you to test and debug
your projects before you build them physically.
There are also other online Arduino emulators and
simulators available if you prefer a different one.
Arduino Libraries 25 Programming & Interfacing

• Arduino libraries are pre-written code that simplifies the


process of working with specific hardware or performing
common tasks. They make it easier for you to interact with
sensors, actuators, displays, communication modules, and
more.
• Sensor Libraries:
1. Adafruit Sensor Library: Provides a common interface for
various sensors.
2. DHT Sensor Library: Used for DHT11 and DHT22
humidity and temperature sensors.
3. Adafruit BME280 Library: For the BME280
environmental sensor (humidity, temperature, pressure).

• Display Libraries:
1. Adafruit GFX Library: A graphics library for various displays.
2. Adafruit SSD1306: Library for controlling OLED displays using
the SSD1306 controller.
3. LiquidCrystal Library: For character LCD displays.
• Communication Libraries:
1. Arduino SoftwareSerial: Allows you to create additional
software serial ports.
2. Wire Library (I2C): "Inter-Integrated Circuit."For I2C
communication with various devices.
3. SPI Library: Used for SPI communication with devices like SPI
sensors or displays.
4. RF24 Library: For NRF24L01(+) wireless communication
modules.
5. Adafruit NFC Library: For NFC communication using PN532
modules.
6. Sensor Fusion and Motion Control:
1. Adafruit LSM9DS1 Library: For the
LSM9DS1 9-DOF sensor.
2.MPU6050 Library: For the MPU6050 gyroscope
and accelerometer module.
3.SparkFun BNO080 Library: For the BNO080
IMU sensor.
• User Interface Libraries:
1. Adafruit GFX Library: Provides graphics
capabilities for creating user interfaces.
2.Adafruit TFTLCD Library: For controlling TFT
LCD displays.
Thinker Simulator- Components
Arduino
Attiny 84
Sensors
Type tinkercad in google
Click on join now
Name the project
Arduino
Programming Arduino for the Internet of Things
(IoT) using timers and threads:
• It involves using Arduino boards and sensors to collect data from
the physical world and then transmitting, processing, or displaying
that data on the internet.
1. Set up your Arduino: Start by selecting the appropriate Arduino
board for your project. Common choices include the Arduino Uno,
Arduino Nano, or ESP8266/ESP32 for IoT projects. Ensure you
have the Arduino IDE installed on your computer.
2. Install necessary libraries: Depending on your IoT project's
requirements, you may need to install libraries for sensors,
communication protocols (e.g., Wi-Fi, Bluetooth), and other
hardware components. You can use the Arduino Library Manager
to install these libraries.
3. Connect hardware: Wire up your sensors and
actuators to the Arduino board. This might involve
connecting sensors via analog or digital pins,
configuring communication modules, and ensuring
proper power supply.
4. Define variables: Set up global variables to store sensor
readings, control states, and other data that your IoT
project requires.
5. Setup function: In the Arduino sketch, use the setup()
function to initialize your hardware, set pin modes,
configure timers, and establish network connections (if
using Wi-Fi or Ethernet shields).
6. Loop function: Use the Loop() function to create the
main program loop. Within this loop, you can check
sensor readings, perform data processing, and make
decisions based on the collected data.
7. Timers: To perform periodic tasks or actions at
specific intervals, you can use timers. Arduino
provides libraries like Millis() and Micros(). to
manage time-related operations. For instance, you
can use Millis() to create delays or schedule actions
every certain number of milliseconds.
8. Threads (Multitasking): Arduino boards are not
inherently multi-threaded, but you can simulate
multitasking using non-blocking code. The key is to
avoid long delays that block the execution of other
tasks. Use concepts like state machines or finite state
machines (FSMs) to manage different tasks
concurrently. You can also leverage libraries like the
Arduino Scheduler or FreeRTOS to implement more
advanced multitasking.
9. Communication: For IoT applications, you'll likely need
to transmit data to a remote server or receive commands
from the internet. Use the appropriate communication
protocols (e.g., MQTT, HTTP, WebSocket) and libraries
to handle data transfer.
10.Error handling: Implement error handling and recovery
mechanisms to ensure the reliability of your IoT system.
This might involve reconnecting to a Wi-Fi network if the
connection is lost or retrying failed data transmissions.
11.Power management: For battery-powered IoT devices,
optimize power usage by putting the Arduino into sleep
mode when it's not actively processing data or performing
tasks.
12.Testing and debugging: Test your IoT application
thoroughly and use debugging tools provided by the
Arduino IDE or external tools like serial monitors to
Example to blink an LED every second:
// Declare a variable to store the previous time the LED state was changed
unsigned long previousMillis = 0;

// Define the interval (in milliseconds) for changing the LED state
const long interval = 1000; // 1000ms = 1 second

// Variable to store the current state of the LED (LOW or HIGH)


int ledState = LOW;

// Setup function runs once when the Arduino starts


void setup() {
// Set the built-in LED pin as an OUTPUT
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// Get the current time in milliseconds since the Arduino started
unsigned long currentMillis = millis();

// Check if it's time to change the LED state based on the interval
if (currentMillis - previousMillis >= interval) {
// Save the current time as the previous time for the nextinterval
previousMillis = currentMillis;

// Toggle the LED state (if it was LOW, make it HIGH, and vice versa)
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}

// Set the LED to the new state (either HIGH or LOW)


digitalWrite(LED_BUILTIN, ledState);
}
}
Adding Security to Sensor Readings
• Adding security to sensor readings in an IoT project is
crucial, especially when dealing with sensitive data or when
you want to prevent unauthorized access or tampering
1. Use Secure Communication Protocols:
1. Transmit sensor data using secure communication protocols like
HTTPS, MQTT with TLS/SSL, or CoAP with DTLS, depending
on your IoT platform and requirements.
2. Encrypt data before sending it over the network to ensure that it
remains confidential during transmission.
2. Authentication and Authorization:
1. Implement authentication mechanisms to verify the identity of
devices and users accessing sensor data.
2. Set up access control and authorization rules to determine who
can read and write sensor data.
3. Secure Device Identity:
1. Each IoT device should have a unique, secure identity. This can be
achieved using hardware-based device IDs or cryptographic keys.
2. Avoid using default passwords or weak credentials.
4. Data Integrity:
1. Implement measures to ensure data integrity, such as message
authentication codes (MACs) or digital signatures.
2. Check received data for signs of tampering or corruption.
5. Secure Storage:
1. If the sensor data is stored locally on the device, use secure storage
mechanisms to protect it from unauthorized access.
2. Encrypt sensitive data stored in non-volatile memory.
• Secure Boot and Firmware Updates:
• Ensure that the device's boot process is secure to prevent
unauthorized firmware modifications.
• Implement secure methods for updating device firmware to
7. Physical Security:
1. Physically secure your IoT devices to prevent physical access to the
sensors or the device itself.
2. Consider tamper-evident packaging and tamper detection
mechanisms.
8. Network Security:
1. Employ network security practices such as firewalls, intrusion
detection systems, and network segmentation to protect your IoT
devices from external threats.
9. Regular Software Updates:
1. Keep the firmware and software on your IoT devices up to date to
patch known vulnerabilities.
2. Implement a mechanism for automatic or remote updates with
security in mind.
10.Logging and Auditing:
1. Implement logging of access and sensor data changes for auditing
purposes.
11. Secure Development Practices:
1. Follow secure coding practices during the development of
your IoT application to minimize the chances of introducing
vulnerabilities.
12.Security Testing:
1. Perform security testing, including penetration testing and
vulnerability assessments, to identify and address security
weaknesses in your IoT system.
13.Compliance with Standards:
1. Ensure that your IoT project complies with relevant security
standards and regulations, such as GDPR, HIPAA, or industry-
specific IoT security standards.
14.User Education:
1. Educate users or administrators about security best practices,
including strong password policies and the importance of
regular updates.
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_DHT.h>
#include <WiFi.h>
#include <WiFiClientSecure.h> // For HTTPS
#include <HTTPClient.h> // For HTTPS

// Constants for your network and server settings


const char* ssid = "YourWiFiNetwork";
const char* password = "YourWiFiPassword";
const char* serverAddress = "yourserver.com";
const int serverPort = 443; // HTTPS port

// Sensor settings
#define DHTPIN 2
#define DHTTYPE DHT22
Adafruit_DHT dht(DHTPIN, DHTTYPE);

// LED pin
const int ledPin = 13;
// Timer variables
unsigned long sensorTimer = 0;
unsigned long sendTimer = 0;
const unsigned long sensorInterval = 5000; // Read sensors every 5 seconds
const unsigned long sendInterval = 60000; // Send data every 60 seconds

// Certificate information for HTTPS (replace with your server's certificate)


const char* rootCACertificate = \
"-----BEGIN CERTIFICATE-----\n" \
"Your Server's Root CA Certificate Here\n" \
"-----END CERTIFICATE-----\n";

void setup() {
// Initialize sensors
dht.begin();

// Initialize LED pin


pinMode(ledPin, OUTPUT);

// Initialize serial communication


Serial.begin(9600);

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
void loop() {
unsigned long currentMillis = millis();

// Read sensors at a fixed interval


if (currentMillis - sensorTimer >= sensorInterval) {
readSensors();
sensorTimer = currentMillis;
}

// Send data to the server at a fixed interval


if (currentMillis - sendTimer >= sendInterval) {
sendDataToServer();
sendTimer = currentMillis;
}

// Blink the LED


toggleLED();
void readSensors() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();

if (!isnan(temperature) && !isnan(humidity)) {


Serial.print("Temperature: ");
Serial.println(temperature);
Serial.print("Humidity: ");
Serial.println(humidity);
} else {
Serial.println("Failed to read from sensor");
}
}

void sendDataToServer() {
// Create a WiFiClientSecure object
WiFiClientSecure client;

// Load the server's root CA certificate


client.setCACert(rootCACertificate);

// Connect to the server


if (!client.connect(serverAddress, serverPort)) {
Serial.println("Connection to server failed");
return;
// Prepare and send data to the server (adjust this based on your server's API)
String dataToSend = "temperature=25.5&humidity=50.0";

// Make an HTTPS POST request


HTTPClient https;
https.begin(client, serverAddress, serverPort, "/your-api-endpoint");
https.addHeader("Content-Type", "application/x-www-form-urlencoded");

int httpResponseCode = https.POST(dataToSend);

if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String response = https.getString();
Serial.println(response);
} else {
Serial.println("HTTP Request failed");
}

https.end();
}
void toggleLED() {
if (ledState) {
digitalWrite(ledPin, LOW);
} else {
digitalWrite(ledPin, HIGH);
}
ledState = !ledState;
}
Authenticating and Encrypting Arduino Data

• Authenticating and encrypting Arduino data


involves ensuring the integrity, authenticity,
and confidentiality of the data exchanged
between an Arduino device and another entity,
such as a server or another device.
• This is important for securing IoT (Internet of
Things) applications, sensor networks, and
communication between Arduino devices and
other systems
Authentication: Authentication is the process of verifying the
identity of the communicating parties to ensure that they are who
they claim to be. In the context of Arduino data, authentication
helps prevent unauthorized devices from accessing or tampering
with the data. Here are some methods for authenticating Arduino
data:
a. Pre-shared Keys (PSK): You can use a shared secret key
between the Arduino and the server/device it's communicating
with. This key is used to verify the authenticity of the Arduino
and the server/device.
b. Certificates: Using digital certificates, you can establish trust
between the Arduino and the server/device. Certificates are issued
by trusted Certificate Authorities (CAs) and can be used to verify
the identity of both parties.
c. Token-based Authentication: Implement token-based
authentication using protocols like OAuth or JWT (JSON Web
Tokens). The Arduino can request and use tokens to authenticate
Encryption: Encryption is the process of converting data into a
secure, unreadable format (ciphertext) that can only be decrypted by
authorized parties who possess the decryption key. Encrypting
Arduino data ensures that even if it's intercepted during
transmission, it remains confidential and cannot be understood by
unauthorized entities. Some encryption methods for Arduino data
include:
a. TLS/SSL: Transport Layer Security (TLS) or its predecessor,
Secure Sockets Layer (SSL), can be used to encrypt data in transit
between the Arduino and the server. This is commonly used for
securing web communication via HTTPS.
b. AES (Advanced Encryption Standard): AES is a symmetric
encryption algorithm that can be implemented on the Arduino to
encrypt and decrypt data stored on the device or transmitted over a
network.
c. Public-Key Cryptography: Public-key encryption (e.g., RSA or
ECC) can be used to establish secure communication channels and
encrypt data between the Arduino and other devices. It's often used
#include <AESLib.h> // Include the AES library

AESLib aes; // Create an AES object

byte key[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0E, 0x0F}; // 128-bit encryption key

void setup() {
Serial.begin(9600);
}

void loop() {
char message[] = "Hello, Arduino!"; // Message to encrypt

// Encrypt the message


byte encrypted[16];
aes.do_aes_encrypt((byte *)message, strlen(message), encrypted, key, 128);

Serial.print("Encrypted: ");
for (int i = 0; i < 16; i++) {
Serial.print(encrypted[i], HEX);
}
// Decrypt the message
byte decrypted[16];
aes.do_aes_decrypt(encrypted, 16, decrypted, key,
128);

Serial.print("Decrypted: ");
for (int i = 0; i < 16; i++) {
Serial.print((char)decrypted[i]);
}
Serial.println();

delay(1000); // Wait for a moment before repeating


}
Authenticating and Encrypting Arduino Data

• Authenticating and encrypting Arduino data


involves ensuring the integrity, authenticity,
and confidentiality of the data exchanged
between an Arduino device and another entity,
such as a server or another device.
• This is important for securing IoT (Internet of
Things) applications, sensor networks, and
communication between Arduino devices and
other systems
Introduction to Raspberry

• The Raspberry Pi is a series of small, affordable single-board


computers developed by the Raspberry Pi Foundation in the
United Kingdom. These versatile devices are designed to promote
computer science education and are used in a wide range of
projects and applications.
1. Affordability: One of the key features of the Raspberry Pi is its
low cost. It was created to be an accessible and affordable tool for
learning about computing and programming. Various models are
available at different price points, making it a great choice for
students, hobbyists, and professionals.
2. Hardware: Raspberry Pi boards are compact and come in
various models, with different specifications and capabilities.
They typically include a CPU, RAM, USB ports, HDMI output,
GPIO (General-Purpose Input/Output) pins, and various
connectors for peripherals.
3. Operating System: The Raspberry Pi can run various
operating systems, including Raspberry Pi OS (formerly
known as Raspbian), which is a Linux-based operating
system optimized for these devices. Users can also
install other Linux distributions and even Windows 10
IoT Core on some models.
4. Education and Learning: Raspberry Pi is an excellent
tool for learning about programming, electronics, and
computer science. It's widely used in schools and
educational programs to teach coding and computer-
related skills.
5. Projects: The Raspberry Pi is incredibly versatile and has
a wide range of applications. You can use it for everything
from building a simple web server, media center, or retro
gaming console to more complex projects like home
automation, robotics, and IoT (Internet of Things)
6. Community and Support: There is a strong
and active community of Raspberry Pi
enthusiasts, makers, and developers. This
community provides resources, tutorials, and
support for those looking to get started or
troubleshoot issues with their Raspberry Pi
projects.
7.Accessories and Add-ons: A variety of
accessories and add-ons are available for the
Raspberry Pi, including cases, cameras,
displays, and sensors, which allow you to
customize and expand your projects as needed.
Installation
1. Select an Operating System: Decide which operating system
you want to install on your Raspberry Pi. Raspberry Pi OS
(formerly Raspbian) is the official and most commonly used OS,
but there are also various other Linux distributions available.
You can even install Windows 10 IoT Core on some models.
2. Prepare an SD Card: You'll need an SD card to install the
operating system. The Raspberry Pi boots from the SD card, so
you'll want a fast and reliable one. A capacity of 8GB or more is
recommended.
3. Download the OS Image: Visit the official Raspberry Pi
website or the website of the chosen OS to download the disk
image. If you're using Raspberry Pi OS, you can download it
from the Raspberry Pi Foundation's website. Be sure to choose
the version that matches your Raspberry Pi model
3. Write the Image to the SD Card: Use a tool like Etcher
(available for Windows, macOS, and Linux) to write the
downloaded image to the SD card. This tool will handle
the writing process and ensure that the image is properly
burned to the card.
4. Configure Wi-Fi (if needed): If you're using a Wi-Fi
connection, you can configure your network settings
before booting the Raspberry Pi. To do this, create a
wpa_supplicant.conf file on the root of the SD card and
add your Wi-Fi credentials. Additionally, create an empty
file named ssh (without any extension) to enable SSH
access.
5. Insert the SD Card and Power Up: Insert the prepared
SD card into your Raspberry Pi, connect a power source
(usually via USB), and connect a display (via HDMI),
keyboard, and mouse if needed. Power up the Raspberry
Pi by plugging it in.
6. Initial Setup: When the Raspberry Pi boots up, you'll go
through the initial setup process, including setting your
timezone, changing the default password, and expanding
the file system. If you've configured Wi-Fi, you should
now be connected to your network.
7. Update and Upgrade: It's a good practice to run the
following commands to update your system and installed
packages:
sudo apt update
sudo apt upgrade
8. Software Installation: You can now start installing
software and packages specific to your project or needs
using package managers like apt or by building from source
9. Reboot: After making changes and installations, it's a good
idea to reboot your Raspberry Pi to ensure everything is
working properly.
GPIO
GPIO, which stands for General-Purpose Input/Output, is a
crucial feature of the Raspberry Pi and many other
microcontroller boards. It allows you to interact with the
physical world by providing pins that can be configured as
either input or output, and you can control or read from them
using software.
1. Pins: The Raspberry Pi has a set of GPIO pins, typically
arranged in a 40-pin header. The number and arrangement of
these pins may vary between different Raspberry Pi models.
2. Input and Output: GPIO pins can be configured as either
input or output. As input pins, they can be used to read data
from external sensors or devices. As output pins, you can use
them to control LEDs, motors, relays, and other hardware
components.
3. Voltage Levels: Raspberry Pi GPIO pins operate at 3.3V. Be
cautious not to connect them directly to devices that require a
different voltage (e.g., 5V), as this can damage your Raspberry Pi.
You might need level shifters or voltage dividers when interfacing
with such devices.
4. Pin Numbering: The pins on the Raspberry Pi are typically
numbered using two different schemes: Broadcom (BCM) GPIO
numbers and physical pin numbers. You can choose which numbering
scheme to use based on your preferences. Some libraries and code
examples might use one or the other, so it's essential to be aware of
this.
5. GPIO Libraries: To work with GPIO on a Raspberry Pi, you can use
programming languages like Python, C/C++, or others. Python is
often a popular choice because of its simplicity. You can use libraries
like RPi. GPIO for Python to interact with the GPIO pins. Other
languages and libraries are available as well.
basic example in Python using the RPi.GPIO library to turn an LED on
and off connected to a GPIO pin:

Import Libraries: The program starts by importing the necessary Python


libraries. In this case, it imports RPi.GPIO for Raspberry Pi GPIO control
and time for managing time-related functions.
import RPi.GPIO as GPIO
import time

Setmode() tells the program to use the Broadcom SOC channel numbers
for pin references. GPIO pins can be referred to using either the Broadcom
numbering (BCM) or the physical pin numbering (BOARD).
# Set the GPIO mode (BCM or BOARD)
GPIO.setmode(GPIO.BCM)

It defines the variable led_pin to store the GPIO pin number (in this case,
17) that's connected to the LED.
# Define the GPIO pin you're using
sets this pin as an output, indicating that you want to control
it to turn an LED on and off.
# Set the pin as an output
GPIO.setup(led_pin, GPIO.OUT)
This part of the code creates a loop that runs indefinitely
using while True

try:
while True:
GPIO.output(led_pin, GPIO.HIGH) # Turn the LED on
turns the LED on by sending a signal to the GPIO pin to
make it HIGH, which typically powers the LED
time.sleep(1)

pauses the program for 1 second, keeping the LED on.


GPIO.output(led_pin, GPIO.LOW) # Turn the
LED off
turns the LED off by setting the GPIO pin to LOW,
which turns off the power to the LED.
time.sleep(1)
pauses the program for another second, keeping the
LED off.

except KeyboardInterrupt:
GPIO.cleanup() # Cleanup GPIO pins on
program exit
basic example in Python using the RPi.GPIO library to turn an LED on and off connected to
a GPIO pin:
import RPi.GPIO as GPIO
import time

# Set the GPIO mode (BCM or BOARD)


GPIO.setmode(GPIO.BCM)

# Define the GPIO pin you're using


led_pin = 17

# Set the pin as an output


GPIO.setup(led_pin, GPIO.OUT)

try:
while True:
GPIO.output(led_pin, GPIO.HIGH) # Turn the LED on
time.sleep(1)
GPIO.output(led_pin, GPIO.LOW) # Turn the LED off
time.sleep(1)

except KeyboardInterrupt:

You might also like