0% found this document useful (0 votes)
20 views117 pages

E and IOT LAB Usermanual - MLR 20 With M - Python

Uploaded by

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

E and IOT LAB Usermanual - MLR 20 With M - Python

Uploaded by

Shiva reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 117

DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Introduction to Embedded System

1.1 Introduction
An embedded system is various type of computer system or computing device that performs a
dedicated function and/or is designed for use with a specific embedded software application.
Embedded systems may use a combination of ‘Read-only’ as well as with ‘Read-Write’ based
operating system. But an embedded system is not usable as a commercially viable substitute for
general-purpose computers or devices.
An embedded operating system is the software program that manages all the other programs in
an embedded device after initial load of programs by a boot loader. It normally guarantees a
certain capability within a specified storage size and time constraint as well as with application
programs. It also normally has small foot print including initial boot loader, OS kernel, required
device drivers, file systems for the user data and so forth. It has very-likely structure of a normal
operating system however mainly differentiated by some factors such as type of pre-installed
device, functional limits, taking designed job only.

Fig 1.0
Developing software and hardware for microcontroller based systems involves the use of a range
of tools that can include editors, assemblers, compilers, debuggers, simulators, emulators and
MLR INSTITUTE OF TECHNOLOGY 1
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Flash/OTP programmers. To the newcomer to microcontroller development it is often not clear


how all of these different components play together in the development cycle and what
differences there are for example between starter kits, emulators and simulators.
To complicate matters more, there are quite a number of different approaches and technologies
for emulation available that make it difficult for even seasoned embedded engineers to pick the
right tools. With this article, I'll try to give a short explanation of the different tools involved in
the microcontroller development cycle, with a particular focus on the different emulator types
and their advantages and disadvantages.

1.2 Writing Microcontroller Code


Software Code for a microcontroller is written in a programming language of choice (often
Assembler or C). This source code is written with a standard ASCII text editor and saved as an
ASCII text file. Programming in assembler involves learning a microcontroller's specific
instruction set (assembler mnemonics), but results in the most compact and fastest code. A
higher level language like C is for the most part independent of a microcontroller's specific
architecture, but still requires some controller specific extensions of the standard language to be
able to control all of a chip's peripherals and functionality. The penalty for more portable code
and faster program development is a larger code size (20%...40% compared to assembler).

1.3 Translating the Code


Next the source code needs to be translated into instructions the microcontroller can actually
execute. A microcontroller instruction set is represented by "op codes". Op codes are a unique
sequence of bits ("0" and "1") that are decoded by the controller's instruction decode logic and
then executed. Instead of writing opcodes in bits, they are commonly represented as hexadecimal
numbers, whereby one hex number represents 4 bits within a byte, so it takes two hex numbers to
represent 8 bits or 1 byte. For that reason a microcontroller's firmware in machine readable form
is also called Hex-Code and the file that stores that code Hex-File.

1.4 Assemblers, Compilers, Linkers and Librarians


Assemblers or (C-) Compilers translate the human readable source code into "hex code" that
represents the machine instructions (op codes). To support modular code and reusable libraries of
code, most assemblers and compilers today come with Linkers and Librarians.
Linkers, link code modules saved in different files together into a single final program. At the
same time they take care of a chip's memory allocation by assigning each instruction to a
microcontroller memory addresses in such a way that different modules do not overlap.
Librarians help you to manage, organize and revision control a library of re-usable code
modules.
Once the ASCII source code text file has been assembled (with an Assembler) or compiled (with
a Compiler) and the files have been linked (with the Linker), the output results in a number of
files that can be used for debugging the software and programming the actual microcontroller's
memory.
MLR INSTITUTE OF TECHNOLOGY 2
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

1.5 Debugging the Code


A debugger is a piece of software running on the PC, which has to be tightly integrated with the
emulator that you use to validate your code. For that reason all emulator manufacturers ship their
own debugger software with their tools, but also compiler manufacturers frequently include
debuggers, which work with certain emulators, into their development suites.
A Debugger allows you to download your code to the emulator's memory and then control all of
the functions of the emulator from a PC. Common debugging features include the capability to
examine and modify the microcontroller's on-chip registers, data- and program-memory;
pausing or stopping program executing at defined program locations by setting breakpoints;
single-stepping (execute one instruction at a time) through the code; and looking at a history of
executed code (trace).
So far we've talked about several different pieces of software: Text Editor, Assembler or
Compiler, Linkers, Librarians and Debugger. You can easily imagine that it can become quite a
time-consuming challenge to alternate back and forth between all of these programs during the
debugging process (discover a bug, edit the source code, compile it again, link it again,
download the modified code to the emulator, etc.). This is where an integrated development
environment (IDE) comes in.
An Integrated Development Environment puts all of the previously discussed software
components under one common unified user interface, so that it becomes possible to make a
code change and get the modified code loaded into the emulator with a few mouse clicks, instead
of dozens. A good IDE allows you for example to click on a syntax error message produced by
the compiler and have the source code with the highlighted offending instruction pop up for
editing in the text editor. One click of a button and the modified code gets retranslated, linked
and downloaded to the emulator. An IDE allows you to store the configuration settings for a
project - like compiler switches, or what flavor of chip to emulate - so you can easily recreate a
project later on. Some IDEs are flexible enough to allow you to incorporate different choices of
third party tools (like compilers and debuggers), others only work with a manufacturer's own tool
chain.

1.6 Debugging Tools


When it comes to debugging your code and testing your application there are several different
tools you can utilize that differ greatly in terms of development time spend and debugging
features available. In this section we take a look at simulators, microcontroller starter kits and
emulators.

1.7 Simulators
Simulators try to model the behavior of the complete microcontroller in software. Some
simulators go even a step further and include the whole system (simulation of peripherals outside
of the microcontroller). No matter how fast your PC, there is no simulator on the market that can
actually simulate a microcontroller's behavior in real-time. Simulating external events can
become a time-consuming exercise, as you have to manually create "stimulus" files that tell the

MLR INSTITUTE OF TECHNOLOGY 3


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

simulator what external waveforms to expect on which microcontroller pin. A simulator can also
not talk to your target system, so functions that rely on external components are difficult to
verify. For that reason simulators are best suited to test algorithms that run completely within the
microcontroller (like a math routine for example). They are the perfect tool to complement
expensive emulators for large development teams, where buying an emulator for each developer
is financially not feasible.

1.8 Microcontroller Starter Kits


Starter Kits, commonly bundle a hardware board and in-system programmer with some
software components (assembler, linker, debugger, sometimes an IDE and a code-size limited
"evaluation" version of a compiler), to allow for very basic emulation and debugging functions.
These kits are most predominant with Flash based microcontrollers. The Flash memory allows an
actual sample of the microcontroller to be used to "emulate" it-self, by using the included in-
system programmer to download the code into the Flash and execute it.
To enable some basic debugging, that kit’s need to download a small piece of monitor code
along with your own code. This monitor code allows you to stop execution (break) and examine
memory and of course uses some of the microcontroller's resources (interrupts; stack-, code- and
data-memory; some pins). That's why this approach is called intrusive or non-transparent
emulation.
Included with the starter kits is an evaluation board, whose main purpose it is to get you started
on your development quickly without the need to develop your own hardware board. The board
is typically equipped with a sample of a microcontroller to allow you to execute and evaluate
your code. The kits also support the capability to hook up your own hardware if you prefer a
setup closer to your final application.
Do not confuse the evaluation boards with a FLASH or OTP production programmer.
Even though the kits offer programming capability, the microcontroller sockets on the boards are
not built to withstand hundreds or thousands of insertions and are also not equipped with a socket
for all controller packages (sockets only for DIP/PLCC packages, but not for SO or QFP
packages).
A big advantage of these kits over simulators is that they work in real-time and thus allow for
easy input/output functionality verification. Simulators on the other hand offer typically much
more powerful debugging features that rival those of high-end emulators. Starter kits, however,
are completely sufficient and the cheapest option to develop simple microcontroller projects.

1.9 In-System Programming (ISP)


FLASH microcontrollers can be programmed both in-circuit (in-system) and out-of- circuit. With
in-circuit programming the microcontroller is already soldered into the target system and can be
programmed via one of its communication interfaces (UART, SPI). This requires that you have
the signals required for programming routed to an in-system-programming (ISP) connector to
which an ISP programmer can be hooked up. The ISP connector required varies from
manufacturer to manufacturer and microcontroller to microcontroller, so it is recommended that

MLR INSTITUTE OF TECHNOLOGY 4


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

before you start your PCB layout, you decide on which ISP programmer you want to use and
find out which ISP connector is required for it.
As ISP programming is done via a serial interface it is slower than out-of-circuit programming
that uses parallel data transfers - something you might want to consider if you have to program
100 000 devices.
One big advantage of ISP programmers is the fact that they do not require expensive ZIF socket
adapters. All you need is the ISP connector on your board and the microcontroller soldered onto
the board to program even the most exotic package.
Having an ISP connector on your board is a good idea - even if you use out-of-circuit
programming for production. It enables you to do painless firmware updates or last minute bug
fixes without having to disolder the microcontroller first.

Introduction to Smart51®

2.1 Introduction

Smart51® is 8051 based Development Kit and Ideal platform for the embedded system
beginners. The Smart51® development board is as shown in fig1.0

MLR INSTITUTE OF TECHNOLOGY 5


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 1.0

Smart51® has following interfaces

 Interfacing LEDs and switchs


 Interfacing 16x2 Alpha numeric LCD
 Interfacing Serial Port
 Interfacing PS2 key board
 Interfacing Keypad
 Interfacing Relays
 Interfacing RTC
 Interfacing Temperature sensor

With the all above features any kind of medium range of embedded application can be built with
board.

3. 8051 Microcontroller

3.1 Introduction
The 8051 is an 8 bit microcontroller originally developed by Intel in 1980. It is the world's most
popular microcontroller core, made by many independent manufacturers (truly multi-sourced).
There were 126million 8051s (and variants) shipped in 1993!!

MLR INSTITUTE OF TECHNOLOGY 6


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

A typical 8051 contains:


 CPU with Boolean processor
 5 or 6 interrupts: 2 are external, 2 priority levels
 2 or 3 16-bit timer/counters
 Programmable full-duplex serial port(baud rate provided by one of the timers)
 32 I/O lines (four 8-bit ports)
 RAM
 ROM/EPROM in some models

