0% found this document useful (0 votes)
14 views36 pages

Introduction to Raspberry Pi 4 Features

The document provides an overview of the Raspberry Pi 4, a low-cost, credit-card-sized computer designed for learning programming and exploring computing. It details the features, requirements, applications, and comparisons with Arduino, emphasizing the capabilities of Raspberry Pi in various fields such as IoT, robotics, and media usage. Additionally, it explains the differences between microcontrollers and microprocessors, highlighting the architecture and functionalities of each.

Uploaded by

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

Introduction to Raspberry Pi 4 Features

The document provides an overview of the Raspberry Pi 4, a low-cost, credit-card-sized computer designed for learning programming and exploring computing. It details the features, requirements, applications, and comparisons with Arduino, emphasizing the capabilities of Raspberry Pi in various fields such as IoT, robotics, and media usage. Additionally, it explains the differences between microcontrollers and microprocessors, highlighting the architecture and functionalities of each.

Uploaded by

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

Raspberry Pi 4

The Raspberry Pi is a low cost, credit-card sized computer that plugs into a
computer monitor or TV, and uses a standard keyboard and mouse. It is a capable
little device that enables people of all ages to explore computing, and to learn how
to program in languages like Scratch and Python.

Course
Instructor: Engr. Salman Bashir
A Brief Introduction To

Raspberry Pi 4 Computer
Model B

Introduction

The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer
monitor or TV, and uses a standard keyboard and mouse. It is a capable little device
that enables people of all ages to explore computing, and to learn how to
program in languages like Scratch and Python. Raspberry Pi is popularly used for
real time Image/Video Processing, IoT based applications and Robotics
[Link] Pi is slower than laptop or desktop but is still a computer
which can provide all the expected features or abilities, at a low power consumption.
Raspberry Pi Foundation officially provides Debian based Raspbian OS. Also, they
provide NOOBS OS for Raspberry Pi. We can install several Third-Party versions of
OS like Ubuntu, Arch linux, RISC OS, Windows 10 IOT Core, etc.

Raspbian OS is official Operating System available for free to use. This OS is


efficiently optimized to use with Raspberry Pi. Raspbian have GUI which includes
tools for Browsing, Python programming, office, games, etc.

Features
 Broadcom BCM2711, Quad core Cortex-A72 (ARM v8) 64-bit SoC @ 1.5GHz
 2GB, 4GB or 8GB LPDDR4-3200 SDRAM (depending on model)
 2.4 GHz and 5.0 GHz IEEE 802.11ac wireless, Bluetooth 5.0, BLE
 Gigabit Ethernet
 2 USB 3.0 ports; 2 USB 2.0 ports.
 Raspberry Pi standard 40 pin GPIO header (fully backwards compatible with
previous boards)
 2 × micro-HDMI ports (up to 4kp60 supported)
 2-lane MIPI DSI display port
 2-lane MIPI CSI camera port
 4-pole stereo audio and composite video port
 H.265 (4kp60 decode), H264 (1080p60 decode, 1080p30 encode)
 OpenGL ES 3.1, Vulkan 1.0
 Micro-SD card slot for loading operating system and data storage
 5V DC via USB-C connector (minimum 3A*)
 5V DC via GPIO header (minimum 3A*)
 Power over Ethernet (PoE) enabled (requires separate PoE HAT)
 Operating temperature: 0 – 50 degrees C ambient
Things Required to RUN Raspberry Pi
 A 15W USB-C power supply – we recommend the official Raspberry Pi USB-
C Power Supply
 Micro SD card with Raspberry Pi OS installed (buy a pre-loaded SD card
along with your Raspberry Pi, or install Raspberry Pi OS using Raspberry Pi
imager)
 A keyboard and mouse
 Cables to connect to one or two displays via Raspberry Pi 4's micro HDMI
ports

Sr No. Required Things


1 Raspberry Pi Model B
2 USB Type-C 5v Power Supply
3 16 GB SanDisk SD Card with card Reader
4 HDMI Cable
5 LCD Screen
6 Keyboard
7 Mouse

Applications
With Raspberry Pi we can do anything from advance tasks to common ones.

 Desktop PC. Using Raspberry Pi, the microSD card, and a power supply, a
simple desktop can be made. ...
 Wireless print server. ...
 Media Usage. ...
 Game Servers. ...
 Retro Gaming Machine. ...
 Robot Controller. ...
 Stop Motion Camera. ...
 Artificial Intelligence based Robotic Car
 Home Automation
 Self-Driving Cars
 Facial Recognition Robot
 Smart Hub
 Advance Agricultural Robot
And so many other tasks which requires computers and are complex.
Arduino

