5g and Iot Notes
5g and Iot Notes
Simply, the "G" stands for "GENERATION". While connected to the internet, the speed of the
connec on depends upon the signal strength that is shown in abbrevia ons like 2G, 3G, 4G,
5G, etc. on any mobile device. Each genera on of wireless broadband is defined as a set of
telephone network standards that describe the technological implementa on of the system.
o Introduced in the 1980s, 1G technology was purely analog and provided basic voice
communica on. It used frequency modula on for voice signals and was highly prone
to sta c and noise. The systems were circuit-switched and had low capacity, leading
to frequent dropped calls.
o Technology: Analog cellular systems like AMPS (Advanced Mobile Phone System).
o Drawbacks: Poor voice quality, frequent call drops, lack of data services.
2G (Second Genera on):
o Launched in the 1990s, 2G was the first digital mobile communica on system. It
introduced digital encryp on, data services like SMS and MMS, and improved call
quality. Technologies like GSM (Global System for Mobile communica ons) and CDMA
(Code Division Mul ple Access) emerged in this era.
o Technology: Digital, introduced technologies like GSM (Global System for Mobile
Communica ons) and CDMA (Code Division Mul ple Access).
o Features: Enhanced voice clarity, basic data services (SMS and MMS), be er security
with encryp on.
o Examples: GSM networks that became the founda on for future mobile
communica on.
Introduced around the early 2000s, 3G brought significant improvements in data transfer
speeds, enabling mobile broadband services. It facilitated video calls, mobile internet
access, and streaming services. Key technologies include UMTS (Universal Mobile
Telecommunica ons System) and CDMA2000.
o Features: Faster data speeds (up to 2 Mbps), video calling, mobile internet.
o Launched in the late 2000s, 4G focused on high-speed internet access and the ability
to transmit large amounts of data. LTE (Long Term Evolu on) and WiMAX are the
predominant 4G technologies. It supports mobile HD TV, video conferencing, and
faster online gaming.
o Features: Speeds up to 100 Mbps for mobile, seamless video streaming, online
gaming.
o Real-world Usage: Services like Ne lix, YouTube, and social media apps flourished
due to 4G networks.
An Overview of 5G Requirements :
5G (Fi h Genera on):
5G, the latest genera on, offers extremely high speeds, ultra-low latency, and massive
connec vity. It enables advanced applica ons such as IoT, autonomous vehicles, and smart
ci es. The key features include Enhanced Mobile Broadband (eMBB), Ultra-Reliable Low-
Latency Communica ons (URLLC), and Massive Machine Type Communica ons (mMTC)
o Massive Device Connec vity: 5G is designed to connect a vast number of IoT devices
efficiently.
o Energy Efficiency: 5G networks aim to consume less energy per transmi ed data unit.
o Spectrum Efficiency: Efficient use of the spectrum is cri cal for handling the increased
demand for bandwidth.
o Global Standards: Organiza ons like the ITU (Interna onal Telecommunica on Union)
and 3GPP (3rd Genera on Partnership Project) work on crea ng unified global
standards for 5G.
o Security and Privacy: Regula ons also focus on ensuring secure communica on and
protec ng user privacy.
o mmWave (Millimeter Wave): Offers extremely high bandwidth but limited range and
penetra on.
o Dynamic Spectrum Sharing (DSS): Allows 5G to share the spectrum with 4G LTE,
ensuring smooth transi ons and be er resource u liza on.
o Carrier Aggrega on: Combining mul ple frequency bands to improve bandwidth and
data rates.
Channel modeling
A model that reflects the communica on characteris cs of radio signals. It can be
used to study the channel's transmission capability.
Spectrum
5G networks require a large amount of spectrum, or radio frequencies, to support
high data rates and low latency.
Millimeter-wave (mm-Wave) technology
5G networks use mm-Wave technology, which operates in the 24.25–52.6 GHz
frequency range. This technology allows for a wider range of frequencies, which
results in a larger bandwidth and be er data transmission rates.
Challenges
Cost
5G networks can be expensive to implement due to the cost of spectrum, hardware,
and planning permissions.
Infrastructure
5G networks may face challenges related to infrastructure, such as gaps in coverage
and penetra on.
Cybersecurity
5G networks may be vulnerable to cybera acks, despite having more
comprehensive algorithms than previous networks.
Latency
5G networks need to have low latency, which is the me it takes for a data signal to
travel from one point to another and back.
Urban Macro (UMa):
o Scenario: Dense urban environments with tall buildings.
o Challenges: High path loss, significant mul path effects, and frequent
handovers due to small cell size.
Channel Models:
o NYUSIM: A popular simulator for mmWave channel modeling.
o Cluster-based models: Group mul path components into clusters for easier
modeling.
o Ray Tracing: Predicts the path of radio waves through the environment using
geometrical op cs principles.
IEEE 802.15.4
IEEE 802.15.4 is a standard that defines the physical layer (PHY) and media access control (MAC)
sublayer for low-rate wireless networks. It's used in home automa on, sensor networking, and the
Internet of Things (IoT). (or)
IEEE 802.15.4 is a technical standard that defines the opera on of a low-rate wireless personal area
network (LR-WPAN).
IEEE 802.15.4-2006 was published a er revisions and improvements made by IEEE 802.15
TG4b
Defines the MAC and PHY layers for low-rate wireless personal area networks (LR-WPANs)
Specifies how to insert MAC headers and footers into network-layer frames
Provides the basis for higher-layer standards like ZigBee, WirelessHART, and 6LoWPAN
Architecture
The LR-WPAN architecture is defined in terms of a number of blocks in order to simplify the
standard. These blocks are called layers. Each layer is responsible for one part of the standard
and offers services to the higher layers. The layout of the blocks is based on the open systems
interconnec on (OSI) seven-layer model (see 2.2).
An LR-WPAN device comprises a PHY, which contains the radio frequency (RF) transceiver
along with its low-level control mechanism, and a MAC sublayer that provides access to the
physical channel for all types of transfer. Figure 3 shows these blocks in a graphical
representa on
PHY
The PHY provides two services:
the PHY data service and the PHY management service interfacing to the physical layer
management en ty (PLME). The PHY data service enables the transmission and recep on of
PHY protocol data units (PPDUs) across the physical radio channel. Clause 6 contains the
specifica ons for the PHY. Figure 3—LR-WPAN device architecture Physical Medium PHY MAC
802.2 LLC Upper Layers SSCS IEEE WIRELESS MAC AND PHY SPECIFICATIONS FOR LR-WANS Std
802.15.4-2003 .
The features of the PHY are ac va on and deac va on of the radio transceiver, ED, LQI,
channel selec on, clear channel assessment (CCA), and transmi ng as well as receiving
packets across the physical medium. The radio shall operate at one of the following license-
free bands:
— 868–868.6 MHz (e.g., Europe),
— 902–928 MHz (e.g., North America) or
IoT Protocols:
These protocols are used to establish communica on between a node device and a
server over the internet. it helps to send commands to an IoT device and receive data
from an IoT device over the internet. we use different types of protocols that are
present on both the server and client side and these protocols are managed by
network layers like applica on, transport, network, and link layer.
Applica on Layer protocol:
In this layer, protocols define how the data can be sent over the network with the lower
layer protocols using the applica on interface. these protocols include HTTP,
WebSocket, XMPP, MQTT, DDS, and AMQP protocols.
HTTP
Hypertext transfer protocol is a protocol that presents in an applica on layer for
transmi ng media documents. it is used to communicate between web browsers and
servers. it makes a request to a server and then waits ll it receives a response and in
between the request server does not keep any data between the two requests.
WebSocket
This protocol enables two-way communica on between a client and a host that can be
run on an untrusted code in a controlled environment. This protocol is commonly used
by web browsers.
MQTT
It is a machine-to-machine connec vity protocol that was designed as a
publish/subscribe messaging transport. and it is used for remote loca ons where a small
code footprint is required.
Transport Layer:
This layer is used to control the flow of data segments and handle error control. also, these
layer protocols provide end-to-end message transfer capability independent of the underlying
network.
TCP
The transmission control protocol is a protocol that defines how to establish and maintain
a network that can exchange data in a proper manner using the internet protocol.
UDP
a user datagram protocol is a part of an internet protocol called the connec onless
protocol. this protocol is not required to establish the connec on to transfer data.
Network Layer:
This layer is used to send datagrams from the source network to the des na on network.
we use IPv4 and IPv6 protocols as host iden fica on that transfers data in packets.
IPv4
This is a protocol address that is a unique and numerical label assigned to each device
connected to the network. an IP address performs two main func ons host and
loca on addressing. IPv4 is an IP address that is 32-bit long.
IPv6
It is a successor of IPv4 that uses 128 bits for an IP address. it is developed by the IETF
task force to deal with long-an cipated problems.
Link Layer:
Link-layer protocols are used to send data over the network’s physical layer. it also
determines how the packets are coded and signaled by the devices.
Ethernet
It is a set of technologies and protocols that are used primarily in LANs. it defines the
physical layer and the medium access control for wired ethernet networks.
WiFi
It is a set of LAN protocols and specifies the set of media access control and physical
layer protocols for implemen ng wireless local area networks.
Push-Pull Model — The push-pull model cons tutes data publishers, data consumers,
and data queues.
Publishers and Consumers are not aware of each other.
Publishers publish the message/data and push it into the queue. The consumers,
present on the other side, pull the data out of the queue. Thus, the queue acts as the
buffer for the message when the difference occurs in the rate of push or pull of data
on the side of a publisher and consumer.
Queues help in decoupling the messaging between the producer and consumer.
Queues also act as a buffer which helps in situa ons where there is a mismatch
between the rate at which the producers push the data and consumers pull the data.
Exclusive Pair –
Exclusive Pair is the bi-direc onal model, including full-duplex communica on
between client and server. The connec on is constant and remains open ll the client
sends a request to close the connec on.
The Server has the record of all the connec ons which has been opened.
This is a state-full connec on model and the server is aware of all open connec ons.
WebSocket-based communica on API is fully based on this model.
2. Cloud Compu ng: It provides us the means by which we can access applica ons as
u li es over the internet. Cloud means something which is present in remote
loca ons. With Cloud compu ng, users can access any resources from anywhere like
databases, web servers, storage, any device, and any so ware over the internet.
Characteris cs –
1. Broad network access
2. On-demand self-service
3. Rapid scalability
4. Measured service
5. Pay-per-use
Provides different services, such as –
IaaS (Infrastructure as a service) Infrastructure as a service provides online services
such as physical machines, virtual machines, servers, networking, storage, and data
center space on a pay-per-use basis. Major IaaS providers are Google Compute Engine,
Amazon Web Services, and Microso Azure, etc. Ex: Web Hos ng, Virtual Machine,
etc.
PaaS (Pla orm as a service) Provides a cloud-based environment with a very thing
required to support the complete life cycle of building and delivering West web-based
(cloud) applica ons — without the cost and complexity of buying and managing the
underlying hardware, so ware provisioning, and hos ng. Compu ng pla orms such
as hardware, opera ng systems, libraries, etc. Basically, it provides a pla orm to
develop applica ons. Ex: App Cloud, Google app engine
SaaS (So ware as a service): it is a way of delivering applica ons over the internet as
a service. Instead of installing and maintaining so ware, you simply access it via the
internet, freeing yourself from complex so ware and hardware management. SaaS
Applica ons are some mes called web-based so ware on-demand so ware or hosted
so ware. SaaS applica ons run on a SaaS provider’s service and they manage security
availability and performance. Ex: Google Docs, Gmail, office, etc.
3. Big Data Analy cs: It refers to the method of studying massive volumes of data or
big data. Collec on of data whose volume, velocity, or variety is simply too massive
and tough to store, control, process and examine the data using tradi onal databases.
Big data is gathered from a variety of sources including social network videos, digital
images, sensors, and sales transac on records. Several steps are involved in analyzing
big data –
1. Data cleaning
2. Munging
3. Processing
4. Visualiza on
Examples –
Bank transac ons
Data generated by IoT systems for loca on and tracking of vehicles
E-commerce and in Big-Basket
Health and fitness data generated by IoT systems such as fitness bands
4. Communica ons Protocols: They are the backbone of IoT systems and enable
network connec vity and linking to applica ons. Communica on protocols allow
devices to exchange data over the network. Mul ple protocols o en describe different
aspects of a single communica on. A group of protocols designed to work together is
known as a protocol suite; when implemented in so ware they are a protocol stack.
They are used in
1. Data encoding
2. Addressing schemes
IoT Level-2
It has a single node that performs sensing and/or actua on and local analysis (IoT
Device and collected data).
At this, IoT Level Databases and applica ons establish in Cloud.
It is useful for solu ons where the data involved is big, however, the primary analysis
requirement is not computa onally intensive and can be done locally itself.
IoT Level-3
It has a single node. Database and applica ons established in the cloud.
It is suitable for solu ons where the data involved is big and the analysis requirements
are computa onally intensive.
IoT Level-4
It has mul ple nodes that perform local analysis. It has a Cloud-based applica on and
database. This IoT System contains local and cloud-based observer nodes which can
subscribe to and receive informa on collected in the cloud from IoT node devices.
It is suitable for solu ons where we are using mul ple nodes, the data involved is big
and the analysis requirements are computa onally intensive.
IoT Level-5
It has mul ple end nodes and one coordinator node. The end nodes use for sensing
and/or actua on.
In this model, the Coordinator node collects data from the end nodes and transfers it
to the cloud. In this model, we used a Cloud-based Database for storing and Analyzing
data.
It is suitable for solu ons based on wireless sensor networks, in which the data
involved is big and the analysis requirements are computa onally intensive.
IoT Level-6
It has mul ple independent end nodes that are used for sensing and/or actua on and
transferring data to the cloud. We used a Cloud-based database.
The analy cs component analyzes the data and stores the results in the cloud database
and the results are visualized with the cloud-based applica on.
The centralized controller is aware of the status of all the end nodes and sends control
commands to the nodes
Domain-Specific IoTs:
The Internet of Things (IoT) applica ons span a wide range of domains Home Automa on
Ci es Environment, Energy, Retail, Logis cs, Agriculture, Industry and Health & Lifestyle.
1. Home Automa on IoT
Smart Appliances: IoT-connected appliances such as refrigerators, washing machines,
and ovens can be controlled remotely via smartphone apps.
Home Security: IoT-enabled security systems include smart locks, cameras, and
mo on detectors, which provide real- me alerts and remote access.
Energy Management: Smart thermostats and ligh ng systems adjust se ngs based
on occupancy or me of day, improving energy efficiency.
Home Health Monitoring: Devices like smart beds and air quality monitors track
health metrics and environmental condi ons, enhancing well-being.
2. Smart Ci es IoT
Public Safety: IoT sensors and cameras monitor streets for crimes, accidents, and
other safety issues, providing data to emergency services.
Smart Parking: IoT-based systems direct drivers to available parking spaces, reducing
traffic conges on.
Infrastructure Monitoring: Sensors on bridges and buildings provide data on
structural health, allowing for proac ve maintenance.
Public Transport: IoT devices track buses and trains, providing real- me loca on data
to commuters and op mizing schedules.
3. Environment IoT
Weather Monitoring: IoT sensors collect data on temperature, humidity, and other
weather parameters, aiding in climate studies and disaster preparedness.
Pollu on Control: IoT systems track air and water quality, enabling authori es to take
mely ac ons to reduce pollu on.
Wildlife Monitoring: IoT devices are used to track wildlife movements, aiding
conserva on efforts.
4. Energy IoT
Smart Meters: IoT-enabled meters provide real- me electricity usage data, helping
consumers and u li es manage energy be er.
Renewable Energy Management: IoT systems op mize the genera on and
distribu on of solar and wind energy, integra ng them into the grid.
Energy Storage: IoT devices manage ba ery storage systems, ensuring efficient
energy use during peak and off-peak hours.
5. Retail IoT
Smart Shelves: Shelves equipped with weight sensors track product levels and no fy
staff for restocking.
Personalized Shopping: IoT beacons in stores provide personalized discounts and
product informa on to customers via their smartphones.
Checkout Automa on: IoT systems enable cashier-less checkouts, where sensors and
cameras track what customers take and automa cally bill them.
6. Logis cs IoT
Asset Tracking: IoT devices monitor the loca on and condi on of goods during
transit, ensuring mely deliveries and quality maintenance.
Warehouse Automa on: IoT robots and sensors op mize storage, retrieval, and
inventory management in warehouses.
Supply Chain Transparency: IoT data provides real- me insights into the supply chain,
enhancing efficiency and reducing bo lenecks.
7. Agriculture IoT
Soil Sensors: IoT devices measure soil moisture and nutrient levels, guiding farmers in
irriga on and fer liza on.
Crop Monitoring: Drones and IoT sensors collect data on crop health, helping in early
disease detec on and yield predic on.
Livestock Management: IoT devices monitor the health and loca on of livestock,
improving animal welfare and produc vity.
8. Industry IoT (Industrial IoT or IIoT)
Smart Manufacturing: IoT-enabled machines communicate and coordinate with each
other, op mizing produc on processes.
Quality Control: IoT sensors detect defects in products during manufacturing,
ensuring high-quality output.
Supply Chain Op miza on: IoT data helps in tracking materials and finished goods,
improving supply chain efficiency.
9. Health & Lifestyle IoT
Remote Pa ent Monitoring: IoT devices monitor pa ents’ vital signs and send data to
healthcare providers, enabling remote care.
Wearable Health Devices: Fitness trackers and smartwatches collect data on physical
ac vity, sleep, and heart rate, helping users maintain a healthy lifestyle.
Smart Fitness Equipment: IoT-enabled gym equipment adjusts workouts based on
the user’s performance and health data.
IoT and M2M are o en used inter changeably. Fig. Shows the end-to-end architecture of
M2M systems comprises of M2M area networks, communica on networks and applica on
fomain.
An M2M area network comprises of machines( or M2M nodes) whiach have embedded
network modules for sensing, actua on and communica ng various communic on protocols
can be used for M2M LAN such as ZigBee, Bluetooth, M-bus, Wireless M-Bus etc., These
protocols provide connec vity between M2M nodes within an M2M area network.
The communica on network provides connec vity to remote M2M area networks. The
communica on network provides connec vity to remote M2M area network.
The communica on networkcan use either wired or wireless network(IP based). While the
M2M are networks use either properietorary or non-IP baed communica on protocols, the
communica on network uses IP-based network. Since non-IP based protocols are used
within M2M area network, the M2M nodes within one network cannot communicate with
nodes in an externalnetwork.
To enable the communica on between remote M2M are network, M2M gateways are used.
Fig. Shows a block diagram of an M2M gateway. The communica on between M2M nodes
and the M2M gateway is based on the communica on protocols which are naive to the M2M
are network. M2M gateway performs protocol transla ons to enable Ip-connec vity for M2M
are networks. M2M gateway acts as a proxy performing transla ons from/to na ve protocols
to/from Internet Protocol(IP). With an M2M gateway, each mode in an M2M area network
appears as a virtualized node for external M2M area networks.
Figure shows the SDN Architecture and SDN Layers in which the control and data planes
are decoupled and the network controller is centralized
1) Centralized NetworkController With decoupled control and data planes and centralized
network controller, the network administrators can rapidly configure the network.
• Earlier versions of SNMP did not have strong security features. 18PCSC41-Interner of Things
2020-2021(Even) 13 M.Sc(CS) CS Department- MTNC
NETWORK OPERATOR REQUIREMENTS
Ease of use
• Dis nc on between configura on and state data
• Fetch configura on and state data separately
• Configura on of the network as a whole
• Configura on transac ons across devices
• Configura on deltas
• Dump and restore configura ons
• Configura on valida on
• Configura on database schemas
• Comparing configura ons
• Role-based access control
• Consistency of access control lists:
• Mul ple configura on sets
• Support for both data-oriented
NETCONF
Network Configura on Protocol (NETCONF) is a session-based network management
protocol. NETCONF allows retrieving state or configura on data and manipula ng
configura on data on network devices.
• NETCONF works on SSH transport protocol. Transport layer provides end-to-end connec vity
and ensure reliable delivery of messages.
• NETCONF uses XML-encoded Remote Procedure Calls (RPCs) for framing request and
response messages.
• The RPC layer provides mechanism for encoding of RPC calls and no fica ons.
• NETCONF provides various opera ons to retrieve and edit configura on data from network
devices.
• The Content Layer consists of configura on and state data which is XML-encoded.
• The schema of the configura on and state data is defined in a data modeling language called
YANG.
• NETCONF provides a clear separa on of the configura on and state data.
• The configura on data resides within a NETCONF configura on datastore on the server.
YANG
YANG is a data modeling language used to model configura on and state data manipulated
by the NETCONF protocol
• YANG modules contain the defini ons of the configura on data, state data, RPC calls that
can be issued and the format of the no fica ons.
• YANG modules defines the data exchanged between the NETCONF client and server.
18PCSC41-Interner of Things 2020-2021(Even) 16 M.Sc(CS) CS Department- MTNC
• A module comprises of a number of 'leaf' nodes which are organized into a hierarchical tree
structure. YANG Module Example
• The 'leaf' nodes are specified using the 'leaf' or 'leaf-list' constructs.
• Leaf nodes are organized using 'container' or 'list' constructs.
• A YANG module can import defini ons from other modules.
• Constraints can be defined on the data nodes, e.g. allowed values.
• YANG can model both configura on data and state data using the 'config' statement. This
YANG module is a YANG version of the toaster MIB
• The toaster YANG module begins with the header informa on followed by iden ty
declara ons which define various bread types.
• The leaf nodes (‘toasterManufacturer’ ‘toasterModelNumber’ and oasterStatus’) are
defined in the ‘toaster’ container.
• Each leaf node defini on has a type and op onally a descrip on and default value.
• The module has two RPC defini ons (‘make-toast’ and ‘cancel-toast’).
9) Data Provider API: Applica ons on the IoT device can register for callbacks for various
events using the Data Provider API. Through the Data Provider API, the applica ons can report
sta s cs and opear onaldata.
Steps for IoT device Management with NETCONF-YANG
1) Create a YANG model of the system that defines the configura on and state data of the
system.
2) Complete the YANG model with the ‗Inctool‘ which comes withLibnetconf.
3) Fill in the IoT device mangement code in the TransAPImodule.
4) Build the callbacks C file to generate the libraryfile.
5) Load the YANG module and the TransAPImodule into the Netopeer server using Netopeer
managertool.
6) The operator can now connect from the management system to the Netopeer server using
the NetopeerCLI.
7) Operator can issue NETCONF commands from the Netopeer CLI. Command can be issued
to changew the configura on dsta, get opera onal dat or execute an RPC on the IoTdevice.
Unit V: IoT Physical Devices and Endpoints
IoT Physical Devices and Endpoints:
A "Thing" in Internet of Things (IoT) can be any object that has a unique iden fier and which
can send/receive data (including user data) over a network (e.g., smart phone, smartTV,
computer, refrigerator, car, etc.).
• IoT devices are connected to the Internet and send informa on about themselves or about
their surroundings (e.g. informa on sensed by the connected sensors) over a network (to
other devices or servers/storage) or allow actua on upon the physical en es/environment
around them remotely.
IoT Device Examples
A home automa on device that allows remotely monitoring the status of appliances and
controlling the appliances.
• An industrial machine which sends informa on abouts its opera on and health monitoring
data to a server.
• A car which sends informa on about its loca on to a cloud-based service.
• A wireless-enabled wearable device that measures data about a person such as the
number of steps walked and sends the data to a cloud-based service.
Raspberry Pi:
Introduc on to Raspberry Pi:
Raspberry Pi Raspberry Pi is a low-cost mini-computer with the physical size of a credit card.
Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a normal
desktop computer can do. Raspberry Pi also allows interfacing sensors and actuators through
the general purpose I/O pins.
Since Raspberry Pi runs Linux opera ng system, it supports Python "out of the box".
Raspberry Pi is a low-cost mini-computer with the physical size of a credit card. Raspberry Pi
runs various flavors of Linux and can perform almost all tasks that a normal desktop computer
can do.
Raspberry Pi also allows interfacing sensors and actuators through the general purpose I/O
pins. Since Raspberry Pi runs Linux opera ng system, it supports Python "out of the box".
Processor: ARM-based CPU.
Memory: Varies by model, typically ranging from 512MB to 8GB of RAM.
Connec vity: Includes USB ports, HDMI output, Ethernet, Wi-Fi, and Bluetooth.
GPIO Pins: General-purpose input/output pins for connec ng sensors, actuators, and
other peripherals.
Commands:
sudo nano /boot/config.txt
Add the following lines to enable UART:
enable_uart=1
dtoverlay=pi3-miniuart-bt
Save and reboot the Raspberry Pi.
4. Python Code Example:
o You can use the pyserial library in Python for serial communica on.
Python Code:
import serial
import me
ser = serial.Serial('/dev/serial0', 9600) # Open the serial port
while True:
ser.write(b'Hello World\n') # Send data
me.sleep(1)
Commands:
sudo raspi-config
Navigate to Interfacing Op ons -> SPI and enable it.
o Reboot the Raspberry Pi.
4. Python Code Example:
o Use the spidev library for SPI communica on.
Python Code
import spidev
spi = spidev.SpiDev()
spi.open(0, 0) # Open SPI bus 0, device (CS) 0
def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1] & 3) << 8) + adc[2]
return data
while True:
print(read_adc(0)) # Read from ADC channel 0
try:
while True:
bu on_state = GPIO.input(23)
if bu on_state == GPIO.LOW:
GPIO.output(18, GPIO.HIGH) # Turn on LED
else:
GPIO.output(18, GPIO.LOW) # Turn off LED
me.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup()
2. Controlling Output:
# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
# Set up PWM
pwm = GPIO.PWM(18, 50) # 50Hz frequency
pwm.start(0)
try:
while True:
pwm.ChangeDutyCycle(7.5) # Neutral posi on
me.sleep(1)
pwm.ChangeDutyCycle(12.5) # 180 degrees
me.sleep(1)
pwm.ChangeDutyCycle(2.5) # 0 degrees
me.sleep(1)
except KeyboardInterrupt:
pwm.stop()
GPIO.cleanup()
try:
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
print(f'Temp: {temperature}°C Humidity: {humidity}%')
else:
print('Failed to get reading. Try again!')
me.sleep(2)
except KeyboardInterrupt:
pass