One strong point of the 8051 is the way it handles interrupts. Vectoring to fixed 8-byte areas is
convenient and efficient. Most interrupt routines are very short (or at least they should be), and
generally can fit into the 8-byte area. Of course if your interrupt routine is longer, you can still
jump to the appropriate routine from within the 8 byte interrupt region.
The 8051 instruction set is optimized for the one-bit operations so often desired in real-world,
real-time control applications. The Boolean processor provides direct support for bit
manipulation. This leads to more efficient programs that need to deal with binary input and
output conditions inherent in digital-control problems. Bit addressing can be used for test pin
monitoring or program control flags.
The P89V51RD2 is a 80C51 microcontroller with 64 kB Flash and 1024 bytes of data RAM. A
key feature of the P89V51RD2 is its X2 mode option. The design engineer can choose to run the
application with the conventional 80C51 clock rate (12 clocks per machine cycle) or select the
X2 mode (6 clocks per machine cycle) to achieve twice the throughput at the same clock
frequency. Another way to benefit from this feature is to keep the same performance by reducing
the clock frequency by half, thus dramatically reducing the EMI.
The Flash program memory supports both parallel programming and in serial In-System
Programming (ISP). Parallel programming mode offers gang-programming at high speed,
reducing programming costs and time to market. ISP allows a device to be reprogrammed in the
end product under software control. The capability to field/update the application firmware
makes a wide range of applications possible.
The P89V51RD2 is also In-Application Programmable (IAP), allowing the Flash program
memory to be reconfigured even while the application is running.
3.2 Features
 80C51 Central Processing Unit
 5 V Operating voltage from 0 MHz to 40 MHz
 64 kB of on-chip Flash user code memory with ISP (In-System Programming) and IAP
(In-Application Programming)
 Supports 12-clock (default) or 6-clock mode selection via software or ISP
 SPI (Serial Peripheral Interface) and enhanced UART
 PCA (Programmable Counter Array) with PWM and Capture/Compare functions
 Four 8-bit I/O ports with three high-current Port 1 pins (16 mA each)
 Three 16-bit timers/counters

MLR INSTITUTE OF TECHNOLOGY 7


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Programmable watchdog timer


 Eight interrupt sources with four priority levels
 Second DPTR register
 Low EMI mode (ALE inhibit)
 TTL- and CMOS-compatible logic levels
 Brown-out detection
 Low power modes Power-down mode with external interrupt wake-up Idle mode
 DIP40 packages

3.3 Block Diagram

Fig1.3
 It provides many functions (CPU, RAM, ROM, I/O, interrupt logic, timer, etc.) in a
single package
 8-bit data bus - It can access 8 bits of data in one operation (hence it is an 8-bit
microcontroller)
 16-bit address bus - It can access 216 memory locations - 64 kB each of RAM and ROM
 On-chip RAM - 128 bytes ("Data Memory")
 On-chip ROM - 4 kB ("Program Memory")

MLR INSTITUTE OF TECHNOLOGY 8


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Four byte bi-directional input/output port


 UART (serial port)
 Two 16-bit Counter/timers
 Two-level interrupt priority
 Power saving mode

A particularly useful feature of the 8051 core is the inclusion of a Boolean processing engine
which allows bit-level Boolean logic operations to be carried out directly and efficiently on
internal registers and RAM. This feature helped to cement the 8051's popularity in industrial
control applications. Another valued feature is that it has four separate register sets, which can be
used to greatly reduce interrupt latency compared to the more common method of storing
interrupt context on a stack.
The 8051 UART can be configured to use a 9th data bit that can provide addressable
communications in an RS-485 multi-point communications environment.
8051 based microcontrollers typically include one or two UARTs, two or three timers, 128 or
256 bytes of internal data RAM (16 bytes of which are bit-addressable), up to 128 bytes of I/O,
512 bytes to 64 kB of internal program memory, and sometimes a quantity of extended data
RAM (ERAM) located in the external data space. The original 8051 core ran at 12 clock cycles
per machine cycle, with most instructions executing in one or two machine cycles. With a 12
MHz clock frequency, the 8051 could thus execute 1 million one-cycle instructions per second or
500,000 two-cycle instructions per second. Enhanced 8051 cores are now commonly used which
run at six, four, two, or even one clock per machine cycle, and have clock frequencies of up to
100 MHz, and are thus capable of an even greater number of instructions per second. All SILabs,
some Dallas and a few Atmel devices have single cycle cores.
Even higher speed single cycle 8051 cores, in the range 130 MHz to 150 MHz, are now available
in internet downloadable form for use in programmable logic devices such as FPGAs, and at
many hundreds of MHz in ASICs.
Common features included in modern 8051 based microcontrollers include built-in reset timers
with brown-out detection, on-chip oscillators, self-programmable Flash ROM program memory,
boot loader code in ROM, EEPROM non-volatile data storage, I²C, SPI, and USB host
interfaces, PWM generators, analog comparators, A/D and D/A converters, RTCs, extra counters
and timers, in-circuit debugging facilities, more interrupt sources, and extra power saving modes.

3.4 Pin Diagram

MLR INSTITUTE OF TECHNOLOGY 9


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 1.7

MLR INSTITUTE OF TECHNOLOGY 10


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Introduction to KEIL IDE

4.1 About µVision3 IDE


The µVision3 IDE is a Windows-based software development platform that combines a robust
editor, project manager, and make facility. µVision3 integrates all tools including the C
compiler, macro assembler, linker/locator, and HEX file generator.

Fig 4.1

MLR INSTITUTE OF TECHNOLOGY 11


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

µVision3 helps expedite the development process of your embedded applications by providing
the following:

 Full-featured source code editor,


 Device database for configuring the development tool setting,
 Project manager for creating and maintaining your projects,
 Integrated make facility for assembling, compiling, and linking your embedded
applications,
 Dialogs for all development tool settings, True integrated source-level Debugger with
high-speed CPU and peripheral simulator,
 Advanced GDI interface for software debugging in the target hardware and for
connection to Keil ULINK,
 Flash programming utility for downloading the application program into Flash ROM,
 Links to development tools manuals, device datasheets & user's guides.

The µVision3 IDE offers numerous features and advantages that help you quickly and
successfully develop embedded applications. They are easy to use and are guaranteed to help you
achieve your design goals.

The µVision3 IDE and Debugger is the central part of the Keil development toolchain.
µVision3 offers a Build Mode and a Debug Mode.

In the µVision3 Build Mode you maintain the project files and generate the application.

4.2 User Interface


The µVision3 User Interface consists of menus, toolbar buttons, keyboard shortcuts, dialog
boxes, and windows that you use as you interact with and manage the various aspects of your
embedded project.

The menu bar provides menus for editor operations, project maintenance, development tool
option settings, program debugging, external tool control, window selection and manipulation,
and on-line help.

The toolbar buttons allow you to rapidly execute µVision3 commands. A Status Bar provides
editor and debugger information. The various toolbars and the status bar can be enabled or
disabled from the View Menu commands.

Keyboard shortcuts offer quick access to µVision3 commands and may be configured via the
menu command Edit — Configuration — Shortcut Key.

MLR INSTITUTE OF TECHNOLOGY 12


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

The following sections list the µVision3 commands that can be reached by menu commands,
toolbar buttons, and keyboard shortcuts. The µVision3 commands are grouped mainly based
on the appearance in the menu bar:
 File Menu and File Commands
 Edit Menu and Editor Commands
 Outlining Menu
 Advanced Menu
 Selecting Text Commands
 View Menu
 Project Menu and Project Commands
 Debug Menu and Debug Commands
 Flash Menu
 Peripherals Menu
 Tools Menu
 SVCS Menu
 Window Menu
 Help Menu

4.3 Creating an Application

Any application, if we want to develop using KEIL IDE first we need to create a Project. Project
is nothing but creating source files and related executable file for this , first we need to create a
folder where ever u want to have the project files. And follow the procedure given below.

Step1: Creating a project

To create a new project file, go to the µVision3 menu and select Project — New — µVision
Project…. The Create New Project dialog asks you for the new project file name. At this time
navigate to the folder where your new project will reside. It's a good idea to use a separate folder
for each project. Use the icon Create New Folder in this dialog to create a new empty folder.

Select this folder and enter the file name for the new project, i.e. Project1. µVision3 creates a
new project file with the name PROJECT1.UV2 which contains a default target and file group
name. You can see these names in the Project Workspace — Files.

Step2: Select Microcontroller from the database

When you create a new project µVision3 asks you to select a CPU for your project. The Select
Device dialog box shows the µVision3 device database. Just select the microcontroller you use.
For the example in this chapter we are using the Philips 89V51rd2 controller. This selection sets
necessary tool options for the 89V51RD2 device and simplifies the tool configuration.

MLR INSTITUTE OF TECHNOLOGY 13


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 4.2

For some devices, µVision3 requires additional parameters that you have to enter manually.
Please carefully read the information provided under Description. It might have additional
instructions for the device configuration.

Step3: Adding startup code

A embedded program requires CPU initialization code that needs to match the configuration of
your hardware design. This Startup Code depends also on the tool chain that you are using. Since
you might need to modify that file to match your target hardware, the file should be copied to
your project folder.

For most devices, µVision3 asks you to copy the CPU specific Startup Code to your project. This
is required on almost all projects (exceptions are library projects and add-on projects). The
Startup Code performs configuration of the microcontroller device and initialization of the
compiler run-time system.

Step4: Creating new Source files

You may create a new source file with the menu option File — New. This opens an empty editor
window where you can enter your source code. µVision3 enables the C color syntax highlighting

MLR INSTITUTE OF TECHNOLOGY 14


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

when you save your file with the dialog File — Save As... Under a filename with the extension
*.C. We are saving our example file under the name MAIN.C.

Step5: Adding Source files to Project

Once you have created your source file you can add this file to your project. µVision3 offers
several ways to add source files to a project. For example, you can select the file group in the
Project Workspace — Files page and click with the right mouse key to open a local menu. The
option Add Files opens the standard files dialog. Select the file MAIN.C you have just created.

Fig 4.3

Step6: Setting tool Options

µVision3 lets you set options for your target hardware. The dialog Options for Target opens via
the toolbar icon or via the Project — Options for Target menu item. In the Target tab you
specify all relevant parameters of your target hardware and the on-chip components of the device
you have selected. The following dialog shows the settings for our example.

MLR INSTITUTE OF TECHNOLOGY 15


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 4.3

The following table describes the options of the Target dialog:

Dialog Item Description


Xtal specifies the external clock frequency of your device. Several microcontrollers use an on-chip PLL
to generate the CPU clock. In this cases the value is not identical with the XTAL frequency. Check
your hardware design carefully to determine the correct value.

Operating allows you to select a Real-Time Operating System for your project.
System

Use On-chip defines the address spaces for the on-chip memory components for the linker/locater. Note that on
ROM / RAM some devices you need to reflect this configuration in the Startup Code.

MLR INSTITUTE OF TECHNOLOGY 16


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Step7: Configure the Startup code

The CPU Startup Code (on most ARM targets the file name is Startup.S) may be open from the
Project Workspace — Files Tab. Most startup files have embedded comments for the µVision3
Configuration Wizard which provides menu driven selections.

The default settings of the Startup Code give a good starting point on most single chip
applications. However you need to adapt the configuration for your target hardware. CPU/PLL
clock and BUS system are target specific and cannot be automatically configured. Some devices
provide options to enable or disable on-chip components (for example on-chip xdata RAM on
8051 variants).