Introduction
Arduino was developed by Massimo Banzi Et Al. in Ivrea, Italy. Arduino is a simple
electronics prototyping tool with open-source hardware and software. Arduino is
essentially a Microcontroller development board using which you can Blink LEDs,
accept inputs from Buttons, read data from Sensors, control Motors and many other
“Microcontroller” related tasks.
The most popular Arduino board is the Arduino UNO, which is based on
ATmega328P Microcontroller from Atmel (now Microchip). Coming to the software
side of Arduino, all Arduino boards can be programmed in C and C++ programming
languages using a special software called Arduino IDE. The Arduino IDE consists of
all the toolchains for editing source code, compiling and programming the
Microcontroller on the Arduino board.

Features
The Arduino Uno R3 board includes the following specifications.
 It is an ATmega328P based Microcontroller
 The Operating Voltage of the Arduino is 5V
 The recommended input voltage ranges from 7V to 12V
 The i/p voltage (limit) is 6V to 20V
 Digital input and output pins-14
 Digital input & output pins (PWM)-6
 Analog i/p pins are 6
 DC Current for each I/O Pin is 20 mA
 DC Current used for 3.3V Pin is 50 mA
 Flash Memory -32 KB, and 0.5 KB memory is used by the boot loader
 SRAM is 2 KB
 EEPROM is 1 KB
 The speed of the CLK is 16 MHz
 In Built LED
Arduino Uno R3 Programming
 The programming of an Arduino Uno R3 can be done using IDE software. The
microcontroller on the board will come with pre-burned by a boot loader that
permits to upload fresh code without using an exterior hardware programmer.
 The communication of this can be done using a protocol like STK500.
 We can also upload the program in the microcontroller by avoiding the boot
loader using the header like the In-Circuit Serial Programming.
 Program is written in Arduino IDE which is also open source.
 Program is written in basic C# language.

Applications of Arduino Uno ATmega328


The applications of Arduino Uno include the following.
 Arduino Uno is used in Do-it-Yourself projects prototyping.
 In developing projects based on code-based control
 Development of Automation System
 Designing of basic circuit designs.
 Smart Projects
 Line Following Robots
 Basic Robotic Arms
And other basic to intermediate level of projects. But conjugate of Arduino with
Raspberry Pi can open new doors of advancement.
Difference between Raspberry Pi and Arduino
[Link]. Arduino Raspberry Pi
1. Control unit of Arduino is from Atmega While control unit of Raspberry Pi is from ARM family.
family.
2. Arduino is based on a microcontroller. While Raspberry Pi is based on a microprocessor.

3. It is designed to control the electrical While Raspberry Pi computes data and produces
components connected to the circuit valuable outputs, and controls components in a
board in a system. system based on the outcome of its computation.
4. Arduino boards have a simple While Raspberry Pi boards have a complex
hardware and software structure. architecture of hardware and software.
5. CPU architecture: 8 bit. CPU architecture: 64 bit.
6. It uses very less RAM, 2 kB. While Raspberry Pi requires more RAM, 1,2,4,8 GB.

7. It clocks a processing speed of 16 While Raspberry Pi clocks a processing speed of 1.4


MHz. GHz.
8. It is cheaper in cost. While Raspberry Pi is expensive.
9. It has a higher I/O current drive While Raspberry Pi has a lower I/O current drive
strength. strength.
10. It consumes about 200 MW of power. While it consumes about 700 MW of power.

Microcontrollers and Processors


Before doing anything let’s first understand these two terms and get a basic concept
of them so that we can work with them and know the use of them in real-life based
applications.
Micro-Controllers
A microcontroller is an electronic device belonging to the microcomputer family.
These are fabricated using the VLSI technology on a single chip. There are
microcontrollers available in the present market with different word length starting
from 4 bit, 8 bit, 64 bit to 128 bit.
In a broader sense, the components which constitute a microcontroller are the
memory, peripherals and most crucially a processor. Microcontrollers are present in
devices where the user has to exert a degree of control. They are designed and
implemented to execute a specific function such as displaying integers or characters
on an LCD display module of a home appliance. Application of microcontrollers is
myriad. In simpler terms, any gadget or equipment which has to deal with the
functions such as measuring, controlling, displaying and calculating the values
consist of a microcontroller chip inside it. They are present in almost all the present
day home appliances, toys, traffic lights, office instruments and various day-to-day
appliances.
Microcontroller Architecture

The most important part of a microcontroller is a central processing unit with a word
length ranging from 4-bit to 64-bit and in some modern microcontrollers the word
length goes even beyond the limit of 64-bit. A timer is one other constituent of a
microcontroller. There is a watchdog timer. Memory spaces such as RAM, ROM,
EEPROM, EPROM are there to store data and programs. For data storage, volatile
memory RAM is used while for the program and operating parameter storage ROM
and other memory spaces are used.
CPU: Being regarded as the brain of the microcontroller, central processing unit
fetches, decodes and executes the instructions. It coordinates various activities
taking place in the microcontroller.

