E and IOT LAB Usermanual - MLR 20 With M - Python
E and IOT LAB Usermanual - MLR 20 With M - Python
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
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
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.
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
Fig 1.0
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!!
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
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")
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.
Fig 1.7
Fig 4.1
µVision3 helps expedite the development process of your embedded applications by providing
the following:
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.
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.
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
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.
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.
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.
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.
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.
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
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.
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
µ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.
Fig 4.3
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.
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.
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.
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.
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.
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
Fig 5.2
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.
Fig 5.6
Keil uVision2.lnk
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.
As soon as you save the file name, automatically a window “Select device for Target
‘Target 1’ ” is opened.
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.
Default Setting
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
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.
8. 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.
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
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.
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
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).
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.
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
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.
/**********************************************************************/
PPROGRAM-1
TITLE : Program To Toggle All The Bits Of Port P1 Continuously With 250 ms Delay
PROCEDURE:
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
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
PROGRAM-2
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.
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
}
}
/**********************************************************************/
RESULT
Task :
PROGRAM-3
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
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:
#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:
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:
Viva Questions:
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.
PROGRAM-4
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.
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:
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:
Viva Questions:
PROGRAM-5
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). Write an Embedded C program to display the Message at port 1 on the 16x2 lcd
display?
Solution:
#include<reg51.h>
int i,j;
for(i=0;i<count;i++)
for(j=0;j<112;j++);
lcd_data_port= cmd;
en=1;
delay(1);
en=0;
delay(5);
lcd_data_port=char_data;
en=1;
delay(1);
en=0;
delay(5);
int i;
void LCD_String_xy (char row, char pos, char *str) /* Send string to LCD function */
if (row == 0)
else if (row == 1)
void main()
LCD_Command(0xC0);
Result:
IDE : KEIL
PROCEDURE:
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)
for(k=0;k<10;k++)
P2=no_code[k];
msdelay(100);
PROGRAM-6
IDE : KEIL
Addition
ENTRY
START
MOV R1,#23
MOV R2,#23
SUB R3,R2,R1
END
MULTIPLICATION:
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)
}
}
}
PROGRAM-8
EXP:8 Interface a Stepper motor (or) DC motor and rotate it in clockwise and anti-clockwise
direction 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
#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;
}
}
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:
PROGRAM-9
{
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++;}
}
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.
OTHER PLATFORM
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.
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
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
MICROPYTHON PROMPT
1. To get the Micropython prompt, click on Tools –> Options
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
Now , from the Thonny install firmware window , click browse and locate the downloaded .bin
file.
Now if you install firmware , you can see the writing starts at location 0x1000
6. Once the firmware is installed you can see the Micropython prompt under SHELL.
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.
machine, uos, esp , time , network are some of the frequently used modules.
Then an object that we will call pin_02 is initialized to identify it, turning GPIO 02 “2”
into an output pin “ Pin.OUT ”.
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.
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
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
Program sketch
from machine import Pin
from time import sleep
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
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.
Circuit diagram:
Program :
import machine
import time
from hcsr04 import HCSR04
from machine import I2C
from pico_i2c_lcd import I2cLcd
try:
while True:
# Read distance from ultrasonic sensor
distance_cm = sensor.distance_cm()
except KeyboardInterrupt:
pass
finally:
lcd.clear()
# Initialize LED
led = machine.Pin(LED_PIN, machine.Pin.OUT)
try:
while True:
# Read distance from ultrasonic sensor
distance_cm = sensor.distance_cm()
except KeyboardInterrupt:
pass
finally:
led.off() # Turn off the LED when the program ends
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
AIM:
Circuit diagram
Program sketch
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.
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
// 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);
delay(1000);
}
PROGRAM-5
EXP:5 Store humidity & temperature data to Thing Speak, periodically logging ambient light
level to Thing Speak.
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 <ESP8266WiFi.h>
String apiKey = "J4KDQLEBLEZZ8UCX"; // Enter your Write API key from ThingSpeak
const char *ssid = "wifi"; // replace with your wifi ssid and wpa2 key
const char *pass = "12341234";
const char* server = "api.thingspeak.com";
WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
Result
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>
int gpio4Value;
int gpio5Value;
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 */
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();
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);
}
Result :