You must ensure that the settings in the startup file match the other settings in your project. The
button Edit as Text opens the Startup Code in a standard editor window and allows you to
review the source code of this file.

Step8: Building project

Typically, the tool settings under Options — Target are all you need to start a new application.
You may translate all source files and link the application by clicking on the Build Target
toolbar button.

When you build an application, µVision3 displays errors, warnings, and any other messages in
the Output Window — Build page. Double-click on a message to open the corresponding
source file.

MLR INSTITUTE OF TECHNOLOGY 17


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

After building the project, you may Modify existing source code or add new source files to the
project. The Build Target toolbar button translates only modified or new source files and
generates the executable file. µVision3 maintains a file dependency list and knows all include
files used within a source file. Even the tool options are saved in the file dependency list, so that
µVision3 rebuilds files only when needed. With the Rebuild Target command, all source files
are translated, regardless of modifications.

Step9: Creating Hex file

Once you have successfully generated your application you can start debugging. After you have
tested your application, it is required to create an Intel HEX file to download the software into an
EPROM programmer or simulator. µVision3 creates HEX files with each build process when
Create HEX file under Options for Target — Output is enabled. The FLASH Fill Byte, Start and
End values direct the OH166 utility to generate a sorted HEX files; sorted files are required for
some Flash programming utilities.

You may start your PROM programming utility after the make process when you specify the
program under the option User — Run User Program #1 as explained under Start External Tools.

Fig 4.4

The created Hex file will be transferred to the microcontroller using a tool called Flash magic.

MLR INSTITUTE OF TECHNOLOGY 18


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

5. Introduction Flash Magic Tool

5.1 Introduction

Flash magic Tools developed and distributed by NXP semiconductors and it if freely available in
the internet and here we have included the CD along with manual. In the CD in the softwares
folders you will find a setup file called FlashMagic.exe, double click on the icon then u fill see
the following setup image on the desktop.

Fig 5.1

Click on the Run button the following window will come

MLR INSTITUTE OF TECHNOLOGY 19


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 5.2

Click on next button then the following window will come

Fig 5.3

Click on the “I accept the agreement” then the following window will come

Fig 5.4
Select the Installation location using Browse button and click on the Next Button
Then it will show the following window
MLR INSTITUTE OF TECHNOLOGY 20
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 5.5

Click on Install button after installation it will create a ICON on the desktop if you double click
on the icon the following will appear.

MLR INSTITUTE OF TECHNOLOGY 21


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Fig 5.6

6 Building and running the LED Blinking application on Smart51®

6.1 Getting started with keil (creating .hex file)


Double Click on the keil icon

Keil uVision2.lnk

Keil window page will be opened

 If you find any project(program) is already displayed, then go to project and


Choose the option close the project.
MLR INSTITUTE OF TECHNOLOGY 22
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Now go to Project and click on the New Project

 As you click on New Project you will get a window as Create New Project
 Now create a New Folder on the desktop, open the new folder and write a
File name (Example: led) to the project and then save it.

MLR INSTITUTE OF TECHNOLOGY 23


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 As soon as you save the file name, automatically a window “Select device for Target
‘Target 1’ ” is opened.

 Double click on Atmel, you will get a list of IC’s.

MLR INSTITUTE OF TECHNOLOGY 24


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Select AT89LV51 and press OK

 Now click on File and select New

MLR INSTITUTE OF TECHNOLOGY 25


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 A text page Text1 will be opened as shown

 Now write your application program (ex: Led program) on the text page.

 As you complete writing your application programs click on save, a Save As window
appears, give the File name with extension .C (Example Led.c) and save it.

MLR INSTITUTE OF TECHNOLOGY 26


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Add files to Source Group

 Click on Led and then Add it

MLR INSTITUTE OF TECHNOLOGY 27


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Right click on target

 Select frequency 11.0592 MHz

MLR INSTITUTE OF TECHNOLOGY 28


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Go to output and select create HEX file

MLR INSTITUTE OF TECHNOLOGY 29


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 If there are no errors, Click on save and close the window

7. Dumping the .hex in the micro controller


MLR INSTITUTE OF TECHNOLOGY 30
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

7.1 Getting started with Flash Magic

 Double click on the Flash Magic icon

Default Setting

 Go to Options  Advanced Options

 Select Communication  select on Half-duplex Communications

MLR INSTITUTE OF TECHNOLOGY 31


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Now Click on Hardware Config  select Assert DTR and RTS while COM Port
open

 Now Click on Just in Time Code select Browse Local disk C  Program Files
 Flash Magic  JIT Examples  Manual Serial Number 
ManualSerialNumber  Open
 Write Timeout 20 seconds and then click OK

MLR INSTITUTE OF TECHNOLOGY 32


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

7.2 Settings and Dumping the application program (.hex file) to the Trainer
kit using Flash Magic.

Step 1 - Communications
COM Port : COM 1
Baud Rate : 9600
Device : 89LV51RD2
Interface : None {ISP}
Step 2 - Erase
Select Erase all Flash
Step 3 – Browse
Each time, browse the application program HEX file from the created folder
which has to be loaded in the IC.
Step 4 – Options
Select Verify after programming
Step 5 – Start
Before going to Step 5. Go to ISP Click on Read Device Signature
(NOTE: - See that the RS-232 is connected to the trainer kit and computer and also power
supply on the kit is turned off)

 As soon as you click on Read device Signature this window appears, now switch on the
trainer kit, go to step 5 and click on Start.

MLR INSTITUTE OF TECHNOLOGY 33


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Interface the ports and connectors as per the program design


 For example programs refer CD

MLR INSTITUTE OF TECHNOLOGY 34


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

8. HyperTerminal

8.1 Introduction to HyperTerminal

HyperTerminal is a program that you can use to connect to other computers, Telnet sites, bulletin
board systems (BBSs), online services, and host computers, using either your modem, a null
modem cable or Ethernet connection.

Though using HyperTerminal with a BBS to access information on remote computers is a


practice that has become less common with the availability of the World Wide Web,
HyperTerminal is still a useful means of configuring and testing your modem or examining your
connection with other sites.

HyperTerminal records the messages passed to and from the computer or service on the other
end of your connection. Therefore, it can serve as a valuable troubleshooting tool when setting
up and using your modem. To make sure that your modem is connected properly or to view your
modem's settings, you can send commands through HyperTerminal and check the results.
HyperTerminal has scroll functionality that allows you to look at received text that has scrolled
off the screen.

You can use HyperTerminal to transfer large files from a computer onto your portable computer
using a serial port rather than going through the process of setting your portable computer up on
a network.

You can use HyperTerminal to help debug source code from a remote terminal. You can also use
HyperTerminal to communicate with older character-based computers.

HyperTerminal is designed to be an easy-to-use tool and not meant to replace other full feature
tools available on the market. You can use HyperTerminal to perform the specific tasks
described above, but you should not attempt to use HyperTerminal for more complex

MLR INSTITUTE OF TECHNOLOGY 35


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

communication needs. For more information on what HyperTerminal does and does not support,
see the HyperTerminal frequently asked questions list at the Hilgraeve Web Site.

8.2 Getting started with HyperTerminal


 To open HyperTerminal, click Start, point to All Programs, point to Accessories, point to
Communications, and then click HyperTerminal.

MLR INSTITUTE OF TECHNOLOGY 36


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Now go to File  Click on Properties

MLR INSTITUTE OF TECHNOLOGY 37


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

MLR INSTITUTE OF TECHNOLOGY 38


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

MLR INSTITUTE OF TECHNOLOGY 39


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

9. Real Time Operating System


A real-time operating system (RTOS) (Generally pronounced as: Are-toss) is a multitasking
operating system intended for real-time applications. Such applications include embedded
systems (programmable thermostats, household appliance controllers, mobile telephones),
industrial robots, spacecraft, industrial control , and scientific research equipment.
An RTOS facilitates the creation of a real-time system, but does not guarantee the final result
will be real-time; this requires correct development of the software. An RTOS does not
necessarily have high throughput; rather, an RTOS provides facilities which, if used properly,
guarantee deadlines can be met generally (soft real-time) or deterministically (hard real-time).
An RTOS will typically use specialized scheduling algorithms in order to provide the real-time
developer with the tools necessary to produce deterministic behavior in the final system. An
RTOS is valued more for how quickly and/or predictably it can respond to a particular event than
for the given amount of work it can perform over time. Key factors in an RTOS are therefore a
minimal interrupt latency and a minimal thread switching latency.
An early example of a large-scale real-time operating system was Transaction Processing
Facility developed by American Airlines and IBM for the Sabre Airline Reservations System.

Design philosophies
Two basic designs exist:
 Event-driven (priority scheduling) designs switch tasks only when an event of higher
priority needs service, called pre-emptive priority.
 Time-sharing designs switch tasks on a clock interrupt, and on events, called round robin.

Time-sharing designs switch tasks more often than is strictly needed, but give smoother, more
deterministic multitasking, giving the illusion that a process or user has sole use of a machine.
Early CPU designs needed many cycles to switch tasks, during which the CPU could do nothing
useful. So early OSes tried to minimize wasting CPU time by maximally avoiding unnecessary
task-switches.
More recent CPUs take far less time to switch from one task to another; the extreme case is
barrel processors that switch from one task to the next in zero cycles. Newer RTOS almost
invariably implement time-sharing scheduling with priority driven pre-emptive scheduling.

Scheduling
In typical designs, a task has three states: 1) running, 2) ready, 3) blocked. Most tasks are
blocked, most of the time. Only one task per CPU is running. In simpler systems, the ready list is
usually short, two or three tasks at most.
The real key is designing the scheduler. Usually the data structure of the ready list in the
scheduler is designed to minimize the worst-case length of time spent in the scheduler's critical
section, during which preemption is inhibited, and, in some cases, all interrupts are disabled. But,
MLR INSTITUTE OF TECHNOLOGY 40
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

the choice of data structure depends also on the maximum number of tasks that can be on the
ready.
If there are never more than a few tasks on the ready list, then a simple unsorted bidirectional
linked list of ready tasks is likely optimal. If the ready list usually contains only a few tasks but
occasionally contains more, then the list should be sorted by priority, so that finding the highest
priority task to run does not require iterating through the entire list. Inserting a task then requires
walking the ready list until reaching either the end of the list, or a task of lower priority than that
of the task being inserted. Care must be taken not to inhibit preemption during this entire search;
the otherwise-long critical section should probably be divided into small pieces, so that if, during
the insertion of a low priority task, an interrupt occurs that makes a high priority task ready, that
high priority task can be inserted and run immediately (before the low priority task is inserted).
The critical response time, sometimes called the flyback time, is the time it takes to queue a new
ready task and restore the state of the highest priority task. In a well-designed RTOS, readying a
new task will take 3-20 instructions per ready queue entry, and restoration of the highest-priority
ready task will take 5-30 instructions. On a 20MHz 68000 processor, task switch times run about
20 microseconds with two tasks ready.100 MHz ARM CPUs switch in a few microseconds.
In more advanced real-time systems, real-time tasks share computing resources with many non-
real-time tasks, and the ready list can be arbitrarily long. In such systems, a scheduler ready list
implemented as a linked list would be inadequate.