I/O ports: There are several parallel input/output ports in a microcontroller. They are
used to interface various peripherals such as printers, external memories, LEDs and
LCDs to the microcontroller. Apart from parallel ports, there are serial ports to
interface serially connected peripherals with the microcontroller.
Memory: As in the case of a microprocessor, a microcontroller has spaces for
memories such as RAM, ROM including EEROM and EPROM. It also allocates a
certain amount of flash memory to store program source code.
Timers and counters: These are the fascinating constituent parts of a
microcontroller. Timers and counters are used in operations which include modulation,
clock functions, frequency generation and measuring and pulse generation.
Analog to digital converters (ADCs): Such converters are useful while converting
the output of a sensor which would be in analog form.
Digital to analog converter (DAC): The working of a DAC is just the reverse of an
analog to digital converter. As it is obvious, the output will be an analog signal which
can be used to control the analog peripherals such a motor.

Features of a Microcontroller
 The main advantage of a CISC (complex instruction set computer)
architecture, with which the modern microcontrollers are built, is the macro-
type instructions. A macro instruction can be used in a program replacing a
number of instructions.
 Latest microcontrollers are operated at lesser power consumption. Usually,
they can support a working voltage of 1.8-5.5 V.
 Advanced memory is another feature of a microcontroller. Use of ROM
memories like EEPROM and EPROM (flash memory) make it more reliable
and user-friendly. While EEPROM is a relatively slow memory, EPROM is
faster. Fact that it allows more erase/write cycles also makes it more usable.

Advantages
The main advantage of a microcontroller is that the low cost with all the integral parts
mounted together on a single chip. The design makes it more compact and easy to
use. The easiness of using a microcontroller and the relatively easy maintenance
process also make it more reliable. Almost all the pins in a microcontroller are
programmable and it makes the microcontroller a lot user-friendly. Simplicity while
interfacing ROM, RAM, and I/O ports. Easiness of troubleshooting and a minimal
time requirement for various operations are other crucial advantages.

Disadvantages
Since it contains all the components on a single chip, microcontrollers are having
relatively complex architecture. Microcontrollers are not suitable to interface high
power devices directly and they can only perform the limited number of operations
simultaneously.

Micro-Processors
Computer's Central Processing Unit (CPU) built on a single Integrated Circuit
(IC) is called a microprocessor. A digital computer with one microprocessor which
acts as a CPU is called microcomputer. It is a programmable, multipurpose, clock -
driven, register-based electronic device that reads binary instructions from a storage
device called memory, accepts binary data as input and processes data according to
those instructions and provides results as output. The microprocessor contains
millions of tiny components like transistors, registers, and diodes that work together.

Block Diagram of a Microprocessor

A microprocessor consists of an ALU, control unit and register array.


Where ALU performs arithmetic and logical operations on the data received from an
input device or memory. Control unit controls the instructions and flow of data within
the computer. And, register array consists of registers identified by letters like B, C,
D, E, H, L, and accumulator.

Basic Terms used in Microprocessor

Here is a list of some basic terms used in microprocessor:

Instruction Set - The group of commands that the microprocessor can understand is
called Instruction set. It is an interface between hardware and software.

Bus - Set of conductors intended to transmit data, address or control information to


different elements in a microprocessor. A microprocessor will have three types of
buses, i.e., data bus, address bus, and control bus.

IPC (Instructions Per Cycle) - It is a measure of how many instructions a CPU is


capable of executing in a single clock.

Clock Speed - It is the number of operations per second the processor can perform.
It can be expressed in megahertz (MHz) or gigahertz (GHz). It is also called the
Clock Rate.
Bandwidth - The number of bits processed in a single instruction is called Bandwidth.

Word Length - The number of bits the processor can process at a time is called the
word length of the processor. 8-bit Microprocessor may process 8 -bit data at a time.
The range of word length is from 4 bits to 64 bits depending upon the type of the
microcomputer.

Data Types - The microprocessor supports multiple data type formats like binary,
ASCII, signed and unsigned numbers.

Features of Microprocessor

 Low Cost - Due to integrated circuit technology microprocessors are


available at very low cost. It will reduce the cost of a computer system.
 High Speed - Due to the technology involved in it, the microprocessor
can work at very high speed. It can execute millions of instructions per
second.
 Small Size - A microprocessor is fabricated in a very less footprint due to
very large scale and ultra large scale integration technology. Because of
this, the size of the computer system is reduced.
 Versatile - The same chip can be used for several applications, therefore,
microprocessors are versatile.
 Low Power Consumption - Microprocessors are using metal oxide
semiconductor technology, which consumes less power.
 Less Heat Generation - Microprocessors uses semiconductor technology
which will not emit much heat as compared to vacuum tube devices.
 Reliable - Since microprocessors use semiconductor technology,
therefore, the failure rate is very less. Hence it is very reliable.
 Portable - Due to the small size and low power consumption
microprocessors are portable.

Comparison between Microprocessor and Microcontroller