Algorithms
Some commonly used RTOS scheduling algorithms are:
 Cooperative scheduling
o Round-robin scheduling
o Fixed priority pre-emptive scheduling
 Preemptive scheduling
o Preemptive time slicing
o Critical section preemptive scheduling
o Static time scheduling
 Earliest Deadline First approach
 Advanced scheduling using the stochastic and MTG

Inter task communication and resource sharing


Multitasking systems must manage sharing data and hardware resources among multiple tasks. It
is usually "unsafe" for two tasks to access the same specific data or hardware resource
simultaneously. ("Unsafe" means the results are inconsistent or unpredictable, particularly when
one task is in the midst of changing a data collection. The view by another task is best done
either before any change begins, or after changes are completely finished.) There are three
common approaches to resolve this problem:
MLR INSTITUTE OF TECHNOLOGY 41
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Temporarily masking/disabling interrupts


 Binary semaphores
 Message passing

General-purpose operating systems usually do not allow user programs to mask (disable)
interrupts, because the user program could control the CPU for as long as it wished. Modern
CPUs make the interrupt disable control bit (or instruction) inaccessible in user mode to allow
operating systems to prevent user tasks from doing this. Many embedded systems and RTOSs,
however, allow the application itself to run in kernel mode for greater system call efficiency and
also to permit the application to have greater control of the operating environment without
requiring OS intervention.
On single-processor systems, if the application runs in kernel mode and can mask interrupts,
often that is the best (lowest overhead) solution to preventing simultaneous access to a shared
resource. While interrupts are masked, the current task has exclusive use of the CPU; no other
task or interrupt can take control, so the critical section is effectively protected. When the task
exits its critical section, it must unmask interrupts; pending interrupts, if any, will then execute.
Temporarily masking interrupts should only be done when the longest path through the critical
section is shorter than the desired maximum interrupt latency, or else this method will increase
the system's maximum interrupt latency. Typically this method of protection is used only when
the critical section is just a few source code lines long and contains no loops. This method is
ideal for protecting hardware bitmapped registers when the bits are controlled by different tasks.
When the critical section is longer than a few source code lines or involves lengthy looping, an
embedded/real-time programmer must resort to using mechanisms identical or similar to those
available on general-purpose operating systems, such as semaphores and OS-supervised
interprocess messaging. Such mechanisms involve system calls, and usually invoke the OS's
dispatcher code on exit, so they can take many hundreds of CPU instructions to execute, while
masking interrupts may take as few as three instructions on some processors. But for longer
critical sections, there may be no choice; interrupts cannot be masked for long periods without
increasing the system's interrupt latency.
A binary semaphore is either locked or unlocked. When it is locked, a queue of tasks can wait for
the semaphore. Typically a task can set a timeout on its wait for a semaphore. Problems with
semaphore based designs are well known: priority inversion and deadlocks.
In priority inversion, a high priority task waits because a low priority task has a semaphore. A
typical solution is to have the task that has a semaphore run at (inherit) the priority of the highest
waiting task. But this simplistic approach fails when there are multiple levels of waiting (A waits
for a binary semaphore locked by B, which waits for a binary semaphore locked by C). Handling
multiple levels of inheritance without introducing instability in cycles is not straightforward.
In a deadlock, two or more tasks lock a number of binary semaphores and then wait forever (no
timeout) for other binary semaphores, creating a cyclic dependency graph. The simplest deadlock
scenario occurs when two tasks lock two semaphores in lockstep, but in the opposite order.
Deadlock is usually prevented by careful design, or by having floored semaphores (which pass
control of a semaphore to the higher priority task on defined conditions).

MLR INSTITUTE OF TECHNOLOGY 42


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

The other approach to resource sharing is for tasks to send messages. In this paradigm, the
resource is managed directly by only one task; when another task wants to interrogate or
manipulate the resource, it sends a message to the managing task. This paradigm suffers from
similar problems as binary semaphores: Priority inversion occurs when a task is working on a
low-priority message, and ignores a higher-priority message (or a message originating indirectly
from a high priority task) in its in-box. Protocol deadlocks occur when two or more tasks wait for
each other to send response messages. Although their real-time behavior is less crisp than
semaphore systems, simple message-based systems usually do not have protocol deadlock
hazards, and are generally better-behaved than semaphore systems.

Interrupt handlers and the scheduler


Since an interrupt handler blocks the highest priority task from running, and since real time
operating systems are designed to keep thread latency to a minimum, interrupt handlers are
typically kept as short as possible. The interrupt handler defers all interaction with the hardware
as long as possible; typically all that is necessary is to acknowledge or disable the interrupt (so
that it won't occur again when the interrupt handler returns). The interrupt handler then queues
work to be done at a lower priority level, often by unblocking a driver task (through releasing a
semaphore or sending a message). The scheduler often provides the ability to unblock a task
from interrupt handler context.

Memory allocation
Memory allocation is even more critical in an RTOS than in other operating systems. Firstly,
speed of allocation is important. A standard memory allocation scheme scans a linked list of
indeterminate length to find a suitable free memory block; however, this is unacceptable as
memory allocation has to occur in a fixed time in an RTOS.V Secondly, memory can become
fragmented as free regions become separated by regions that are in use. This can cause a
program to stall, unable to get memory, even though there is theoretically enough available.
Memory allocation algorithms that slowly accumulate fragmentation may work fine for desktop
machines—when rebooted every month or so—but are unacceptable for embedded systems that
often run for years without rebooting. The simple fixed-size-blocks algorithm works
astonishingly well for simple embedded systems.
Another real strength of fixed size blocks is for DSP systems particularly where one core is
performing one section of the pipeline and the next section is being done on another core. In this
case, fixed size buffer management with one core filling the buffers and another set of cores
returning the buffers is very efficient. A DSP optimized RTOS like Unison Operating System or
DSP nano RTOS provides these features.
10 UC/OS Operating System

μC/OS

MLR INSTITUTE OF TECHNOLOGY 43


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Micro/OS(commonly termed µC/OS or uC/OS), is a low-cost priority-based pre-emptive real


time multitasking operating system kernel for microprocessors, written mainly in the C
programming language. It is mainly intended for use in embedded systems.

μC/OS is a portable, ROMable, scalable, preemptive real-time, deterministic, multitasking kernel


for microprocessors, microcontrollers and DSPs. μC/OS can manage up to 63 application tasks
and provides the following services:

1. Semaphores.
2. Event Flags.
3. Mutual Exclusion Semaphores (to reduce priority inversions) .
4. Message Mailboxes.
5. Message Queues.
6. Task Management.
7. Time Management.
8. Fixed Sized Memory Block Management.

μC/OS can be scaled to only contain the features you need for your application and thus provide
a small footprint. Depending on the processor, μC/OS can be reduced to as little as 2K bytes of
code space and 300 bytes of data space (excluding stacks).

The execution time for most of the services provided by μC/OS is both constant and
deterministic. This means that the execution Times do not depend on the number of tasks
running in your Application μC/OS has been used in hundreds of products from companies all
around the world. Many colleges and Universities worldwide are also using μC/OS-II in
curriculum teaching the subject of real-time systems. This ensures that engineers in the
workplace are trained and ready to use μC/OS in your products.

μC/OS view

You can ‘View’ the status of your tasks which are managed by μC/OS with an add-on module
called μC/OS-View. To accomplish this, you add a small target resident module that
communicates with a Microsoft Windows application via an RS-232C serial port.

MLR INSTITUTE OF TECHNOLOGY 44


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

11. LAB programs

/**********************************************************************/

PPROGRAM-1

EXP:1 LED BLINKING USING 8051

TITLE : Program To Toggle All The Bits Of Port P1 Continuously With 250 ms Delay

AIM : TO BLINK THE LEDS

8051 FAMILY: AT89C51

Software IDE : KEIL

PROCEDURE:

1) In this Program PORT0 Is connected to the LED PORT .

MLR INSTITUTE OF TECHNOLOGY 45


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

2) Put the data 0x00 in to PORT0.


3) To clear the PORT0.
4) Enter into while loop.
5) Put the data 0xFF into PORT0.To ON the leds.
6) Give 20 millisecond delay.
7) Put the data 0x00 into PORT0.To OFF the leds.
8) Give 20 millisecond delay.
9) This process is repeated continuously.

PROGRAM :
i) Write an Embedded C program to blink the leds with delay of 20 msec at Port
zero?

#include<reg51.h>
void delay_ms(int sec);
void delay_ms(int sec)
{
int i,j;
for(i=0;i<sec;i++)
for(j=0;j<1275;j++);
}
void main()
{
P0=0x00;
while(1)
{
P0=0xff;
delay_ms(250);
P0=0x55;
delay_ms(250);
}

/********************************************************************/
Result

MLR INSTITUTE OF TECHNOLOGY 46


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Viva Questions:
i. What are the features of 8051?
ii. What is a particularly useful feature of the 8051?
iii. In 8051 how many clock cycles per machine cycle?
iv. Explain Memory Architecture of 8051?
v. How many ports dose 8051 has?
Task
1) Write an Embedded C program to Blink the LED with various Patterns at port1 using
8051.
2) Write an Embedded C program to Blink the LED with ascending order and descending
order with different delay at port2 using 8051

MLR INSTITUTE OF TECHNOLOGY 47


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-2

EXP:2 SWITCH PROGRAM


TITLE : Develop and execute the program such that whenever a Switch is pressed
corresponding LED glows
AIM : WHEN EVER SWITCH IS PRESSED CORRESPONDING LED
TURNS ON
8051 FAMILY
IDE : KEIL
THEORY : SWITCHES
Eight Tactile Switches can be used as keypad to the controller.

PROCEDURE:

1) In this Program PORT0 Is connected to the LED PORT .PORT1 connected to SWITCH
PORT
2) put the data 0x00 in to PORT0 and PORT1 to clear the PORTS.
3) Enter into while loop.

MLR INSTITUTE OF TECHNOLOGY 48


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

4) Check the status of the switch1 if pressed enter into the if block .
5) Wait for releasing the switch1.
6) After releasing ON the LED1.and comes out from if block.
7) And check the status of switch2 if it is pressed enter into the block and ON the
corresponding LED.
8) Does not match check the switch3 status.
9) This process is repeated continuously.