Starting with Raspberry Pi
As we know raspberry pi is a Computer which means like any other computers it also
needs Operating System (OS). But unlike other computers it does not run Window
operating system is which is widely use and is easier to use Operating system.
It is Linux based and hence has its own OS which is known as Raspbian. But other
than raspbian we can install third parties OS like Ubuntu and kali Linux.
Raspbian
Raspbian is a free operating system based on Debian optimized for the Raspberry Pi
hardware. An operating system is the set of basic programs and utilities that make
your Raspberry Pi run. However, Raspbian provides more than a pure OS: it comes
with over 35,000 packages, pre-compiled software bundled in a nice format for easy
installation on your Raspberry Pi.

The initial build of over 35,000 Raspbian packages, optimized for best performance
on the Raspberry Pi, was completed in June of 2012. However, Raspbian is still
under active development with an emphasis on improving the stability and
performance of as many Debian packages as possible.

Installation of Raspbian
Raspberry Pi OS or previously known as Raspbian can be installed on SD card with
so many methods. The basic and easy to use method is to use Balena Etcher.
Things Required
 Balena Etcher (Can be downloaded from official website)
 Raspberry Pi OS(Can be downloaded from official website)
 SD card module with Card Reader

Steps to Install OS
 The first step is to install Balena Etcher after downloading it.
 Open The Application ( It’s basic User Interface can be seen in figure 1)
 Click on Flash from File Button and navigate to the folder where Raspberry Pi
OS is downloaded. Select that file and open it.
 Next Select the folder (SD CARD) usually it is F:\ Drive But it can vary from
Computer to computer.
 Then at last click on Flash Button and it will start Flashing the OS onto the
SD-card.
Step 1

(Figure 1) Interface of Balena Etcher

Step 2 >> Selecting OS File

(Figure 2)
Step 3 >> Selecting Target Folder (In this case our SD
card is localized as F:\ Drive)

(Figure 3)

Step 4 >> The interface after clicking on Flash button


( Flashing)

(Figure 4)
Setting Up Raspberry Pi for the First Use
After our SD card is loaded with OS now we can power up the Raspberry pi.
For Powering up Raspberry Pi we can use 5v Type C power Adapter.
Then we can use HDMI cable to connect monitor with our Raspberry Pi. If you don’t
have the HDMI support on your LCD or monitor then you can buy a cheap HDMI
Adapter for LCD.
Now Plug that OS loaded SD card into the Raspberry Pi and power up everything.
These are the screen which can be seen after powering up Raspberry Pi.

First Time Boot


 Insert SD card into the Raspberry Pi
 Connect Mouse and Keyboard to the Raspberry Pi
 Connect LCD Screen
 And Power Up the Raspberry pi with Power Adapter
 Wait for few Seconds during this duration Simple Boot setup may appear but
you don’t have to do anything. It is similar to the boot up system of window
just the difference of Interface.
 After few seconds Desktop Interface will appear with configuration window.
Configurations are of resolution settings which will be automatically done. If
none then you can do it manually by just clicking on Next Button.

Desktop Interface with Configuration Wizrad

Getting Started With the First Project


In the world of Electronics and Computers the first project for every new comer is to
say or write ‘Hello World!’ If you are familiar with python then you can already guess
what it can be. But wait, Raspberry pi is hardware with General Purpose I/O pins
then why don’t we just blink a Led with them, so alright we will do that.
Blinking Led
Blinking Led is considered as ‘Hello World’ in field of electronics so let’s do that.
What you’ll need for this guide
We will need the following tools to complete the project:
 Raspberry Pi 4 setup with monitor and USB Mouse & Keyboard
 Solderless breadboard
 Jumper wires for easy hookup
 Resistor pack(Between 100 – 200 OHM)
 Red LED

Setting up Circuit
 Place Led on the breadboard
 The longer leg is the positive and the shorter one is negative side of led.
 Connect the resistor with the anode or the large leg of Led.
 Now connect both of connections to the pins of raspberry pi using jumper
wires.
 The shorter leg is negative and it will be connected to GND pin of
raspberry pi.
 The resistors other leg will be connected to GPIO pin 8.

Circuit Diagram

Pin Designation and Configuration in Raspberry Pi 4

By using following Figure you can map the pins provided on Raspberry pi Computer,
and can use those pins for your projects.

The Pins marked in Yellow Color are Input/output Purpose.


The Pins marked in Black Color are Ground pins.

The Pins marked in off-Yellow Color are for 3.3v because some modules use logic 3
voltage supply.

The Pins marked in Red Color are for 5v power supply.

Writing Software
As our Circuit is complete, so now we can move to the software part or the program
to instruct the Raspberry pi.

On Raspberry Pi, there are two options available one is to write program using
Python Programming language and other is to use Scratch. Before digging deep let’s
get familiar with both of them.

What is Scratch?
Scratch is a visual programming language. It can be accessed as a free desktop and
online multimedia authoring tool that can be used by students, scholars, teachers,
and parents to easily create games and provide a stepping stone to the more
advanced world of computer programming. It can also be used for a range of
educational and entertainment constructionist purposes from math and science
projects, including simulations and visualizations of experiments, recording lectures
with animated presentations, to social sciences animated stories, and interactive art
and [Link] addition, a new version, “Scratch 2.0”, was released in May 2013. This
new version was a web application, eliminating the need to download any software.
Scratch was initiative to teach students about programing or more precisely using
Visual programming. Scratch is very easy to use. All you have to do is to join the
blocks like you do in Jigsaw Puzzles. Everything is provided and you have to join
piece by piece to shape your program or sketch.
Scratch Example

What is Python?
Python is an interpreted high-level general-purpose programming language. Its
design philosophy emphasizes code readability with its use of significant indentation.
Its language constructs as well as its object-oriented approach aim to
help programmers write clear, logical code for small and large-scale projects.
Python is dynamically-typed and garbage-collected. It supports multiple programming
paradigms, including structured (particularly, procedural), object-oriented
and functional programming. It is often described as a "batteries included" language
due to its comprehensive standard library.
Guido van Rossum began working on Python in the late 1980s, as a successor to
the ABC programming language, and first released it in 1991 as Python
0.9.0. Python 2.0 was released in 2000 and introduced new features, such as list
comprehensions and a garbage collection system using reference counting.
Python 3.0 was released in 2008 and was a major revision of the language that is not
completely backward-compatible. Python 2 was discontinued with version 2.7.18 in
2020. Currently newer version 2.9 is also available now. It has sa many more
features and offers less bugs as compared to previous builds.
Python consistently ranks as one of the most popular programming languages.

Libraries
Libraries in programming languages are collections of prewritten code that users
can use to optimize tasks. Take libraries as actual library which contains
thousands of pre-arranged books. If we need any information we will simply go to
library and pick a book form shelf and will collect the data we were looking for. If
there would be no libraries and all we had were just a pile of books without any
arrangement then of course we would have to sort them out first and it looks
frustrating. For similar purpose libraries are written. Libraries are written by
developers for specific tasks. Libraries make work easier actually lot easier. And
also our main file on which we are working remains simple and contains fewer
lines when we import libraries for our work in that file otherwise it would cost us
time and more hard work and more lines which simply leads to less efficient code
and more bugs. Well simply Library in any programming language plays an
important role. As we got familiar with libraries and their importance so we can move
forward.

Libraries in Python
Python is often described as a "batteries included" language due to its
comprehensive standard library. There are so many libraries available for python
which we can implement in our projects. Some of the famous libraries are as follows:
NumPy
Primary Language: Python
Use: NumPy is a library used to make powerful arrays. For machine learning,
NumPy divides the data and manipulates it easily.

Meaning, machine learning uses many operations on arrays of data. These data
sets often contain thousands of numbers and to iterate through every single value
one at a time would be difficult and lengthy. NumPy simplifies all of this!

Matplotlib
Primary Language: Python

Use: Going off of the above, Matplotlib is used with NumPy to help with datasets.
Specifically, Matplotlib handles large datasets and comes complete with standard
graphing functions. It’s also useful for visualizing values over time.

Basically, Matplotlib is great for plotting and works hand-in-hand with NumPy.

TensorFlow
Primary Language: Python or C++

Use: TensorFlow is a library developed by Google to facilitate the creation and


training of machine learning models and neural networks. It can be used to create
and train machine learning models.

Keras
Primary Language: Python

Use: Keras is also a library developed to facilitate the creation and training of
machine learning models and neural networks. But going off the above, Keras
was introduced to simplify TensorFlow. This library can make machine learning
significantly easier and it still uses TensorFlow as a backend.

Pillow
Primary Language: Python

Use: In Python, you can use the Pillow library to create bitmap images.

SFML
Primary Language: C++

Use: The Simple and Fast Multimedia Library (SFML) is a library that allows for
the creation of images, generation of sound effects, and even connecting of
multiple computers!

p5
Primary Language: JavaScript

Use: [Link] is one of the most well-known JavaScript libraries with tons of built-in
code.

p5 play
Primary Language: JavaScript

[Link] is a p5 library for easily adding collisions, animations, and various other
features dealing with sprites.

IDE (Integrated Development Environment)


An integrated development environment (IDE) is software for building applications
that combines common developer tools into a single graphical user interface (GUI).
An IDE allows developers to start programming new applications quickly because
multiple utilities don’t need to be manually configured and integrated as part of the
setup process. Developers also don’t need to spend hours individually learning how
to use different tools when every utility is represented in the same workbench. This
can be especially useful for on-boarding new developers who can rely on an IDE to
get up to speed on a team’s standard tools and workflows. In fact, most features of
IDEs are meant to save time, like intelligent code completion and automated code
generation, which removes the need to type out full character sequences.

IDEs for Python


1. IDLE
2. PYCHARM
3. ATOM
4. ECLIPSE
5. SUBIME TEXT
6. THONNY
7. SPYDER