i) Write an Embedded C program to blink the leds connected to port zero controlled at
port one?
#include<reg51.h>
sbit sw1 = P1^0; /* SWITCH1 CONNECTED TO PORT1.0 */
sbit sw2 = P1^1; /* SWITCH2 CONNECTED TO PORT1.1 */
sbit sw3 = P1^2; /* SWITCH3 CONNECTED TO PORT1.2 */
sbit sw4 = P1^3; /* SWITCH4 CONNECTED TO PORT1.3 */
sbit sw5 = P1^4; /* SWITCH5 CONNECTED TO PORT1.4 */
sbit sw6 = P1^5; /* SWITCH6 CONNECTED TO PORT1.5 */
sbit sw7 = P1^6; /* SWITCH7 CONNECTED TO PORT1.6 */
sbit sw8 = P1^7; /* SWITCH8 CONNECTED TO PORT1.7 */

/* MAIN PROGRAM */
void main()
{
P0 = 0x00; /* CLEARING PORT0 */
P1 = 0x00; /* CLEARING PORT1 */
while(1)
{
if(sw1 == 1) //CHECK IF THE SWITCH1 IS PRESSED
{
while(sw1 != 0); //WAIT FOR RELEASING THE KEY

MLR INSTITUTE OF TECHNOLOGY 49


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

P0 = 0x01; //PUT THE DATA INTO PORT0


}
if(sw2 == 1) //CHECK IF THE SWITCH2 IS PRESSED
{
while(sw2 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x02; //PUT THE DATA INTO PORT0
}
if(sw3 == 1) //CHECK IF THE SWITCH3 IS PRESSED
{
while(sw3 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x04; //PUT THE DATA INTO PORT0
}
if(sw4 == 1) //CHECK IF THE SWITCH4 IS PRESSED
{
while(sw4 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x08; //PUT THE DATA INTO PORT0
}
if(sw5 == 1) //CHECK IF THE SWITCH5 IS PRESSED
{
while(sw5 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x10; //PUT THE DATA INTO PORT0
}
if(sw6 == 1) //CHECK IF THE SWITCH6 IS PRESSED
{
while(sw6 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x20; //PUT THE DATA INTO PORT0
}
if(sw7 == 1) //CHECK IF THE SWITCH7 IS PRESSED
{

MLR INSTITUTE OF TECHNOLOGY 50


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

while(sw7 != 0); //WAIT FOR RELEASING THE KEY


P0 = 0x40; //PUT THE DATA INTO PORT0
}
if(sw8 == 1) //CHECK IF THE SWITCH8 IS PRESSED
{
while(sw8 != 0); //WAIT FOR RELEASING THE KEY
P0 = 0x80; //PUT THE DATA INTO PORT0
}

}
}

/**********************************************************************/

RESULT

MLR INSTITUTE OF TECHNOLOGY 51


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Task :

i) Write an Embedded C program to control the led at connect led port1.2


controlled(Switch) at port2.1?
ii) Develop and execute the program such that whenever a Switch is pressed corresponding
LED glows

PROGRAM-3

MLR INSTITUTE OF TECHNOLOGY 52


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

EXP:3 TIMERS PROGRAM

AIM : To toggle all the bits of port P1 continuously with some delay in between. Using Timer
0, 16-bit mode to generate the delay

8051 FAMILY: AT89C51

Soft ware IDE : KEIL

THEORY : timers
The timers are used to generate exact time delay for blinking of leds conneceted
to the controller.

PROCEDURE:

1) In this Program PORT 1 Is connected to the LED PORT . put the data 0x00 in to PORT0
and PORT1 to clear the PORTS.
2) Declare the delay function.
3) Enter into while loop.
4) Write toggle led’s connected to port 1
5) Close the while loop
6) Close the main function
7) Write delay function.
8) Place the TMOD value
9) Set the baud rate for TH0
10) Start the timer .
11) Check the overflow condition , if it is overflow’s TI is clear.

i) Write an Embedded C program to toggle all the bits of port one with delay in between by
using Timer 0 in 16-bit ?

Solution:

MLR INSTITUTE OF TECHNOLOGY 53


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

#include <reg51.h>
void T0Delay(void);
void main(void){
while (1) {
P1=0x55;
T0Delay();
P1=0xAA;
T0Delay();
}
}
void T0Delay(){
TMOD=0x01;
TL0=0x00;
TH0=0x35;
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;

Result:

MLR INSTITUTE OF TECHNOLOGY 54


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

ii) Write an Embedded C program to toggle P1.5 with delay of 50 ms. Use Timer 0, mode 1
(16-bit) to create the delay?
Solution:

#include <reg51.h>
void T0M1Delay(void);
sbit mybit=P1^5;
void main(void){
while (1) {
mybit=~mybit;
T0M1Delay();
}
}
void T0M1Delay(void){
TMOD=0x01;
TL0=0xFD;
TH0=0x4B;
TR0=1;
while (TF0==0);
TR0=0;
TF0=0;

Result:

MLR INSTITUTE OF TECHNOLOGY 55


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Viva Questions:

i. What is the function of timer?


ii. Explain the interrupts of 8051 micro controller?
iii. Explain about different modes of timer ?

Task

1) Write an 8051 C program to toggle all bits of P2 continuously every 500 ms. Use Timer 1.
mode 1 to create the delay.

2) Write an 8051 C program to toggle only pin PI.5 continuously every 250 ms. Use Timer 0,
mode 2 (8-bit auto-reload) to create the delay.

MLR INSTITUTE OF TECHNOLOGY 56


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-4

EXP-4 : SERIAL COMMUNICATION PROGRAM

AIM : TO WRITE A PROGRAM FOR SERIAL COMMUNICATION

8051 FAMILY: AT89C51

IDE : KEIL

THEORY :

Serial Port

The controller has a single UART port through which it can communicate serially with PC. But
for converting the 0 & 5 volt signal into PC’s plus minus 12v we require a line Driver IC for
which we use MAX 232.
HyperTerminal
HyperTerminal is a program that you can use to connect to other computers, Telnet sites, and
bulletin board systems (BBSs), online services, hardware devices and host computers, using
either your modem or a null modem cable.

PROCEDURE:

1) In this Program PORT1 Is connected to the LCD PORT and SERIAL PORT is connected to
COM PORT1
2) Open the hyper terminal and select COMPORT1 and put the 9600 baud rate.
3) Wait for 20 millisecond .
4) Set SCON register to 0x50.and TMOD register to 0x20.timer will be operate on mode2.
5) Set the 9600 baud rate. On the timer1.
6) Assign your required character to sbuf
7) And the same data is transmitted to HyperTerminal.
8) This process is repeated continuously.

MLR INSTITUTE OF TECHNOLOGY 57


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

i. Write an Embedded C program to transfer the letter “V” serially at 4800 baud
rate ?

Solution:
#include <reg51.h>
void main(void){
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud rate
SCON=0x50;
TR1=1;
while (1) {
SBUF=‘v’; //place value in buffer
while (TI==0);
TI=0;
}

Result:

MLR INSTITUTE OF TECHNOLOGY 58


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

ii. Write an Embedded C program to transfer the message “YES” serially at 9600
baud rate?

Solution:
#include <reg51.h>
void SerTx(unsigned char);
void main(void){
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFD; //9600 baud rate
SCON=0x50;
TR1=1; //start timer
while (1) {
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
}
}
void SerTx(unsigned char x){
SBUF=x; //place value in buffer
while (TI==0); //wait until transmitted
TI=0;

Result:

MLR INSTITUTE OF TECHNOLOGY 59


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Viva Questions:

i. What is hardware and software interface?

ii. What is programming against software interface?

iii. Explain hardware interface?

iv. Explain Software interface?

v. What is serial communication ?

vi. What is parallel communication?

vii. What is the width of data bus?

viii. What is the width of address bus?

MLR INSTITUTE OF TECHNOLOGY 60


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-5

EXP-5 : LCD with 8051 INTERFACING PROGRAM

AIM : TO WRITE A PROGRAM FOR DISPLAYING DATA ON THE LCD

8051 FAMILY: AT89C51

IDE : KEIL

THEORY :
Lcd
A two line, 16 characters LCD is used to display the status of the serial port i.e. to display the
data written on hyper terminal.

PROCEDURE:

1) In this Program PORT3 Is connected to the LCD PORT and


2) Initialize the LCD and clear the LCD set the lcd cursor position to 1 st line starting letter.
3) Send_string function sends the data from microcontroller to PC hyperterminal.
4) Give the string that displayed on the lcd
5) Enter the data in HyperTerminal is stored in array buffer and display on the LCD .
6) And the same data is transmitted to HyperTerminal.
7) This process is repeated continuously.

MLR INSTITUTE OF TECHNOLOGY 61


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

8) Write the delay function.


9) Write the data mode function for transferring the data controller to lcd.
10) Write the command mode function and commands how the data can be displayed on the lcd.
11) Write the string function for transferring the data from microcontroller to lcd display

1). Write an Embedded C program to display the Message at port 1 on the 16x2 lcd
display?
Solution:

/* LCD16x2 8 bit 8051 interface */

#include<reg51.h>

sfr lcd_data_port=0x90; /* P1 port as data port */

sbit rs=P2^0; /* Register select pin */

sbit rw=P2^1; /* Read/Write pin */

sbit en=P2^2; /* Enable pin */

void delay(unsigned int count) /* Function to provide delay Approx 1ms */

int i,j;

for(i=0;i<count;i++)

for(j=0;j<112;j++);

void LCD_Command (unsigned char cmd) /* LCD16x2 command funtion */


MLR INSTITUTE OF TECHNOLOGY 62
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

lcd_data_port= cmd;

rs=0; /* command reg. */

rw=0; /* Write operation */

en=1;

delay(1);

en=0;

delay(5);

void LCD_Char (unsigned char char_data) /* LCD data write function */

lcd_data_port=char_data;

rs=1; /* Data reg.*/

rw=0; /* Write operation*/

en=1;

delay(1);

en=0;

delay(5);

void LCD_String (unsigned char *str) /* Send string to LCD function */

int i;

for(i=0;str[i]!=0;i++) /* Send each char of string till the NULL */


MLR INSTITUTE OF TECHNOLOGY 63
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

LCD_Char (str[i]); /* Call LCD data write */

void LCD_String_xy (char row, char pos, char *str) /* Send string to LCD function */

if (row == 0)

LCD_Command((pos & 0x0F)|0x80);

else if (row == 1)

LCD_Command((pos & 0x0F)|0xC0);

LCD_String(str); /* Call LCD string function */

void LCD_Init (void) /* LCD Initialize function */

delay(20); /* LCD Power ON Initialization time >15ms */

LCD_Command (0x38); /* Initialization of 16X2 LCD in 8bit mode */

LCD_Command (0x0C); /* Display ON Cursor OFF */

LCD_Command (0x06); /* Auto Increment cursor */

LCD_Command (0x01); /* clear display */

LCD_Command (0x80); /* cursor at home position */

void main()

LCD_Init(); /* initialization of LCD*/


MLR INSTITUTE OF TECHNOLOGY 64
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

LCD_String("MLRIT ES LAB"); /* write string on 1st line of LCD*/

LCD_Command(0xC0);