Uses of Python
 Python can be used on a server to create web applications.
 Python can be used in Artificial Intelligence.
 Python can be used to automate simple and boring tasks.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Python as compared to other languages


 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.
Reason to choose Python
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a
functional way.

Example

Hello World Program.

print(“Hello World!”)

See it’s just a simple easy-to read single line which will print Hello World on screen.

Now as we got familiar with python so let’s use this language for our project
using raspberry Pi.

Python in Raspberry Pi

The Raspbian OS comes with pre-installed Python 2 and 3and also IDE.
There are two types of Python IDEs pre installed on Raspbian. The first one is simple
interpreter and the second is Thonny.
So to get started all you have to do is to follow the following instruction:
So go ahead and load it up by clicking on the Left corner Pi icon -> Programming ->
Thonny Python IDE/ mu (You can use any of these IDEs by clicking on them)
Before starting to write our program we have to install GPIO Library for raspberry pi
so that we can use our gpio pins.
To install the Python library open a terminal and execute the following

$ sudo apt-get install [Link] [Link]

Now go to any of the IDE you want to use. The best and recommended is to use
Thonny IDE.

Now we have to write our code. Before writing code we have to know what we want
to do,

We need to do the following:

 Initialize the GPIO ports


 Turn the LED on and off in 1 second intervals

To initialize the GPIO ports on the Raspberry Pi we need to first import the Python
library, then initialize the library and setup pin 8(or any pin designated for Input/output
purpose) as an output pin.

So now we have a sketch in our mind that what we want to do, so let’s make it real.

import [Link] as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
[Link](False) # Ignore warning for now
[Link]([Link]) # Use physical pin numbering
[Link](8, [Link], initial=[Link]) # Set pin 8 to be an output pin and
set initial value to low (off)

As we have imported and initialized our library in addition to time library now, Next we
need to turn the LED on and off in 1 second intervals by setting the output pin to
either high (on) or low (off). We do this inside a infinite loop so our program keep
executing until we manually stop it. For infinite loop we use while loop but if we want
to loop our code for counted numbers then we use for loop.

while True: # Run forever


[Link](8, [Link]) # Turn on
sleep(1) # Sleep for 1 second
[Link](8, [Link]) # Turn off
sleep(1) # Sleep for 1 second

After combining both codes it will look something like this:

import [Link] as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module
[Link](False) # Ignore warning for now
[Link]([Link]) # Use physical pin numbering
[Link](8, [Link], initial=[Link]) # Set pin 8 to be an output pin and
set initial value to low (off)
while True: # Run forever
[Link](8, [Link]) # Turn on
sleep(1) # Sleep for 1 second
[Link](8, [Link]) # Turn off
sleep(1) # Sleep for 1 second

With our program finished, save it as blinking_led.py and run it either inside your IDE
or in the console with:

$ python blinking_led.py

After Running, this code and our circuit all setup, we will see our led blinking on and
off with delay of One second.

Second Project

Overview
Interfacing L298N Motor Driver Module with Raspberry Pi will allow us to
control a DC Motor (in fact, you can control two DC Motors).

When I say control a DC Motor, I mean you can start a motor, stop it, make it rotate in
forward direction, backward directions, increase the speed of rotation and also
decrease the speed.

For this, I’ll be using the L298N Motor Driver Module. If you remember, I have already
made a project on CONTROLLING A DC MOTOR WITH RASPBERRY PI using
L293D Motor Driver.

How different will it be for controlling a DC Motor using Raspberry Pi with L293D and
L298N? Well, there won’t be much of a difference as essentially both these modules
serve the same purpose.

But it is always nice to learn about something new and implement it into a project. So,
first, let me take you through a simple introduction to L298N Motor Driver Module.

L298N Motor Driver Module


In recent times, L298N Motor Driver Module has become the favorite choice of
hobbyists and makers when it comes to DC Motor Control. It became so popular that
the module is now available at a very low cost.
The L298N Motor Driver Module is based on the powerful L298N Motor Driver IC.
The pin diagram of the L298N Motor Driver IC is shown in the image below. This IC,
along with few other extra components make up the L298N Motor Driver Module.
The above image shows the L298N Motor Driver Module with names of all the
components on it. To name a few, it contains screw terminals for connecting motors
and power supply, male headers for connecting different pins like enable, IN1, IN2
etc.

NOTE:

 There is jumper near the power supply terminals of the L298N Motor Driver
Module. If it is connected, it will enable the on-board 5V regulator, which
supplies +5V logic supply for L298N IC.
 This must be used only if the supply voltage is less than or equal to +12V. If it
is more than +12V, then disconnect the jumper to disable the regulator.

Circuit Diagram of Raspberry Pi L298N Interface


The following image shows the circuit diagram of the Raspberry Pi L298N Motor
Driver Module Interface. The circuit diagram is made with the help of Fritzing App.

Components Required
 Raspberry Pi
 L298N Motor Driver Module
 12V DC Motor
 12V Power Supply for Motor and Motor Driver
 Power Supply for Raspberry Pi
 Connecting Wires