LCD_String("Hello World"); /*write string on 2nd line*/

while(1); /* Infinite loop. */

Result:

ii) TITLE : SEVEN SEGMENT DISPLAY

MLR INSTITUTE OF TECHNOLOGY 65


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

AIM : TO INTERFACE THE SEVEN SEGMENTS DISPLAY WITH 8051 AMILY

IDE : KEIL

PROCEDURE:

1) In this Program PORT1 Is connected to the INTERFACE


2) Defined the delay function
3) Enter into while loop.
4) \GIVE VALUES TO A-Z and 0-9
5) This process is repeated continuously.

i. Write a Program to interface a Seven Segment led Display using 8051.


Solution:
#include<reg51.h>

void msdelay(unsigned int time) // Function for creating delay in milliseconds.

unsigned i,j ;

for(i=0;i<time;i++)

for(j=0;j<1275;j++);

void main()

unsigned char
no_code[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90}; //Array for
hex values (0-9) for common anode 7 segment

int k;

while(1)

MLR INSTITUTE OF TECHNOLOGY 66


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

for(k=0;k<10;k++)

P2=no_code[k];

msdelay(100);

PROGRAM-6

EXP:6 : Simple assembly program using ARM

AIM : Simple assembly program for addition, subtraction, multiplication, division.

ARM FAMILY: LPC2148

IDE : KEIL

i) Simple assembly program for addition, subtraction, multiplication, division.

Addition

AREA ADD, CODE, READONLY


ENTRY
START
MOV R1,#23
MOV R2,#23
ADD R3,R2,R1
END
SUBSTRACTION

AREA ADD, CODE, READONLY

MLR INSTITUTE OF TECHNOLOGY 67


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

ENTRY
START
MOV R1,#23
MOV R2,#23
SUB R3,R2,R1
END

MULTIPLICATION:

AREA ADD, CODE, READONLY


ENTRY
START
MOV R1,#23
MOV R2,#23
MUL R3,R2,R1

END

PROGRAM-7

EXP:7 Interface a simple Switch and display its status through Relay, Buzzer and LED
using ARM.
#include<lpc214x.h>
void delay();
void main()
{
IO0DIR |=0Xffffffff; //Port 0 is now acting as a output pin
IO1DIR = 0x00000000; //Port 1 is now acting as a input pin
while(1)
{
if((IO1PIN & (1<<16)) ==0) //Checking 16th pin of Port 1
{
IOSET0 |=0Xffffffff; //Port 0's all pins are high now (LED is glowing)
}
else
{
IOCLR0 |=0Xffffffff; //Port 0's all pins are low now (LED is OFF)
}
}
}

MLR INSTITUTE OF TECHNOLOGY 68


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-8

EXP:8 Interface a Stepper motor (or) DC motor and rotate it in clockwise and anti-clockwise
direction using ARM .

TITLE : Stepper motor (or) DC motor program using ARM

AIM : Write a program to control and Interface Stepper motor using LPC2148 ARM
microcontroller. Demonstrate simulation of motor interfacing using schematic representation in
Proteus software.
Apparatus required
LPC2148 ARM microcontroller
KIEL SOFTWARE
Proteus software (Schematic drawing)
Mention all the names selected in Proteus schematic:
●LPC2148
MLR INSTITUTE OF TECHNOLOGY 69
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

●ULN2003A
●STEPPER MOTOR ANIMATED UNIPOLAR
Theory:
1. Stepper motor is a brushless DC motor that divides the full rotation angle of360° into
number of equal steps.
2. The motor is rotated by applying a certain sequence of control signals. Thespeed of
rotation can be changed by changing the rate at which the control signalsare applied.
3. Various stepper motors with different step angles and torque ratings are available in the
market.
4. Microcontroller can be used to apply different control signals to the motor to make it
rotate according to the need of the application.
5. For more information about Stepper Motor and how to use it, refer thetopic Stepper
Motor in the sensors and modules section.Step angle is the minimum angle that stepper
motor will cover within one move/step. Number of steps required to complete one
rotation depends upon step angle. E.g.If step angle is of 45° then 8 steps are required to
complete one rotation.Basic specifications of configuring registers and IO details if used
in program
6. Rotating stepper motor in clockwise and counter clockwise directions alternately.
7. Here, we are using six wire unipolar stepper motor. Only four wires are required to
control this stepper motor. The two center tap wires of the stepper motor are connected
to 5V supply.
8. Controlling a stepper motor using LPC2148 Development Board. It worksby turning
ON & OFF a four I/O port lines generating at a particular frequency.
9. The ARM7 LPC2148 Development Board has four numbers of I/O port lines, connected
with I/O Port lines (P1.16 – P1.19) to rotate the stepper motor. ULN2803 is used as a
driver for port I/O lines, drivers output connected to steppermotor, connector provided
for external power supply if needed

Progarm

MLR INSTITUTE OF TECHNOLOGY 70


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

i) Write an Embedded c program to a Stepper motor rotate it in clockwise and anti-clockwise


direction using ARM .

#include<lpc214x.h>
void delay()
{
unsigned int i;
for(i=0;i<80000;i++);
}
int main()
{
unsigned char arr1[4]={ 0x00000001,0x00000002,0x00000004,0x00000008};
unsigned char arr2[4]={ 0x00000008,0x00000004,0x00000002,0x00000001};
unsigned int x,y,w;
IO0DIR |=0x0000000F;
IO0CLR =0x0000000F;
while(1)
{
for(x=0;x<13;x++)
{
for(y=0;y<4;y++)
{
IO0SET = arr1[y];
delay();
IO0CLR =0x0000000F;

}
}

MLR INSTITUTE OF TECHNOLOGY 71


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

for(w=0;w<13;w++)
{
for(y=0;y<4;y++)
{
IO0SET =arr2[y];
delay();
IO0CLR =0x0000000F;

}
}
}
}

Task :
i) Write an Embedded c program to a DC motor rotate it in clockwise and anti-clockwise
direction using ARM .
Result:

MLR INSTITUTE OF TECHNOLOGY 72


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

MLR INSTITUTE OF TECHNOLOGY 73


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-9

EXP:9. Display Hello World message using Internal UART

TITLE: UART in LPC2148


AIM : Write a program to Display Hello World message using Internal UART.
Apparatus required
LPC2148 ARM microcontroller
KIEL SOFTWARE
Proteus software (Schematic drawing)

i) Write a program to Display Hello World message using Internal UART


#include <lpc214x.h>
void initClocks(void);
void initUART0(void);
void U0Write(char data);
void Send_String(char* StringPtr);
char String[]="Hello from BINARYUPDATES.COM !!! \n\r\n";
unsigned int delay;
int main(void)

MLR INSTITUTE OF TECHNOLOGY 74


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

{
initClocks(); // Set CCLK=60Mhz and PCLK=60Mhz
initUART0();
while(1)
{
Send_String(String); //Pass the string to the USART_putstring function and sends it over the serial
for(delay=0; delay<500000; delay++); // delay
}
}
void initUART0(void)
{
PINSEL0 = 0x5; /* Select TxD for P0.0 and RxD for P0.1 */
U0LCR = 0x83; /* 8 bits, no Parity, 1 Stop bit | DLAB set to 1 */
U0DLL = 110;
U0DLM = 1;
U0FDR = 0xF1; /* MULVAL=15(bits - 7:4) , DIVADDVAL=0(bits - 3:0)*/
U0LCR &= 0x0F; // Set DLAB=0 to lock MULVAL and DIVADDVAL
//BaudRate is now ~9600 and we are ready for UART communication!
}
void U0Write(char data)
{
while (!(U0LSR & (1<<5))); // wait till the THR is empty
// now we can write to the Tx FIFO
U0THR = data;
}
void initClocks(void)
{
PLL0CON = 0x01; //Enable PLL
PLL0CFG = 0x24; //Multiplier and divider setup
PLL0FEED = 0xAA; //Feed sequence
PLL0FEED = 0x55;
while(!(PLL0STAT & 0x00000400)); //is locked?
PLL0CON = 0x03; //Connect PLL after PLL is locked
PLL0FEED = 0xAA; //Feed sequence
PLL0FEED = 0x55;
VPBDIV = 0x01; // PCLK is same as CCLK i.e.60 MHz
}
void Send_String(char* StringPtr){
while(*StringPtr != 0x00){
U0Write(*StringPtr);
StringPtr++;}
}

MLR INSTITUTE OF TECHNOLOGY 75


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PART-B:
MICROPYTHON
Introduction to ESP32
 ESP32 is a powerful device for IOT development with WIFI & Bluetooth.Compared to
NodeMCU it has more ADC pins , DAC & much more.
 ESP32 can be programmed by many ways including Arduino core.
 This post is on programming ESP32 using MICROPYTHON.
 MicroPython is a lean and fast implementation of the Python3 programming language
that is optimised to run on a microcontroller.
 MicroPython has advantages over traditional programming software such as C/C++
because it is essentially a live development environment and write and debug code much
faster…in fact 5-10 times faster than C++.
 When a device boots up using Micro-Python it does not consume much memory and thus
doesn’t incur current drain. Micro-python also has a number of Micropython specific
libraries for accessing hardware level features.
 Adafruit also introduced CircuitPython ,Soon after MicroPython started picking up the
pace. However, Circuit Python offers support for the Adafruit range of hardware only.

MicroPython is a re-implementation of Python 3 targeted for microcontrollers and embedded


systems. MicroPython is very similar with regular Python.

MLR INSTITUTE OF TECHNOLOGY 76


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

OTHER PLATFORM

MLR INSTITUTE OF TECHNOLOGY 77


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Arduino platform offers open source hardware and software that is easy to use and is used widely
for hobby projects and prototyping.

Open Source?

When it is said that Arduino is an open source platform, it means that all the information
regarding the hardware and software that Arduino provides is freely available and can be used by
anyone. They provide the designs for their hardware and software which can be used by anyone.
Anyone can use these designs to manufacture the hardware and can distribute the software, no
licenses are required.

Why Arduino?

 Arduino provides many types of boards which are useful for various applications.

 Arduino also provides its own IDE (Integrated Development Environment) which is free
to download from Arduino’s website and use.

 Many libraries are provided with the software and a large number of libraries developed
by people from around the world are available for free. The functions implemented in
these libraries can be used for quick development purposes.

 This allows the user to use certain interfaces or modules without having in depth
knowledge about the internal structure or working.

 The point is that lack of technical or coding knowledge should not become an obstacle
for development or creative thinking.

 They also offer a number of expansion boards (or shields as they call them) which can
be plugged into their boards and used.

 All of these enable fast and easy development.

Arduino Boards

A wide range of boards is manufactured by Arduino. These have different sizes, different
microcontrollers, and different processing capabilities. There are entry level boards like the
UNO, LEONARDO, NANO etc; boards with enhanced feature like the MEGA, PRO, ZERO etc;
boards for Internet of Things like the YUN, TIAN etc; and wearable boards like the LILYPAD,
GEMMA etc.