Circuit Design
The design of the Raspberry Pi L298N Motor Driver Interface Circuit is
very simple. First connect 12V Power Supply to L298N Motor Driver
Module. Then, make the GND terminals of Raspberry Pi and L298N Motor
Driver Module common (connect them together).

Now, since we are controlling a single DC Motor, we need to use a single


channel of the L298N. In order to do that, connect the ENA pin of L298N to
Physical Pin 22 (GPIO25) of Raspberry Pi.

Coming to the Inputs of the Motor, connect the IN1 and IN2 of L298N
Module to Physical Pins 16 and 18 (GPIO23 and GPIO24). That’s it. The
rest of the job is done by the Python Script.

Code
The Python Script for Interfacing L298N Motor Driver Module with
Raspberry Pi is given below. We will see the explanation of the code in the
Working Section.

import [Link] as GPIO # Import Raspberry Pi GPIO library


from time import sleep # Import the sleep function from the time module

in1 = 24
in2 = 23
en = 25
temp1=1

[Link]([Link]) # choose BCM or BOARD


[Link](in1,[Link]) # Set to be an output pin
[Link](in2,[Link])
[Link](en,[Link])
[Link](in1,[Link]) # Set pin 24 to be an output pin and set initial value to low (off)
[Link](in2,[Link]) # Set pin 23 to be an output pin and set initial value to low (off)

p=[Link](en,1000) # Set pin 25 to be an output pin


[Link](25)
print("\n")
print("The default speed & direction of motor is LOW & Forward.....")
print("r-run s-stop f-forward b-backward l-low m-medium h-high e-exit")
print("\n")

while(1):
x=input()

if x=='r': # r--run (to run or start the motor)


print("run")
if(temp1==1):
[Link](in1,[Link])# Set pin 24 to be an output pin and set initial value to high (ON)
[Link](in2,[Link]) # Set pin 23 to be an output pin and set initial value to low (off)
print("forward")
x='z'
else:
[Link](in1,[Link])
[Link](in2,[Link])
print("backward")
x='z'

elif x=='s': # s--stop(to stop the motor)

print("stop")
[Link](in1,[Link])
[Link](in2,[Link])
x='z'

elif x=='f': # f-- forward (to run the motor in forward direction
print("forward")
[Link](in1,[Link])
[Link](in2,[Link])
temp1=1
x='z'

elif x=='b': # b-- backward (to run the motor in backward direction
print("backward")
[Link](in1,[Link]))
[Link](in2,[Link])
temp1=0
x='z'

elif x=='l': # I-- low (to decrease the speed to 25%)


print("low")
[Link](25)
x='z'

elif x=='m': # m--medium (to run the motor at medium speed 50%)
print("medium")
[Link](50)
x='z'

elif x=='h': # h--high (to increase the speed to 75% level)


print("high")
[Link](75)
x='z'

elif x=='e': # e--exit (to stop the motor and exit Python)
[Link]()
break

else:
print("<<< wrong data >>>")
print("please enter the defined data to continue.....")

Working of the Project


If you take a look at the code carefully, you can easily understand the working of the
project. After creating the Python Script with the above code, run the script.

You will get a message regarding the default speed and direction of the Motor. This is
followed by a list of commands you must use to control the motor. These commands
are given below.

 r – run (to run or start the motor)


 s – stop (to stop the motor)
 f – forward (to run the motor in forward direction) – default direction
 b – backward (to reverse the direction of rotation)
 l – low (to decrease the speed to 25%) – default speed
 m – medium (to run the motor at medium speed 50%)
 h – high (to increase the speed to 75% level)
 e – exit (to stop the motor and exit Python)

Third Project

Overview
If you remember the previous Raspberry Pi Tutorials, we have seen HOW TO
CONTROL A DC MOTOR USING RASPBERRY PI and also HOW TO CONTROL A
SERVO MOTOR USING RASPBERRY PI.

Stepper Motors can be categorized between Servo Motors and DC Motors as you
can control the angular position of the shaft as well as rotate the shaft freely in either
direction.
I have already discussed about stepper motors, types of stepper motors, internal
structure of a stepper motor and also how to design a stepper motor control circuit
in STEPPER MOTOR CONTROL USING ARDUINO project.

So, I suggest you to refer to that project once before continuing with the Raspberry Pi
Stepper Motor Interface.

Driving a Stepper Motor


It is important for you to identify your stepper motor i.e. whether it is a Unipolar
Stepper Motor or a Bipolar Stepper Motor. Because, the driving techniques for each
of these motor is different.

In this project, I’ll be using a simple 12V Bipolar Stepper Motor. To drive this Stepper
Motor, we need a motor driver module like L293D or L298N. Both these module work
great with the 12V Stepper Motor. So, choosing the driver module is up to you. For
this project, I have chosen the L298N Motor Driver Module.