Arduino: It is probably the best starting point for embedded based IOT. Based Arduino Boards
don’t come with Ethernet shield or Wi-Fi shield and for Arduino to be able to work as IOT

MLR INSTITUTE OF TECHNOLOGY 78


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

device, their need to select Arduino with Ethernet shield or Wi-Fi shield. Arduino run on the
other hand is a board that comes ported with Ethernet shield.
Design and Develop the following programs using ARDUINO UNO OR /
ESP8266(NODEMCU) /ESP32.

Experiments -1

MLR INSTITUTE OF TECHNOLOGY 79


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

1. Introduction to ARDUINO and Micro-Python with THONNY IDE software installation


DOWNLOAD IDE s
As a programming environment, many IDE s are available, of which THONNY IDE is simple &
powerful.
Thonny IDE : An integrated development environment (IDE– Integrated Development
Environment) for Python that is designed for beginners. It stands out for its simplicity of
installation and use, ease of writing and debugging of code.
Download software
https://thonny.org/ & download the installer relevant for (available for Windows,Mac & Linux)

1. Install THONNY IDE by double clicking the downloaded installer.

MLR INSTITUTE OF TECHNOLOGY 80


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

2. Open THONNY IDE .


 The top portion is the EDITOR where you write your Micropython code.
 Bottom is the SHELL.
 As we’ve not yet installed Micropython interpreter, the Shell displays the default Python
prompt.
 ‘>>>’ is the prompt of the interactive Python interpreter, meaning that the interpreter is
ready to get Python statements typed in.

MLR INSTITUTE OF TECHNOLOGY 81


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

MICROPYTHON PROMPT
1. To get the Micropython prompt, click on Tools –> Options

2. Under options window click on INTERPRETER.

MLR INSTITUTE OF TECHNOLOGY 82


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Under first drop down menu select MICROPYTHON (ESP32)


 Under Port , select the port number where ESP32 is connected.
 Click on Firmware install bar.

r
3. Micropython firmware .bin file can be downloaded from
 http://micropython.org/download
 Under ESP32 select the GENERIC .bin file & download it.
 http://micropython.org/resources/firmware/esp32-idf3-20200209-v1.12-154-
gce40abcf2.bin

MLR INSTITUTE OF TECHNOLOGY 83


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Now , from the Thonny install firmware window , click browse and locate the downloaded .bin
file.

Click on install button to start the firmware installation.


4. You need to press & hold the BOOT button on ESP32 module for a moment.

 You may get an error stating ESPTOOL is not installed.


 From within Thonny IDE itself you can install it.
 Click Tools –> Manage Plug ins..

MLR INSTITUTE OF TECHNOLOGY 84


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

5. Under plug in window search for esptool & install it.

Now if you install firmware , you can see the writing starts at location 0x1000

MLR INSTITUTE OF TECHNOLOGY 85


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

6. Once the firmware is installed you can see the Micropython prompt under SHELL.

MLR INSTITUTE OF TECHNOLOGY 86


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

You can type in help() to see a list of python commands to access modules ,network, etc..

 help(“modules”)
 displays the list of modules available.

MLR INSTITUTE OF TECHNOLOGY 87


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

machine, uos, esp , time , network are some of the frequently used modules.

MLR INSTITUTE OF TECHNOLOGY 88


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

7. To control an LED on / off, the following must be done:


 First, the Pin class of the machine module is imported , which allows controlling
the inputs / outputs (General Purpose Input / Output – GPIO -) of the microcontroller –
and therefore, of its corresponding pins on the board. Since pin 02 ( GPIO 02 ) is
connected to the integrated LED.

 Then an object that we will call pin_02 is initialized to identify it, turning GPIO 02 “2”
into an output pin “ Pin.OUT ”.

MLR INSTITUTE OF TECHNOLOGY 89


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

t
Now led.value(1) makes the on board LED ON.
led.value ( 0) makes it OFF.
We have controlled the LED from Interpreter. Now we shall write the complete code in the
EDITOR Section to blink the LED repeatedly.
Here we make use of the sleep class of time function to introduce delay.
Never ending loop is created using
while True:
Notice the loop starts by colon : & instead of braces micropython uses indentation.

MLR INSTITUTE OF TECHNOLOGY 90


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Click File –> Save as


& select Micropython device

MLR INSTITUTE OF TECHNOLOGY 91


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Provide the file name as main.py


 by default already boot.py is available on device.
 Micropython will first execute boot.by & then looks out to execute file named main.py.
 So you cannot upload file in other name to execute. If you use some other name , then the
file will be executed once. After power reboot it will not execute.

MLR INSTITUTE OF TECHNOLOGY 92


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Once the file is stored click on F5 or the Run green button.

MLR INSTITUTE OF TECHNOLOGY 93


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

The script is uploaded and the on board LED blinks.


To stop execution you can press the STOP Red button.
Now the chevrons >>> appear at the shell.
You can write new code & save it to device , again in the name main.py.
This is how to upload new code.

MLR INSTITUTE OF TECHNOLOGY 94


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

MLR INSTITUTE OF TECHNOLOGY 95


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM - 2
EXP:2 Creating different led patterns and controlling them using push button switches
using ESP32 with micro-python .

AIM:

To develop the program blinks the led different patterns and controlling them using
push button using Esp8266 or ESP32

COMPONENTS
1. DOIT ESP32 DevKit v1 (1)
2. An LED (1)
3. 330 Ohm Resistor (1)
4. Jumper wires
5. Breadboard (1)

Circuit diagram

Program sketch
Creating different led patterns
i) One LEDs using ESP32

from machine import Pin

from time import sleep

MLR INSTITUTE OF TECHNOLOGY 96


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

led = Pin(2, Pin.OUT)

while True:

led.high()

sleep(0.5)

led.low()

sleep(0.5)
ii) Three LEDs using ESP32
from machine import Pin
from time import sleep
led_13 = Pin(13, Pin.OUT)
led_14 = Pin(14, Pin.OUT)
led_12 = Pin(12, Pin.OUT)

while True:
led_12.value(0)
led_13.value(1)
led_14.value(0)
sleep(0.5)
led_12.value(1)
led_13.value(0)
led_14.value(0)
sleep(0.5)
led_12.value(0)
led_13.value(0)
led_14.value(1)
sleep(0.5)
iii) Control the led using push button or switches using ESP32

MLR INSTITUTE OF TECHNOLOGY 97


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Program sketch
from machine import Pin
from time import sleep

led = Pin(14, Pin.OUT) # 22 number in is Output


push_button = Pin(13, Pin.IN) # 23 number pin is input

while True:

logic_state = push_button.value()
if logic_state == True: # if pressed the push_button
led.value(1) # led will turn ON
else: # if push_button not pressed
led.value(0)

3. Calculate the distance of an object with the help of an ultrasonic sensor and display it on
an LCD using esp32

AIM:

To develop the program to calculate the distance of an object with the help of an
ultrasonic sensor and display it on an LCD .
COMPONENTS

• ESP8266 NODEMCU board

MLR INSTITUTE OF TECHNOLOGY 98


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

• Ultra Sonic HC-SR04


• LCD
• Jumper wires
• Breadboard
• USB Cable
Theory

The working principle Ultra Sonic HC-SR04


The Ultra Sonic HC-SR04 emits ultrasound at 40,000Hz that travels in the air. If there is
an object or obstacle in its path, then it collides and bounces back to the Ultra Sonic module.

The formula distance = speed*time is used to calculate the distance.

Suppose, an object is placed at a distance of 10 cm away from the sensor, the speed of sound in
air is 340 m/s or 0.034 cm/µs. It means the sound wave needs to travel in 294 µs. But the Echo
pin double the distance (forward and bounce backward distance). So, to get the distance in cm
multiply the received travel time value with echo pin by 0.034 and divide it by 2.

The distance between Ultra Sonic HC-SR04 and an object is:

MLR INSTITUTE OF TECHNOLOGY 99


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Circuit diagram:

Program :

import machine
import time
from hcsr04 import HCSR04
from machine import I2C
from pico_i2c_lcd import I2cLcd

# Define ultrasonic sensor pins


TRIG_PIN = 14
ECHO_PIN = 15

MLR INSTITUTE OF TECHNOLOGY 100


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

# Define LCD configuration


I2C_ADDR = 0x27 # Address of your I2C LCD module
I2C_NUM = 1 # I2C bus number (1 for ESP32)
I2C_FREQ = 400000 # I2C bus frequency (400 kHz)

# Initialize ultrasonic sensor


sensor = HCSR04(trigger_pin=TRIG_PIN, echo_pin=ECHO_PIN)

# Initialize I2C for LCD


i2c = I2C(I2C_NUM, freq=I2C_FREQ)
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16) # Adjust the dimensions if your LCD is different

try:
while True:
# Read distance from ultrasonic sensor
distance_cm = sensor.distance_cm()

# Display distance on the LCD


lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Distance: {:.2f} cm".format(distance_cm))

time.sleep(1) # Update every 1 second

except KeyboardInterrupt:
pass
finally:
lcd.clear()

II) led with ultrasonic sensor


import machine
import time
from hcsr04 import HCSR04

# Define ultrasonic sensor pins


TRIG_PIN = 14
ECHO_PIN = 15

# Define LED pin


LED_PIN = 2

# Initialize ultrasonic sensor


sensor = HCSR04(trigger_pin=TRIG_PIN, echo_pin=ECHO_PIN)
MLR INSTITUTE OF TECHNOLOGY 101
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

# Initialize LED
led = machine.Pin(LED_PIN, machine.Pin.OUT)

try:
while True:
# Read distance from ultrasonic sensor
distance_cm = sensor.distance_cm()

# Control LED based on distance


if distance_cm < 10:
led.on()
else:
led.off()

# Print distance to the console


print("Distance: {:.2f} cm".format(distance_cm))

time.sleep(1) # Update every 1 second

except KeyboardInterrupt:
pass
finally:
led.off() # Turn off the LED when the program ends

MLR INSTITUTE OF TECHNOLOGY 102


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM-4

EXP:4 (a)Controlling relay state based on ambient light levels using LDR sensor.
(b)Basic Burglar alarm security system with the help of PIR sensor and buzzer

1. Interface led and IR (infrared) and PIR Sensor with ESP8266

AIM:

To develop the program determines the distance of an object using IR sensor.


COMPONENTS

• ARDUINO Uno board


• IR Sensor
• 5mm LED
• 330 ohm or 220 ohm resistor
• Jumper wires
• Breadboard
• USB Cable

Circuit diagram

MLR INSTITUTE OF TECHNOLOGY 103


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Program sketch

int led =13;


int irsensor = 10;

void setup()
{
pinMode(led, OUTPUT);
pinMode(irsensor, INPUT);

}
void loop()
{
if(digitalRead(irsensor)==0)
{
digitalWrite(led, HIGH);
}
else
{
digitalWrite(led, LOW);
}
}
Tasks
1. Develop a circuit to count number of visitors in to a room using IR sensors.