The main advantage of a Stepper Motor over a Servo Motor is that complete rotation
of the motor’s shaft is divided into steps and you can precisely position the Stepper
Motor by carefully energizing the Motor Coils.
Even though there is no feedback mechanism like in a Servo Motor, a Stepper Motor
with smaller step angles can provide very accurate angular positioning.

Typically, almost all commercially available Stepper Motors comes with a step angle
of 1.80. So, for a complete 3600 degree rotation, it will have a step count of 200.

In order to increase the accuracy of the Stepper Motor i.e. to achieve a bit more
precise angular positioning of the shaft, you can use a technique called “Half
Stepping”.

Half Stepping is a technique where instead of energizing a single phase at a time, we


will be use a combination of one phase and two phase energizing. With this
technique, you can achieve even smaller resolution of 400 steps and a smoother
operation.

Raspberry Pi Stepper Motor Interface


Almost all advanced CNC Machines and Industrial Pick-n-Place Robots use
Stepper Motors in them. Raspberry Pi on the other hand is a tiny computer that is
being used in a wide range of applications like Robotics, Home Automation, Industrial
Automation an many other.
So, interfacing a Stepper Motor with Raspberry Pi will be interesting as you can
implement this interface in all the above mentioned applications.

A 12V Bipolar Stepper Motor draws about 350mA to 500mA of current. Hence, we
need a dedicated driver circuit while working on the Raspberry Pi Stepper Motor
Interface.

Since I have used a Bipolar Stepper Motor, I only need four control wires. This can
be done with the help of many different modules or drivers like L293D, ULN2003 or
L298N.

In case of a Unipolar Stepper Motor, there are multiple ways you can wire it to the
Driver Module. Typically, a Unipolar Stepper Motor will have either 5 or 6 wires. So,
you need to use ULN2003 or wire it a Bipolar Stepper Motor.

Circuit Diagram
The following image shows the connection diagram of the Raspberry Pi
Stepper Motor Control using L298N. It is implemented using Fritzing Application.
Components Required
 Raspberry Pi 3 Model B
 12V Bipolar Stepper Motor
 L298N Motor Driver Module
 12V Motor Power Supply
 Power Supply for Raspberry Pi
 Connecting Wires
 Computer

Circuit Design
The inputs to the Motor Driver Module i.e. IN1, IN2, IN3 and IN4 are
connected to the Physical Pins 11, 12, 13 and 15 i.e. GPIO17, GPIO18, GPIO27 and
GPIO22 of the Raspberry Pi.

One set of the Motor Coils are connected to OUT1 and OUT2 of the Motor Driver and
the other set is connected to OUT3 and OUT4.

A 12V external power supply is given to the Motor Driver Module and the ground
terminals of the L298N Motor Driver Module and the Raspberry Pi are made common.

A separate 5V supply is given to the Raspberry Pi.

Code
The programming part of the project is implemented using Python. The Python
script for Controlling a Stepper Motor using Raspberry Pi and L298N Motor Driver
Module is given below.

import [Link] as GPIO


import time

out1 = 13
out2 = 11
out3 = 15
out4 = 12

i=0
positive=0
negative=0
y=0

[Link]([Link])
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
print "First calibrate by giving some +ve and -ve values....."

try:
while(1):
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
x = input()
if x>0 and x<=400:
for y in range(x,0,-1):
if negative==1:
if i==7:
i=0
else:
i=i+1
y=y+2
negative=0
positive=1
#print((x+1)-y)
if i==0:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==1:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==2:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==3:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==4:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==5:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==6:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==7:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
if i==7:
i=0
continue
i=i+1

elif x<0 and x>=-400:


x=x*-1
for y in range(x,0,-1):
if positive==1:
if i==0:
i=7
else:
i=i-1
y=y+3
positive=0
negative=1
#print((x+1)-y)
if i==0:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==1:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==2:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==3:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==4:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==5:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==6:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
elif i==7:
[Link](out1,[Link])
[Link](out2,[Link])
[Link](out3,[Link])
[Link](out4,[Link])
[Link](0.03)
#[Link](1)
if i==0:
i=7
continue
i=i-1

except KeyboardInterrupt:
[Link]()
Working of the Project
This purpose of this simple project is just to understand how to Interface a
Stepper Motor with Raspberry Pi and L298N. The working of the project is very
simple and is explained here.

Initially, you need to calibrate the Stepper Motor by giving some random values so
that the steps will be locked. Here, a positive value (like 30, for example) will make
the Stepper Motor to rotate in clockwise direction and a negative value (like -30) will
make it to rotate in the anti-clockwise direction.

After this initial calibration, you can enter any value and the Stepper Motor will move
to that position. Since we are implementing a Half Stepping Technique, the total
number of steps is 400. So, if you enter 100, the Stepper Motor will rotate 900 in
clock wise direction.

Similarly, by entering other values (either positive or negative) you can accurately
control the position of your Stepper Motor.

You might also like