2. Develop a circuit to alert the buzzer when a visitor enters the room.

3. Develop a circuit to switch on the lights automatically when a person enters


the room using PIR sensor

b) Interface LDR Sensor with ESP8266

AIM:
Develop the program to display light intensity using LDR sensor.

COMPONENTS

 ESP8266 board
 LDR
 5mm LED or 5V buzzer
 330 ohm or 220 ohm resistor
 Jumper wires
MLR INSTITUTE OF TECHNOLOGY 104
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

 Breadboard
 USB Cable

Circuit diagram

Interface LDR sensor with arduino

// write a program print the value in serial monitor using ldr int LDR = A0;
int input_val = 0;
void setup()
{
Serial.begin(115200);
}
void loop()
{
input_val = analogRead(LDR);
Serial.print("LDR Value is: ");
Serial.println(input_val);

MLR INSTITUTE OF TECHNOLOGY 105


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

delay(1000);
}

PROGRAM-5

EXP:5 Store humidity & temperature data to Thing Speak, periodically logging ambient light
level to Thing Speak.

MLR INSTITUTE OF TECHNOLOGY 106


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

AIM:

To develop the program d Store humidity & temperature data in Thing Speak .
COMPONENTS

• ESP8266 board
• humidity Sensor
• 5mm LED
• 330 ohm or 220 ohm resistor
• Jumper wires
• Breadboard
• USB Cable

Circuit diagram

#include <DHT.h> // Including library for dht

#include <ESP8266WiFi.h>

String apiKey = "J4KDQLEBLEZZ8UCX"; // Enter your Write API key from ThingSpeak

MLR INSTITUTE OF TECHNOLOGY 107


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

const char *ssid = "wifi"; // replace with your wifi ssid and wpa2 key
const char *pass = "12341234";
const char* server = "api.thingspeak.com";

#define DHTPIN 0 //pin where the dht11 is connected

DHT dht(DHTPIN, DHT11);

WiFiClient client;

void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();

Serial.println("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)


{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

void loop()
{

float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}

MLR INSTITUTE OF TECHNOLOGY 108


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com


{

String postStr = apiKey;


postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();

Serial.println("Waiting...");

// thingspeak needs minimum 15 sec delay between updates


delay(1000);
}

MLR INSTITUTE OF TECHNOLOGY 109


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Result

MLR INSTITUTE OF TECHNOLOGY 110


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

PROGRAM -6

EXP:6 Introduction to HTTP. Hosting a basic server from the ESP32 to control various
digital based actuators (led, buzzer, relay) from a simple web page.
AIM: Hosting a basic server from the ESP32 to control various digital based actuators (led,
buzzer, relay) from a simple web page.
Component Requirement:
1) led, buzzer, relay
2) NodeMCU
3) Jumper Wire
4) USB Cable

Software:
5) Arduino IDE
6) tinkercad
7) wokwi

Program
Write a program to Build NodeMCU Webserver and control an LED from a Webpage

#include <ESP8266WiFi.h>

#define gpio4LEDPin 4 /* One LED connected to GPIO4 - D2 */


#define gpio5LEDPin 5 /* One LED connected to GPIO5 - D1 */

const char* ssid = "wifi"; /* Add your router's SSID */


const char* password = "12341234"; /*Add the password */

int gpio4Value;
int gpio5Value;

WiFiServer espServer(80); /* Instance of WiFiServer with port number 80 */


/* 80 is the Port Number for HTTP Web Server */

void setup()
{
Serial.begin(115200); /* Begin Serial Communication with 115200 Baud Rate */
/* Configure GPIO4 and GPIO5 Pins as OUTPUTs */
pinMode(gpio4LEDPin, OUTPUT);
pinMode(gpio5LEDPin, OUTPUT);
/* Set the initial values of GPIO4 and GPIO5 as LOW*/
/* Both the LEDs are initially OFF */

MLR INSTITUTE OF TECHNOLOGY 111


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

digitalWrite(gpio4LEDPin, LOW);
digitalWrite(gpio5LEDPin, LOW);

Serial.print("\n");
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA); /* Configure ESP8266 in STA Mode */
WiFi.begin(ssid, password); /* Connect to Wi-Fi based on above SSID and Password */
while(WiFi.status() != WL_CONNECTED)
{
Serial.print("*");
delay(500);
}
Serial.print("\n");
Serial.print("Connected to Wi-Fi: ");
Serial.println(WiFi.SSID());
delay(100);
/* The next four lines of Code are used for assigning Static IP to ESP8266 */
/* Do this only if you know what you are doing */
/* You have to check for free IP Addresses from your Router and */
/* assign it to ESP8266 */
/* If you are confirtable with this step, please un-comment the next four lines *
/* if not, leave it as it is and proceed */
//IPAddress ip(192,168,1,6);
//IPAddress gateway(192,168,1,1);
//IPAddress subnet(255,255,255,0);
//WiFi.config(ip, gateway, subnet);
//delay(2000);
Serial.print("\n");
Serial.println("Starting ESP8266 Web Server...");
espServer.begin(); /* Start the HTTP web Server */
Serial.println("ESP8266 Web Server Started");
Serial.print("\n");
Serial.print("The URL of ESP8266 Web Server is: ");
Serial.print("http://");
Serial.println(WiFi.localIP());
Serial.print("\n");
Serial.println("Use the above URL in your Browser to access ESP8266 Web Server\n");
}

void loop()
{
WiFiClient client = espServer.available(); /* Check if a client is available */
if(!client)
MLR INSTITUTE OF TECHNOLOGY 112
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

{
return;
}

Serial.println("New Client!!!");

String request = client.readStringUntil('\r'); /* Read the first line of the request from client */
Serial.println(request); /* Print the request on the Serial monitor */
/* The request is in the form of HTTP GET Method */
client.flush();

/* Extract the URL of the request */


/* We have four URLs. If IP Address is 192.168.1.6 (for example),
* then URLs are:
* 192.168.1.6/GPIO4ON and its request is GET /GPIO4ON HTTP/1.1
* 192.168.1.6/GPIO4OFF and its request is GET /GPIO4OFF HTTP/1.1
* 192.168.1.6/GPIO5ON and its request is GET /GPIO5ON HTTP/1.1
* 192.168.1.6/GPIO4OFF and its request is GET /GPIO5OFF HTTP/1.1
*/
/* Based on the URL from the request, turn the LEDs ON or OFF */
if (request.indexOf("/GPIO4ON") != -1)
{
Serial.println("GPIO4 LED is ON");
digitalWrite(gpio4LEDPin, HIGH);
gpio4Value = HIGH;
}
if (request.indexOf("/GPIO4OFF") != -1)
{
Serial.println("GPIO4 LED is OFF");
digitalWrite(gpio4LEDPin, LOW);
gpio4Value = LOW;
}
if (request.indexOf("/GPIO5ON") != -1)
{
Serial.println("GPIO5 LED is ON");
digitalWrite(gpio5LEDPin, HIGH);
gpio5Value = HIGH;
}
if (request.indexOf("/GPIO5OFF") != -1)
{
Serial.println("GPIO5 LED is OFF");
digitalWrite(gpio5LEDPin, LOW);
gpio5Value = LOW;
}
MLR INSTITUTE OF TECHNOLOGY 113
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

/* HTTP Response in the form of HTML Web Page */


client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(); // IMPORTANT
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
/* CSS Styling for Buttons and Web Page */
client.println("<style>");
client.println("html { font-family: Courier New; display: inline-block; margin: 0px auto; text-
align: center;}");
client.println(".button {border: none; color: white; padding: 10px 20px; text-align: center;");
client.println("text-decoration: none; font-size: 25px; margin: 2px; cursor: pointer;}");
client.println(".button1 {background-color: #13B3F0;}");
client.println(".button2 {background-color: #3342FF;}");
client.println("</style>");
client.println("</head>");

/* The main body of the Web Page */


client.println("<body>");
client.println("<h2>ESP8266 Web Server</h2>");

if(gpio4Value == LOW)
{
client.println("<p>GPIO4 LED Status: OFF</p>");
client.print("<p><a href=\"/GPIO4ON\"><button class=\"button button1\">Click to turn
ON</button></a></p>");
}
else
{
client.println("<p>GPIO4 LED Status: ON</p>");
client.print("<p><a href=\"/GPIO4OFF\"><button class=\"button button2\">Click to turn
OFF</button></a></p>");
}

if(gpio5Value == LOW)
{
client.println("<p>GPIO5 LED Status: OFF</p>");
client.print("<p><a href=\"/GPIO5ON\"><button class=\"button button1\">Click to turn
ON</button></a></p>");
MLR INSTITUTE OF TECHNOLOGY 114
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

}
else
{
client.println("<p>GPIO5 LED Status: ON</p>");
client.print("<p><a href=\"/GPIO5OFF\"><button class=\"button button2\">Click to turn
OFF</button></a></p>");
}

client.println("</body>");
client.println("</html>");
client.print("\n");

delay(1);
/* Close the connection */
client.stop();
Serial.println("Client disconnected");
Serial.print("\n");
}

i) Write a program to Build NodeMCU Webserver and measure an LM35 from a Webpage

#include <ESP8266WiFi.h>
const char* ssid = "wifi"; // Your ssid
const char* password = "12341234"; // Your Password
float temp_celsius = 0;
float temp_fahrenheit = 0;
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
pinMode(A0, INPUT);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi is connected");
server.begin();
MLR INSTITUTE OF TECHNOLOGY 115
DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Serial.println("Server started");
Serial.println(WiFi.localIP());
}
void loop() {
temp_celsius = (analogRead(A0) * 330.0) / 1023.0; // To convert analog values to Celsius We
have 3.3 V on our board and we know that output voltage of LM35 varies by 10 mV to every
degree Celsius rise/fall. So , (A0*3300/10)/1023 = celsius
temp_fahrenheit = celsius * 1.8 + 32.0;
Serial.print(" Temperature = ");
Serial.print(temp_celsius);
Serial.print(" Celsius, ");
Serial.print(temp_fahrenheit);
Serial.println(" Fahrenheit");
WiFiClient client = server.available();
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the
esponse
client.println("Refresh: 10"); // update the page after 10 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("<p style='text-align: center;'><span style='font-size: x-large;'><strong>Digital
Thermometer</strong></span></p>");
client.print("<p style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size:
large;'>Temperature (*C)= ");
client.println(temp_celsius);
client.print("<p style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size:
large;'>Temperature (F) = ");
client.println(temp_fahrenheit);
client.print("</p>");
client.println("</html>");
delay(5000);
}

MLR INSTITUTE OF TECHNOLOGY 116


DEPARTMENT OF ECE EMBEDDED AND IOT LAB

Result :

MLR INSTITUTE OF TECHNOLOGY 117

You might also like