Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

[M Rizwan Akram]

[2021-MC-293]

UNVERISTY OF ENGINEERING AND TECHNOLOGY


LAHORE FAISALABAD
EMBEDDED SYSTEM II LAB REPORTS

2021-MC-293

Name Muhammad Rizwan Akram

REG. No. 2021-MC-293

Section A

Subject Embedded System II

Department Mechatronics & Control Engineering

Submitted To Dr. Muhammd Usman

Department: Mechanical, Mechatronics, Manufacturing Engineering (FC)

1
[M Rizwan Akram]
[2021-MC-293]

Section Course Detail


Semester Fall 2023-2024
Department Mechanical, Mechatronics, and Manufacturing Engineering (FC)
Section A
Subject Title MCT-338L Embedded Systems-II
Subject Domain Engineering
Subject Knowledge -
Contact m.usman@uet.edu.pk

Measurable Student Learning Outcomes


CLOs Description PLOs Domain Domain Level
Design embedded systems for diverse
range of applications based on Serial
communication, interfaces and protocols
including SSI/SPI, I2C, CAN/Ethercat
CLO1 PLO-5 Psychomotor 2. Manipulation
Wireless communication including
Bluetooth and WiFi Input capture,
sampling, synchronization and data
acquisition techniques.
Skillfully demonstrate a solution as
individual/group in Lab sessions/Term
CLO2 PLO-6 Psychomotor 4. Articulation
Project.

To demonstrate the project handling


including use of time, resources, and skills
CLO3 PLO-11 Affective 4. Organizing
during its execution thus exhibiting it.

To effectively present and communicate


diverse concepts and designs for
CLO4 PLO-10 Affective 3. Valuing
experiments and projects utilizing
embedded systems.

Grading Policy
Lab Work 60 Marks (CLO1,CLO2, CLO3, CLO4)
Project Work 40 Marks (CLO1, CLO2, CLO3, CLO4)

2
[M Rizwan Akram]
[2021-MC-293]

Lab Plan
List of Experiments

Lab No. Description CLOs


Introduction to Microcontroller (Arduino UNO)
1. Introduction to microcontrollers (e.g., Arduino UNO)
2. Basic LED blinking using GPIO
CLO1,
Task: Digital Input and Output using GPIOs
Lab 1 CLO3,
 Connect a push-button switch to a digital pin and write a
CLO4
program to control an LED using the button press.
 When the button is pressed, the LED should turn on, and
when released, it should turn off.
Introduction to Microcontroller (Arduino UNO)
1. Dual Input Decision Maker CLO1,
Lab 2 Task: CLO3,
 To create a simple decision-making system based on CLO4
the states of two input switches.
Introduction to Microcontroller (ESP32)
1. ESP32 setup and testing
Task:
CLO1,
 Arduino IDE and ESP32 Board Package installed.
Lab 3 CLO3,
 Basic LED blinking using GPIO
CLO4
2. One switch and three LEDs (via transistor) connected to esp32.
 Write a program to show a binary data on LEDs from 0 to
7 whenever a switch is pressed.
Serial Communication using UART Control Systems CLO1,
Lab 4 1. To establish serial communication between two microcontrollers CLO3,
using UART and transmit/receive data. CLO4
Serial Communication using UART Control Systems
1. Design a simple application that utilizes UART communication for a CLO1,
Lab 5 specific purpose. CLO3,
 Reading the 4 switches state attached to Arduino UNO and CLO4
send serially to esp32 to show the information on LEDs
Data Acquisition using ADC Interfacing
1. Data acquisition using analog sensors (Temperature sensor Ky-028) CLO1,
Lab 6  Synchronization of sensor data and displaying on serial CLO3,
monitor CLO4

Input Capture and Data Acquisition Techniques


CLO1,
1. Data acquisition using analog sensors (e.g., temperature sensor)
Lab 7 CLO3,
2. Data sampling using timers’ interrupt in ESP32.
CLO4
 Sampling and resolution of ADC
Texas Instruments Cortex-M controller GPIO Interfacing
CLO1,
1. Introduction to TM4C123x (TIVA C series) microcontroller
Lab 8 CLO3,
2. Installing Energia IDE & blinky example code
CLO4
3. Installing Keil IDE & blinky example code

3
[M Rizwan Akram]
[2021-MC-293]

Mid Term Exam


Input Capture and Period Measurement of a Pulse
CLO1,
1. Introduction to Capture Module in TM4C123x (TIVA C series)
Lab 9 CLO3,
2. Period measurement on the TM4C123x
CLO4
3. Example Code

UART Communication of the TM4C123 and Tera Term Serial Monitor


CLO1,
1. Introduction to UART module of TM4C123x
Lab 10 CLO3,
2. Tera Term installation and configuration
CLO4
3. Example Code

DC motor interfacing with ESP32 Microcontroller (Open Loop Control)


1. Introduction to inductive loads & PWM module CLO1,
Lab 11 2. To interface a DC motor with the TM4C microcontroller and open CLO3,
loop control of its speed using a potentiometer connected to an CLO4
analog pin.

DC motor interfacing with ESP32 Microcontroller (Closed Loop Control)


CLO1,
1. Introduction to optical encoder and capture mode to measure speed
Lab 12 CLO3,
of DC motor.
CLO4
2. Implementing PID algorithm to control the speed of DC motor.

Case Studies and Embedded System Design Cycle


1. Implementing a case study project from scratch (e.g., temperature CLO1,
Lab 13-14 monitoring system with wireless communication and control) CLO3,
2. Integrating sensors, communication, control, and RTOS CLO4
3. Finalizing the project for deployment

Review and project showcase CLO1,


Lab 15-16 1. Review of key concepts and experiments CLO3,
2. Student presentations showcasing their case study projects CLO4

End Term Exam

4
[M Rizwan Akram]
[2021-MC-293]

Lab # 01
Introduction to Microcontrollers (Arduino UNO)
Objective:
1. Introduction to microcontrollers (e.g., Arduino UNO)
2. Basic LED blinking using GPIO

Apparatus:
1. Arduino UNO board
2. LED
3. Resistor (220-330 ohms)
4. Breadboard
5. Jumper wires

Theory:
1. Microcontrollers Overview:
A microcontroller is a compact integrated circuit that combines a processor (CPU), memory
(RAM and ROM), input/output peripherals, and other supporting components. It is designed to
execute specific tasks and is commonly used in embedded systems, automation, and control
applications. Microcontrollers are widely employed in various electronic devices, ranging from
simple household appliances to complex industrial machinery.

2. Arduino UNO:
Arduino UNO is a popular microcontroller board based on the ATmega328P microcontroller.
Developed by the Arduino company, it provides a user-friendly platform for programming and
prototyping electronic projects. The Arduino UNO board consists of digital and analog
input/output pins, a USB interface for programming and power, and a power jack for an external
power supply. Its open-source nature and extensive community support make it an excellent
choice for both beginners and experienced developers.
GPIO (General Purpose Input/Output):
GPIO pins on a microcontroller serve as versatile interfaces that can be configured as either
inputs or outputs. Digital pins configured as outputs can provide electrical signals (high or low
voltage), while those configured as inputs can read external signals.
LED (Light Emitting Diode):
An LED is a semiconductor device that emits light when an electric current passes through it.
LEDs are commonly used as indicators in electronic circuits. To control an LED using a
microcontroller, a digital output pin is used to toggle the LED's state (ON or OFF).

5
[M Rizwan Akram]
[2021-MC-293]

Apparatus:
Arduino UNO:

Led: Register:

Bread Board: Jumper Wires:

6
[M Rizwan Akram]
[2021-MC-293]

Procedure:
1. Connect the longer leg of the LED (anode) to a digital output pin on the Arduino (e.g.,
Pin 13).
2. Connect the shorter leg of the LED (cathode) to the ground (GND) on the Arduino
through a current-limiting resistor.
3. Open the Arduino IDE on your computer.
4. Write a simple program to turn the LED on and off in a repeating pattern.
5. Upload the program to the Arduino board.

Arduino Code:
 const int buttonPin = 2;
 const int ledPin = 13;
 void setup() {
 pinMode(buttonPin, INPUT);
 pinMode(ledPin, OUTPUT);
 }
 void loop() {
 int buttonState = digitalRead(buttonPin);
 if (buttonState == HIGH) {
 digitalWrite(ledPin, HIGH);
 } else {
 digitalWrite(ledPin, LOW);
 }}

Hardware Picture:

Conclusion:
This Arduino UNO experiment introduced foundational microcontroller programming,
demonstrating LED control through GPIO. This knowledge is vital for progressing to complex
projects with sensors and communication interfaces.

7
[M Rizwan Akram]
[2021-MC-293]

Lab # 02
Introduction to Microcontrollers (Arduino UNO)
Dual Input Decision Maker
Objective:
1. To create a simple decision-making system based on the states of two input switches.

Apparatus:
1. Arduino UNO board
2. Breadboard
3. Two push-button switches
4. LED
5. Resistors
6. Jumper wires

Theory:
Apparatus:
Introduction to Microcontroller (Arduino UNO):
The Arduino UNO is a popular microcontroller board that serves as the heart of many DIY
electronics projects. It is based on the ATmega328P microcontroller and comes with built-in
features such as digital and analog input/output pins, USB connectivity for programming and
communication, and a simple development environment. Arduino UNO is widely used for
prototyping and creating interactive electronic systems due to its ease of use, versatility, and a
supportive community that provides a vast array of libraries and resources for developers.

Arduino UNO:
Arduino UNO is a popular microcontroller board based on the ATmega328P microcontroller.
Developed by the Arduino company, it provides a user-friendly platform for programming and
prototyping electronic projects. The Arduino UNO board consists of digital and analog
input/output pins, a USB interface for programming and power, and a power jack for an external
power supply. Its open-source nature and extensive community support make it an excellent
choice for both beginners and experienced developers.

LED:
Light Emitting Diode, a semiconductor device that emits light when a current passes through it.

Resistor (220-330 ohms):A passive electronic component that limits the current flowing
through the LED to prevent damage.

8
[M Rizwan Akram]
[2021-MC-293]

Breadboard:
A prototyping tool for building electronic circuits without soldering.

Jumper wires:
Flexible wires used to establish connections between components on the breadboard.

Push Button:
A momentary mechanical switch that, when pressed, completes an electrical circuit, allowing
current flow. Typically used for user input or control in electronic projects.

Arduino UNO:

Led: Register: Push Button:

9
[M Rizwan Akram]
[2021-MC-293]

Bread Board: Jumper Wires:

Procedure:
1. Connect two push-button switches to separate digital input pins (e.g., D2 and D3) of the
Arduino. Connect one end of each switch to the pin and the other end to ground (GND)
through individual pull-down resistors (e.g., 10k ohms).
2. Connect an LED to a digital output pin (e.g., D13) through a current-limiting resistor
(e.g., 220 ohms). Connect the LED's other leg to ground (GND).
3. Ensure proper power supply to the Arduino.

Arduino Code:
 const int switch1Pin = 2;
 const int switch2Pin = 3;
 const int ledPin = 13;
 void setup() {
 pinMode(switch1Pin, INPUT);
 pinMode(switch2Pin, INPUT);
 pinMode(ledPin, OUTPUT);
 }
 void loop() {
 int switch1State = digitalRead(switch1Pin);
 int switch2State = digitalRead(switch2Pin);
 if (switch1State == HIGH && switch2State == HIGH) {
 digitalWrite(ledPin, HIGH);
 } else if (switch1State == HIGH) {
 digitalWrite(ledPin, LOW);
 } else if (switch2State == HIGH) {
 digitalWrite(ledPin, LOW);
 } else {
 digitalWrite(ledPin, LOW);
 }
 }

10
[M Rizwan Akram]
[2021-MC-293]

Hardware Picture:

Conclusion:
This experiment successfully implemented a dual input decision-making system using Arduino
UNO and two push-button switches. The provided code allows for different actions or outputs
based on the states of the two switches.

Lab # 03

11
[M Rizwan Akram]
[2021-MC-293]

Introduction to Microcontroller (ESP32)


Objective:
1. ESP32 Setup and Testing:
2. One switch and three LEDs (via transistor) connected to esp32.

Apparatus:
1. ESP32 microcontroller
2. USB Cable (Type A to micro-USB)
3. Breadboard
4. One push-button switch
5. Computer with Arduino IDE and ESP32 Board Package installed
6. Three LEDs
7. Transistors (e.g., NPN transistors)
8. Resistors (for LEDs and transistors)
9. Jumper wires

Theory:
ESP32:
The ESP32 is a powerful and versatile microcontroller featuring integrated Wi-Fi and Bluetooth
capabilities. Developed by Espressif Systems, it is widely used in IoT (Internet of Things)
projects due to its connectivity features and advanced processing capabilities.

Procedure:

12
[M Rizwan Akram]
[2021-MC-293]

Task 1:
ESP32 Setup and Testing:
 Connect the ESP32 Dev Kit:
 Connect the ESP32 Dev Kit to your computer using the USB cable.
1. Launch Arduino IDE:
 Open the Arduino IDE on your computer.
2. Select Board and Port:
 Go to Tools > Board and select "ESP32 Dev Module".
 Go to Tools > Port and select the appropriate COM port.
3. Verify Connection:
 Upload a simple sketch (e.g., Blink) to verify that the ESP32 is communicating with
your computer.
4. Connect LED to GPIO Pin:
 Connect the anode (longer leg) of the LED to GPIO pin 2 of the ESP32 via a current-
limiting resistor (220 ohms), and connect the cathode (shorter leg) to ground.
5. Write and Upload Blink Sketch:
 Write a simple sketch to blink the LED.
6. Test the Circuit:
 Upload the sketch to the ESP32 and observe the LED blinking.
Task2:
Switch and Three LEDs Setup:
1. Connect one side of the push-button switch to a digital pin (e.g., GPIO 2) on the ESP32.
2. Connect the other side of the switch to the ground (GND) on the ESP32.
3. Connect three LEDs to separate digital pins (e.g., GPIO 5, GPIO 6, and GPIO 7) through
transistors for current control.
4. Connect each LED's cathode through a current-limiting resistor to ground.
5. Write a program to display binary data on the LEDs whenever the switch is pressed.

Circuit:

Code:

13
[M Rizwan Akram]
[2021-MC-293]

Task 1:
 int ledPin = 2; // Define the GPIO pin to which the LED is connected
 void setup() {
 pinMode(ledPin, OUTPUT); // Set the GPIO pin as an OUTPUT
 }
 void loop() {
 digitalWrite(ledPin, HIGH); // Turn on the LED
 delay(1000); // Wait for a second
 digitalWrite(ledPin, LOW); // Turn off the LED
 delay(1000); // Wait for a second
 }
Task 2:
 const int switchPin = 2;
 const int ledPins[] = {4, 5, 6};
 void setup() {
 pinMode(switchPin, INPUT_PULLUP);
 for (int i = 0; i < 3; i++) {
 pinMode(ledPins[i], OUTPUT);
 }
 }
 void loop() {
 if (digitalRead(switchPin) == LOW) {
 for (int i = 0; i < 8; i++) {
 displayBinary(i);
 delay(500);
 }
 delay(1000);
 }
 }
 void displayBinary(int value) {
 for (int i = 0; i < 3; i++) {
 digitalWrite(ledPins[i], (value >> i) & 1);
 }
 }

Hardware Picture:

14
[M Rizwan Akram]
[2021-MC-293]

Conclusion:
This lab successfully set up and tested the ESP32 with the Arduino IDE, and implemented a
program to display binary data on three LEDs based on switch input. Understanding these
foundational concepts is essential for developing more advanced projects with the ESP32
microcontroller in interactive applications.

Lab # 04

15
[M Rizwan Akram]
[2021-MC-293]

Serial Communication using UART in Control Systems


Objective:
1. To establish serial communication between two microcontrollers using UART and
transmit/receive data.

Apparatus:
1. Arduino boards
2. ESP32 microcontroller
3. USB cables for programming and power
4. Jumper wires
5. Breadboard

Theory:
Serial communication:
Serial communication is a method of transferring data between two devices sequentially, one bit
at a time, over a communication channel or a physical connection. This contrasts with parallel
communication, where multiple bits are sent simultaneously over separate channels.
UART is a widely used communication protocol that allows devices to transmit and receive data
serially. It involves two pins - TX (Transmit) and RX (Receive). In control systems, UART is
often employed for inter-microcontroller communication due to its simplicity and reliability.

Procedure:
Hardware Setup:
1. Connect both Arduino Uno boards to the computer via USB cables for power.
2. Connect ground (GND) pins of both boards together.
3. Connect the TX (Transmit) pin of the Arduino to the RX (Receive) pin of the ESP32.
4. Connect the RX (Receive) pin of the Arduino to the TX (Transmit) pin of the ESP32.

Arduino Code:
 void setup() {
 Serial.begin(9600);
 }
 void loop() {
 Serial.println("Hello, Microcontroller 2!");
 delay(1000);
 }

ESP32 Code:

16
[M Rizwan Akram]
[2021-MC-293]

 void setup() {
 Serial.begin(9600);
 }
 void loop() {
 if (Serial.available() > 0) {
 String dataReceived = Serial.readString();
 Serial.println("Received: " + dataReceived);
 }

Hardware Picture:

Conclusion:
This experiment successfully demonstrated serial communication between two microcontrollers
using UART. Understanding and implementing UART communication are essential skills for
control systems, enabling devices to exchange information and work collaboratively in various
applications.

Lab # 05

17
[M Rizwan Akram]
[2021-MC-293]

Serial Communication using UART in Control Systems


Objective:
1. To Design a simple application that utilizes UART communication for a specific
purpose.
Apparatus:
1. Arduino UNO
2. ESP32
3. Breadboards
4. Four switches
5. Four LEDs
6. Resistors (for LEDs)
7. Jumper wires

Theory:
UART (Universal Asynchronous Receiver-Transmitter) is a commonly used serial
communication protocol that allows devices to transmit and receive data. In this experiment, we
use UART to send the states of switches from the Arduino UNO to the ESP32. The ESP32 then
displays this information on connected LEDs.

Procedure:
Hardware Setup:
1. Connect four switches to digital pins (e.g., 2, 3, 4, 5) on the Arduino UNO.
2. Connect the other side of each switch to the ground (GND) on the Arduino UNO.
3. Connect four LEDs to digital pins (e.g., 6, 7, 8, 9) on the ESP32.
4. Connect each LED's cathode through a current-limiting resistor to ground.
5. Connect the TX pin of the Arduino UNO to the RX pin of the ESP32, and vice
versa.

Arduino Code:
 void setup() {
 Serial.begin(9600);
 for (int i = 2; i <= 5; i++) {
 pinMode(i, INPUT_PULLUP); }}
 void loop() {
 String switchStates = "";
 for (int i = 2; i <= 5; i++) {
 switchStates += digitalRead(i) == LOW ? '1' : '0'; }
 Serial.println(switchStates);
 delay(1000);

18
[M Rizwan Akram]
[2021-MC-293]

 }

ESP32 Code:
 void setup() {
 Serial.begin(9600); // Initialize Serial communication
 for (int i = 6; i <= 9; i++) {
 pinMode(i, OUTPUT); }}
 void loop() {
 if (Serial.available() > 0) {
 String switchStates = Serial.readString();
 displayLEDs(switchStates); // Display switch states on LEDs}}
 void displayLEDs(String states) {
 for (int i = 0; i < states.length(); i++) {
 digitalWrite(6 + i, states[i] == '1' ? HIGH : LOW);
 }}

Hardware Picture:

Conclusion:
This experiment successfully implemented a UART communication system between an Arduino
UNO and an ESP32. By reading the states of switches on the Arduino UNO and transmitting the
information serially to the ESP32, the switch states were accurately displayed on connected
LEDs. This experiment increased my knowledge for future.

Lab # 06
Data Acquisition using ADC Interfacing

19
[M Rizwan Akram]
[2021-MC-293]

Objective:
1. To perform data acquisition using an analog sensor, specifically the Temperature sensor
KY-028.

Apparatus:
1. ESP32
2. Temperature sensor KY-028
3. Jumper wires
4. Breadboard

Theory:
Temperature Sensor KY-028:
The KY-028 is a temperature sensor module designed for Arduino and other microcontroller
projects. It utilizes a thermistor to measure ambient temperature and outputs an analog voltage
signal that is proportional to the temperature.

Procedure:
Hardware Setup:
1. Connect the KY-028 sensor to the ESP32 using jumper wires.
2. Connect the sensor's signal pin to an analog pin on the ESP32 (e.g., A0).
3. Connect the sensor's VCC pin to the 5V output on the ESP32.
4. Connect the sensor's GND pin to the ground (GND) on the ESP32.

Code:
 const int analogPin = A0;
 int sensorValue;
 void setup() {
 Serial.begin(9600);
 }
 void loop() {
 sensorValue = analogRead(analogPin);

20
[M Rizwan Akram]
[2021-MC-293]

 Serial.println(sensorValue);
 delay(1000);
 }

Hardware Pictures:

Conclusion:
This experiment successfully demonstrated data acquisition using the KY-028 temperature sensor
and Arduino. By interfacing the analog sensor with an ADC, the continuous voltage signal was
converted to a digital value and displayed on the Serial Monitor.

Lab # 07
Data Acquisition with Analog Sensors and Input Capture using Timer
Interrupts

21
[M Rizwan Akram]
[2021-MC-293]

Objective:
1. To data acquisition using analog sensors (e.g., temperature sensor)
2. To input capture experiment using timers’ interrupt.
Apparatus:
1. ESP32
2. Analog sensor (e.g., temperature sensor)
3. Jumper wires
4. Breadboard
5. Timer Interrupts

Theory:
1. Data Acquisition with Analog Sensors:
 Analog sensors generate continuous voltage signals corresponding to physical
phenomena (e.g., temperature).
 Analog-to-Digital Conversion (ADC) is crucial for interfacing these sensors
with microcontrollers like Arduino.
 ADC converts the continuous analog signal into a discrete digital value that
can be processed by the microcontroller.

2. Input Capture Experiment with Timer Interrupts:


 Timer interrupts allow precise timing in microcontroller applications.
 Input capture is a feature that records the timer value when a specific event
occurs (e.g., a rising or falling edge).
 Sampling refers to how frequently the ADC measures the analog signal, while
resolution is the number of digital bits used to represent the analog value.

Procedure:
1. Data Acquisition with Analog Sensors:
1. Connect the analog sensor (e.g., temperature sensor) to an analog pin on the
ESP32.
2. Write code to read the analog value from the sensor using `analogRead()` and
display it on the Serial Monitor.
3. Observe the continuous data acquisition process.

2. Input Capture Experiment:


1. Set up a timer interrupt to capture the timer value on a specific event (e.g., a
button press).

22
[M Rizwan Akram]
[2021-MC-293]

2. Configure the ADC to sample the analog signal at a specific frequency.


3. Vary the ADC resolution and observe its impact on the accuracy of the measured
analog signal.
4. Display the captured data and timer values on the Serial Monitor.

Arduino Code:
1. Data Acquisition with Analog Sensors:
 const int analogPin = A0;
 int sensorValue;
 void setup() {
 Serial.begin(9600);
 }
 void loop() {
 sensorValue = analogRead(analogPin);
 Serial.println(sensorValue);
 delay(1000);
 }
2. Input Capture Experiment:
 #include<Arduino.h>
 hw_timer_t timer;
 void onTimer(){
 int actualValue = analogRead(analogPin);
 float vol = (float)actualValue / 4096* referenceVol;
 float temp= (1.2-vol)/0.01;
 //Serial.print(vol);
 Serial.print("Actual Value:");
 Serial.print(actualValue);
 Serial.print(" Vol: ");
 Serial.print(vol);
 Serial.print(" V Temp: ");
 Serial.print(temp);
 Serial.println("°C");
 delay(1000);
 }
 void setup() {
 Serial begin(9600):
 timer = timer Begin(0, 80, true);
 timerAttachlnterrupt(timer &onTner, true);
 timerAlarmWrite( timer. 1000000, true);

23
[M Rizwan Akram]
[2021-MC-293]

 timerAlarmEnable(timer);
 }
 void loop() {
 }

Hardware Picture:

Conclusion:
This lab demonstrated the process of data acquisition with analog sensors and explored input
capture techniques using timer interrupts.

Lab # 08
Texas Instruments Cortex-M controller GPIO Interfacing

24
[M Rizwan Akram]
[2021-MC-293]

Objectives:
1. Introduction to TM4C123x (TIVA C series) microcontroller
2. Installing Energia IDE & blinky example code
3. Installing Keil IDE & blinky example code

Apparatus:
1. TM4C123x microcontroller board
2. USB cable for programming and power supply
3. LEDs and resistors for the blinky example
4. Laptop

Theory:
1. Introduction to TM4C123x (TIVA C series) Microcontroller:
The TM4C123x series is part of Texas Instruments' TIVA C microcontroller family, based on the
ARM Cortex-M4 architecture. It features a variety of peripherals, including GPIO, UART, SPI,
I2C, and more. GPIO is a crucial part of embedded systems, allowing the microcontroller to
interact with the external world through digital input and output.

TM4C123x (TIVA C series) Microcontroller:


TM4C123x, part of the TIVA C series by Texas Instruments, is a 32-bit ARM Cortex-M4-based
microcontroller. Renowned for its diverse peripheral set, it supports GPIO, UART, SPI, I2C,
timers, and ADC, making it ideal for embedded applications. Its real-time control capabilities
and connectivity features cater to a broad range of projects.

Interface:

Energia IDE:

25
[M Rizwan Akram]
[2021-MC-293]

Energia IDE is open-source electronics prototyping platform tailored for Texas Instruments'
Launchpad series, offering a simplified development environment based on the Arduino
framework. It enables easy coding and uploading of programs to TI microcontroller boards.

Keil IDE:
Keil IDE, or Microcontroller Development Kit (MDK), is a comprehensive integrated
development environment developed by Arm. Widely used for embedded systems programming,
it supports various microcontroller architectures, including ARM Cortex-M series processors,
providing tools for code development, debugging, and project management.

2. Installing Energia IDE & Blinky Example Code


Procedure:
1. Download Energia IDE from the official website.
2. Install Energia on your computer.
3. Now, we have to download the board files for the TIVA Launchpad.
4. Go to Tools > Board > Boards Manager. Search for Teva C boards and download it as
shown below

26
[M Rizwan Akram]
[2021-MC-293]

5. Connect the TM4C123x board to the computer via USB.


6. Open Energia IDE and select the appropriate board from the menu.
7. To open this example program go to File > Example > Basics > Blink as shown below

8. To do this simply connect your board to the computer using the micro USB cable
provided and wait for some time.
9. The drivers for the board should start installing automatically.

27
[M Rizwan Akram]
[2021-MC-293]

10. Then Open your device manager and under the COM ports option you should see your Board
name like shown below
11. Again go to Tools -> Boards and select the LaunchPad(TIVA C) w/ tm4c123 . Once
done you should notice the following at the bottom right corner of your Energia IDE.
12. bottom right corner of your Energia IDE.

13. click on the upload icon on the top left corner and your program should start

14. Observe the blinking of the connected LED.


3. Installing Keil IDE & Blinky Example Code

28
[M Rizwan Akram]
[2021-MC-293]

Procedure:
1. Download Keil IDE from the official website.
Downloading Link:
https://www.keil.com/dd2/texasinstruments/tm4c123gh6p m/
Installing Steps till packs installer step
https://www.pantechelearning.com/installation-procedure- for-keil-ide-for-embedded-
development/
MDK-Stellaris-ICDI-AddOn
https://developer.arm.com/documentation/ka002280/late st/
2. Install Keil on your computer.
3. Set up a new project for the TM4C123x microcontroller.

4. Click on Pack Installer.

29
[M Rizwan Akram]
[2021-MC-293]

5. Configure the project settings, including the target device.

30
[M Rizwan Akram]
[2021-MC-293]

Starting a New Project:

Project Name and Location:

31
[M Rizwan Akram]
[2021-MC-293]

Device Selection:

Manage Run Time Environment:

32
[M Rizwan Akram]
[2021-MC-293]

Adding source file:

6. Write a blinky program using GPIO.

33
[M Rizwan Akram]
[2021-MC-293]

Coding & Building:

Debugger selection for target:

7. Build the project and generate the binary file.


8. Connect the TM4C123x board to the computer and program it with the generated binary.

34
[M Rizwan Akram]
[2021-MC-293]

Debug tab & Stellaris ICDI:

Upload hex file to the launchpad:

35
[M Rizwan Akram]
[2021-MC-293]

Verifying:

9. Observe the blinking LED on the board.

Conclusion:
 Successfully installing Energia IDE and running a blinky example demonstrates the basic
setup and GPIO functionality of the TM4C123x microcontroller.
 The successful installation of Keil IDE and the execution of a blinky program reinforce
the understanding of the development environment and GPIO interfacing with the
TM4C123x microcontroller.
 This lab provided hands-on experience with the Texas Instruments TM4C123x
microcontroller, focusing on GPIO interfacing through both Energia and Keil IDEs.
Understanding how to set up development environments and implement simple programs
lays the foundation for more complex embedded systems projects. Through this lab,
participants gained practical knowledge in microcontroller programming and interfacing
with external components using GPIO.

36
[M Rizwan Akram]
[2021-MC-293]

Lab # 09
Input Capture and Period Measurement of a Pulse
Objective:
1. Introduction to Capture Module in TM4C123x (TIVA C series)
2. Period measurement on the TM4C123x
3. Example Code

Apparatus:
1. TM4C123x microcontroller board
2. Pulse signal source
3. Connecting wires

Theory:
1. Introduction to Capture Module in TM4C123x (TIVA C series)
The Capture Module in TM4C123x, part of the TIVA C series, is a feature for precise event
timestamping and timing measurements. It facilitates tasks like measuring pulse widths and
period durations. This module is crucial in applications requiring accurate event timing, such as
motor control systems and sensor interfacing. Integrated into the microcontroller, it enhances
precision in timestamping external events.

Capture Module in TM4C123x:


The Capture Module in the TM4C123x (TIVA C series) microcontroller is a specialized feature
designed for accurate time measurement. It captures time stamps of both rising and falling edges
of external signals, facilitating precise measurements of pulse duration, frequency, and period.
This module enhances the microcontroller's capabilities in applications requiring real-time timing
information, making it particularly valuable in tasks such as pulse-width modulation and time-
sensitive control systems.

37
[M Rizwan Akram]
[2021-MC-293]

1. Period Measurement on the TM4C123x


Period measurement on the TM4C123x involves determining the time duration of a repeating
event, often associated with a timer or a capture module. This process is essential for applications
such as measuring the frequency or pulse width of a signal. The TM4C123x microcontroller, part
of the TIVA C series, provides features and modules to facilitate period measurement.

Steps:
1. Clock and Port Initialization:
 Enable the timer clock and the digital port.
 Enable the digital pin and set its alternative function.
2. Timer Disable during Initialization:
 Disable the timer by clearing the TAEN (or TBEN) bit in TIMER0_CTL_R.
 Ensure the timer is inactive during setup.
2. 16-Bit Mode Configuration:
 Set GPTMCFG field to 4 in TIMER0_CTL_R for 16-bit mode.
3. Capture Mode Configuration:
 Clear TAAMS (or TBAMS) bit for capture mode.
 Set TACMR (or TBCMR) bit for input edge time mode.
 Set TAMR (or TBMR) field to 3 for capture mode.
4. Overall Input Capture Mode Selection:
 Write 0x0007 to TIMER0_TAMR_R to select input capture mode.
5. Edge Capture Modes:
 Refer to Table 2.17 for available edge capture modes for TAEVENT (or TBEVENT).
6. Prescaler Configuration for Time Measurement:
 Set the 24-bit reload value to 0xFFFFFF.
 Initialize TIMER0_TAILR_R to 0xFFFF and TIMER0_TAPR_R to 0xFF.
7. Arming Input Capture:
 Set CAEIM (or CBEIM) bit in TIMER0_IMR_R to arm input capture.
8. Clear Trigger Flags:
 Clear trigger flags in TIMER0_RIS_R to prevent spurious interrupts.
 Use TIMER0_ICR_R to clear trigger flags.
9. Enable Timer:
 Enable the timer by setting TAEN (or TBEN) bit in TIMER0_CTL_R.
10. Interrupt Configuration:
 Configure NVIC for interrupts if required.
11. Prescaler for 24-Bit Extension:
 Utilize 8-bit prescalers (TIMER0_TAPMR_R and TIMER0_TBPMR_R) to extend
the 16-bit timer to 24 bits.
12. Input Capture Event Actions:
 Capture the current timer value into TIMER0_TAR_R.
 Set CAERIS and CBERIS flags; request interrupt if CAEIM (or CBEIM) is 1.

38
[M Rizwan Akram]
[2021-MC-293]

13. Flag Behavior and Clearing:


 CAERIS and CBERIS flag bits in TIMER0_RIS_R are set by hardware events.
 Clear trigger flags by writing 1s to TIMER0_ICR_R.
14. Resolution, Precision, and Range:
 Resolution: Smallest change in period determined by clock frequency (e.g., 12.5 ns at
80 MHz).
 Precision: Related to the bit width of the counter (e.g., 24 bits provide about 16
million different periods).
 Range: System should detect overflows, underflows, and situations with no period.
15. Considerations for Edge Detection:
 Proper signal conditions are crucial for accurate edge detection.
16. Period Measurement Approach:
 Connect digital input signal to an input capture pin.
 Each rising edge triggers an input capture interrupt.
17. Calculation of Period:
 Period calculated as the difference in TIMER0_TAR_R latch values between
consecutive rising edges.
 Formula for period: [(60000 ms/min) / (300 RPM) / N edges/rotation].
18. Resolution and Precision:
 Resolution: 12.5 ns, indicating the smallest detectable period change.
 -Precision: Slightly less than 24 bits due to ISR execution time (about 1 μs).
 Shortest measurable period is around 1 μs.
19. Limitations and Context Switch Time:
 Method may not work properly if the period is larger than 2^24 cycles (about 209
ms).
 Context switch time influences the shortest measurable period.
20. Interrupt-Driven Approach:
 Input capture interrupt has a separate vector, and interrupts are requested on each
rising edge.
 System counts all cycles required to process the interrupt.
21. 24-Bit Subtraction:
 Achieve 24-bit subtraction by ANDing the difference with 0x0FFFFFF.
22. Initial Period Measurement:
 The first period measurement is considered incorrect and should be neglected.
23. Period Measurement System Implementation:
- Refer to Program 2.16 for likely implementation of the period measurement system for
TM4C123.

Procedure:
1. Connect the pulse signal source to a GPIO pin on the TM4C123x board.
2. Configure the Capture Module to capture time stamps on both rising and falling edges.

39
[M Rizwan Akram]
[2021-MC-293]

3. Implement code to calculate the period based on the captured time stamps.
4. Upload the program to the TM4C123x board.
5. Connect the board to an oscilloscope for verification.
6. Observe and analyze the period measurement results.

3. Example Code
 #include <tm4c123gh6pm.h>
 void setupCaptureModule() {
 // Clock and Port Initialization
 SYSCTL_RCGCTIMER_R |= 0x01; // Enable Timer 0 clock
 SYSCTL_RCGCGPIO_R |= 0x02; // Enable GPIO Port B clock
 GPIO_PORTB_AFSEL_R |= 0x04; // Enable alternative function on PB2
 GPIO_PORTB_PCTL_R |= 0x00000700; // Configure PB2 for T0CCP0
 GPIO_PORTB_DEN_R |= 0x04; // Digital enable PB2
 // Timer Disable during Initialization
 TIMER0_CTL_R &= ~0x01; // Disable Timer 0 during setup
 // 16-Bit Mode Configuration
 TIMER0_CFG_R = 0x04; // Configure Timer 0 as 16-bit timer
 // Capture Mode Configuration
 TIMER0_TAMR_R = 0x03; // Configure Timer 0A for edge time mode
 TIMER0_CTL_R &= ~0x00000008; // Disable Timer 0A match interrupt
 TIMER0_CTL_R |= 0x00000004; // Capture mode, edge-time mode
 TIMER0_TAMR_R |= 0x00000010; // Count up
 // Overall Input Capture Mode Selection
 TIMER0_TAMR_R |= 0x00000007; // Select input capture mode
 // Edge Capture Modes
 // Prescaler Configuration for Time Measurement
 TIMER0_TAILR_R = 0xFFFF; // Initialize TIMER0_TAILR_R to 0xFFFF
 TIMER0_TAPR_R = 0xFF; // Initialize TIMER0_TAPR_R to 0xFF
 }
 int main() {
 setupCaptureModule();
 // Arming Input Capture
 TIMER0_IMR_R |= 0x00000004; // Arm Timer 0A capture interrupt
 // Clear Trigger Flags
 TIMER0_ICR_R = 0x00000004; // Clear Timer 0A capture interrupt flag
 // Enable Timer
 TIMER0_CTL_R |= 0x01; // Enable Timer 0
 while (1) {

40
[M Rizwan Akram]
[2021-MC-293]

 // Main program loop


 // Perform necessary tasks
 }
 return 0;}
 // Interrupt Service Routine (ISR) for Timer 0A capture event
 void TIMER0A_Handler() {
 // Your code for handling the capture event
 // Calculate the period using TIMER0_TAR_R values
 // Clear interrupt flag
 TIMER0_ICR_R = 0x00000004;
 }

Conclusion:
This lab successfully introduced the Capture Module in the TM4C123x microcontroller and
demonstrated its application in period measurement of a pulse signal. By configuring the module
and implementing the necessary code, precise timing information was captured, allowing for
accurate period calculations. The hands-on experience provided insights into the capabilities of
the TM4C123x microcontroller in time-sensitive applications, particularly in scenarios involving
pulse signals.

41
[M Rizwan Akram]
[2021-MC-293]

Lab # 10
UART Communication of the TM4C123 and Tera Term Serial Monitor
Objective:
1. Introduction to UART module of TM4C123x
2. Tera Term installation and configuration
3. Example Code

Theory:
Introduction to UART Module of TM4C123x:
The UART (Universal Asynchronous Receiver/Transmitter) module in the TM4C123x
microcontroller facilitates serial communication, allowing the microcontroller to exchange data
with other devices such as sensors, displays, or other microcontrollers. UART operates in
asynchronous mode, where data is transmitted without a shared clock signal. The TM4C123x
UART module typically includes features like configurable baud rates, data formats, and
interrupt-driven communication. It commonly uses two pins, TX (transmit) and RX (receive), for
bidirectional data transfer. UART communication is widely utilized for its simplicity and
versatility in various embedded systems applications.

1. UART Module of TM4C123x:


The UART module in the TM4C123x microcontroller facilitates serial communication with
external devices. It supports asynchronous data transmission and reception, allowing for the
exchange of data with specific configurations such as baud rate, data bits, stop bits, and parity.
The UART module is commonly used for interfacing with peripherals, sensors, and
communication with other microcontrollers or computer systems. Tera Term is a widely used
serial terminal program that facilitates communication with the microcontroller over UART.

42
[M Rizwan Akram]
[2021-MC-293]

2. Tera Term Installation and Configuration:


Procedure:
Tera Term Serial Monitor
https://forum.digikey.com/t/getting-started-with-the-ti- tiva-tm4c123gxl-launchpad-evaluation-
board/13450
1. Connection to Computer:
 Connect the LaunchPad eval board to the computer via the MicroUSB cable.
 Use the 'DEBUG' MicroUSB port on the device.
 Ensure that the 'DEVICE/DEBUG' switch on the board is set to DEBUG.
2. Driver Installation:
 Windows may automatically install drivers for the device (recognized as a Stellaris
ICDI device).
 If not, navigate to Device Manager, locate the unrecognized
 devices, and update drivers.
 Point Windows to the folder containing the Stellaris ICDI device drivers.
3. TeraTerm Configuration:
 Open TeraTerm and create a new connection.
 Choose the serial option and select the Stellaris Virtual Serial Port from the
dropdown.
4. Configure TeraTerm with the following settings:
 Baud Rate: 115,200
 Data Bits: 8
 Stop Bits: 1
 Parity: None
3. Example Code:
 #include "TM4C123.h"
 #define NVIC_PRI0_R (*((volatile uint32_t *)0xE000E400))
 #define NVIC_PRI4_R (*((volatile unsigned long *)0xE000E410))
 #define NVIC_EN0_R (*((volatile unsigned long *)0xE000E100))
 void Delay(unsigned long counter);
 char UART0_Receiver(void);
 void UART0_Transmitter(char data);
 int main(void)
 {
 SYSCTL->RCGCUART |= 0x01; /* enable clock to UART0 */
 SYSCTL->RCGCGPIO |= 0x01; /* enable clock to GPIOA (PA0 and PA1 are used for
UART0) */
 Delay(1);
 /* UART0 initialization */

43
[M Rizwan Akram]
[2021-MC-293]

 UART0->CTL = 0; /* UART0 module disable */


 UART0->IBRD = 104; /* for 9600 baud rate, integer = 104 */
 UART0->FBRD = 11; /* for 9600 baud rate, fractional = 11*/
 UART0->CC = 0; /* select system clock */
 UART0->LCRH = 0x0070; /* data length 8-bit, no parity bit, no FIFO */
 UART0->CTL = 0x301; /* Enable UART0 module, Rx and Tx */
 /* UART0 TX and RX use PA0 and PA1. Configure them digital and enable alternate
function */
 GPIOA->DEN = 0x03; /* set PA0 and PA1 as digital */
 GPIOA->AFSEL = 0x03; /* use PA0, PA1 alternate function */
 GPIOA->AMSEL = 0; /* Turn off analog function */
 GPIOA->PCTL = 0x00000011; /* configure PA0 and PA1 for UART */
 Delay(1);
 while(1)
 {
 /* My Name
 UART0_Transmitter('R');
 UART0_Transmitter('I');
 UART0_Transmitter('Z');
 UART0_Transmitter('W');
 UART0_Transmitter('A');
 UART0_Transmitter('N');
 Delay(1000000);
 }
 }
 void UART0_Transmitter(char data)
 {
 while((UART0->FR & 0x20) != 0); /* wait until Tx buffer not full */
 UART0->DR = data; /* before giving it another byte */
 }
 void Delay(unsigned long counter)
 {unsigned long i = 0;
 for (i = 0; i < counter; i++);}

Conclusion:
This lab introduced the UART communication module of the TM4C123x microcontroller and
demonstrated its application using Tera Term. The example code showcased basic UART
transmission of the message "Hello, World!" from the microcontroller to the computer.
Understanding UART communication is fundamental for interfacing the microcontroller with
external devices and serves as a foundation for more complex applications.

44
[M Rizwan Akram]
[2021-MC-293]

Lab # 11
DC motor interfacing with ESP32 Microcontroller (Open Loop Control)
Objective:
1. Introduction to inductive loads & PWM module
2. To interface a DC motor with the ESP32 microcontroller and open loop control of its
speed using a potentiometer connected to an analog pin.

Apparatus:
1. ESP32 microcontroller.
2. DC Motor with an H-bridge motor driver Or
3. Transistor 2N222A and Diode 1N4004
4. Potentiometer.
5. Motor Power Supply.
6. Jumper wires.

Circuit Diagram:

Theory:
Introduction to Inductive Loads & PWM Module:
Inductive loads, like DC motors, generate a magnetic field when current flows through their
coils. Their inertia resists abrupt current changes, making them responsive to gradual variations.
PWM (Pulse Width Modulation) is a technique that varies the pulse duration in a signal to
control average power delivered to a device. In the context of motors, PWM adjusts the duty
cycle to regulate speed efficiently. This combination of inductive loads and PWM is crucial for
precise and controlled operation in various electronic applications, notably in motor control
systems.

45
[M Rizwan Akram]
[2021-MC-293]

Inductive Loads:
Inductive loads, such as DC motors, possess coils that induce a magnetic field when current
flows through them. The inertia of these loads resists sudden changes in current, making them
responsive to gradual variations.

PWM Module:
Pulse Width Modulation (PWM) is a technique where a signal's pulse duration is varied to
control the average power delivered to a device. In the context of motor control, PWM is often
used to regulate the speed of motors by adjusting the duty cycle of the pulse signal.
DC motors are inductive loads that respond to changes in voltage and current. Pulse Width
Modulation (PWM) is a technique used to control the speed of DC motors by varying the duty
cycle of a square wave signal. In open-loop control, the speed is adjusted based on a
predetermined relationship, often controlled by external factors like potentiometer values.

DC Motor:

Procedure:
1. Setup Hardware:
Interface with ESP32
 Circuit Connections:
o Connect the DC motor to the H-bridge motor driver. Or as shown in previous fig.
o Connect the motor driver to the appropriate GPIO pins (PB6 PWM) on the ESP32.
o Connect the potentiometer to one of the analog input pins (e.g., A0) on the ESP32.
o Connect the power supply to power the DC motor.
Steps:
Step 2: Software Configuration
 Create a new project in your preferred integrated development environment (IDE) for the
ESP32, such as Arduino IDE.
 Include the necessary libraries for GPIO, ADC, and PWM in your project.
Step 3: Initialize GPIO

46
[M Rizwan Akram]
[2021-MC-293]

 Configure GPIO pins for motor control (e.g., motor driver input pins) as outputs.
 Configure the GPIO pin for the potentiometer (e.g., analog pin A0) as an input.
Step 4: Initialize ADC
 Initialize the Analog-to-Digital Converter (ADC) to read the potentiometer value.
 Configure the ADC to convert the analog input from the potentiometer.
Step 5: Initialize PWM
 Initialize PWM to control the speed of the DC motor.
 Configure PWM parameters such as frequency and duty cycle.
Step 6: Main Loop
 Enter the main loop of your program.
 Continuously read the potentiometer value using the ADC.
 Map the potentiometer value to a PWM duty cycle to control the motor speed.
 Update the PWM duty cycle to adjust the motor speed accordingly.
Step 7: Run the Program
 Build and upload the program onto the ESP32 microcontroller using the selected IDE or
toolchain
 Observe how changing the potentiometer position affects the speed of the DC motor.
Discussion Points:
 Importance of PWM: Discuss how PWM is crucial for controlling the speed of a DC
motor, providing a means to regulate power and achieve variable speeds efficiently.
 Analog-to-Digital Conversion: Explain the process of converting the analog value from
the potentiometer, obtained through ADC, into a PWM duty cycle that controls the motor
speed.
 H-Bridge Motor Driver: Discuss the role of the H-bridge motor driver in controlling the
direction of the DC motor, highlighting its significance in motor control applications.

Code:
 const int potPin = A0; // Connect potentiometer to analog pin A0
 const int motorPin = 5; // Connect motor to GPIO pin 5 (PWM)
 void setup() {
 pinMode(potPin, INPUT);
 pinMode(motorPin, OUTPUT);
 }
 void loop() {
 // Read potentiometer value
 int potValue = analogRead(potPin);

47
[M Rizwan Akram]
[2021-MC-293]

 // Map potentiometer value (0-1023) to motor speed (0-255)


 int motorSpeed = map(potValue, 0, 1023, 0, 255);
 // Set motor speed using PWM
 analogWrite(motorPin, motorSpeed);
 delay(100); // Adjust delay based on your requirements
 }

Circuit Diagram:

Conclusion:
This experiment demonstrated the interfacing of a DC motor with the ESP32 microcontroller
using open-loop control. By leveraging PWM signals and a potentiometer, we achieved variable
speed control of the DC motor. The experiment enhances understanding of inductive loads,
PWM principles, and the practical implementation of open-loop control systems with
microcontrollers.

48
[M Rizwan Akram]
[2021-MC-293]

Lab # 12
DC motor interfacing with ESP32 Microcontroller (Closed Loop Control)
Objective:
1. Introduction to optical encoder and capture mode to measure speed of DC motor.
2. Implementing PID algorithm to control the speed of DC motor.
Apparatus:
1. ESP32 Microcontroller
2. DC Motor with Optical Encoder
3. Motor Driver or H-Bridge Transistor 2N222A and Diode 1N4004
4. Potentiometer.
5. Power Supply
6. Jumper Wires

Theory:
Introduction to Optical Encoder and Capture Mode for DC Motor Speed
Measurement:
An optical encoder is a sensor that converts mechanical motion into electrical signals, providing
feedback on position or speed. In the context of DC motor speed measurement, an optical
encoder is used to capture the rotational speed. Capture mode in microcontrollers, like the
TM4C123x, enables precise event timestamping, allowing accurate measurement of time
intervals between encoder pulses. This combination facilitates closed-loop control, enabling the
implementation of PID algorithms for maintaining and adjusting the DC motor speed with high
accuracy.

Optical Encoder and Capture Mode:


Optical encoders use a light source and photodetectors to generate electrical signals based on the
rotation of a disc with alternating transparent and opaque segments. Capture Mode on
microcontrollers is utilized to precisely capture the time intervals between encoder pulses,
enabling accurate speed measurement.

PID Algorithm:
The PID control algorithm adjusts the motor speed based on proportional, integral, and
derivative terms. Proportional control responds to the current error, integral control considers
past errors, and derivative control anticipates future errors. Tuning PID parameters influences the
system's response and stability.

49
[M Rizwan Akram]
[2021-MC-293]

Circuit Diagram:

Procedure:
1. Setup Hardware:
 Interface the DC motor with the ESP32 microcontroller as in the open-loop
configuration.
 Connect an optical encoder to the motor shaft.
 Connect the output of the optical encoder to a GPIO pin (e.g., GPIO35) on the ESP32 to
capture pulses.
2. Software Configuration:
 Open a new project in your preferred integrated development environment (IDE) for the
ESP32, such as Arduino IDE.
 Include the necessary libraries for GPIO, ADC, PWM, and a PID controller in your
project.
 Configure Capture Mode to measure the time between pulses from the optical encoder.
3. Initialize GPIO:
 Configure GPIO pins for motor control (e.g., motor driver input pins) as outputs.
 Configure the GPIO pin for the potentiometer (e.g., analog pin A0) and the feedback
signal (e.g., GPIO35 for the encoder) as inputs.
4. Initialize ADC:
 Initialize the Analog-to-Digital Converter (ADC) to read the potentiometer value.
5. Initialize PWM:
 Initialize PWM to control the speed of the DC motor.
 Configure PWM parameters such as frequency and duty cycle.
6. Initialize Capture Mode:
 Configure and initialize Capture Mode to measure the time between pulses from the
optical encoder.

50
[M Rizwan Akram]
[2021-MC-293]

7. Initialize PID Controller:


 Configure and initialize a PID controller to regulate the motor speed based on the
difference between the desired and actual speeds.
8. Main Loop:
 Enter the main loop of your program.
 Continuously read the potentiometer value using the ADC.
 Use the PID controller to adjust the PWM duty cycle based on the difference between the
desired and actual speeds.
9. Run the Program:
 Build and upload the program onto the ESP32 microcontroller using the selected IDE or
toolchain.
 Observe how the closed-loop control with the optical encoder maintains the motor speed
close to the desired speed set by the potentiometer.
Discussion Points:
 Optical Encoder and Capture Mode:
o Explain the working principle of optical encoders and how Capture Mode on the ESP32
is utilized to measure the time between pulses for accurate speed calculation.
 PID Algorithm:
o Discuss the Proportional-Integral-Derivative (PID) algorithm and its components (P, I, D)
for closed-loop control.

Code:
 #include <Arduino.h>
 #include <PID_v1.h>
 // Define pin numbers
 const int potPin = A0; // Connect potentiometer to analog pin A0
 const int motorPin = 5; // Connect motor to GPIO pin 5 (PWM)
 const int encoderPin = 2; // Connect optical encoder output to digital pin 2
 // Variables for PID
 double setpoint, input, output;
 PID pid(&input, &output, &setpoint, 1, 0, 0, DIRECT);
 void setup() {
 // Set up pin modes
 pinMode(potPin, INPUT);
 pinMode(motorPin, OUTPUT);
 pinMode(encoderPin, INPUT);
 // Set PID parameters

51
[M Rizwan Akram]
[2021-MC-293]

 pid.SetMode(AUTOMATIC);
 pid.SetSampleTime(100); // Adjust based on your requirements
 // Initialize Serial communication
 Serial.begin(115200);
 }
 void loop() {
 // Read potentiometer value
 int potValue = analogRead(potPin);
 // Map potentiometer value (0-1023) to motor speed (0-255)
 setpoint = map(potValue, 0, 1023, 0, 255);
 // Read encoder pulses to calculate speed
 int encoderPulses = pulseIn(encoderPin, HIGH); // Measure the time between pulses
 input = calculateSpeed(encoderPulses);
 // Compute PID and adjust motor speed
 pid.Compute();
 analogWrite(motorPin, output);
 // Print information for debugging
 Serial.print("Setpoint: ");
 Serial.print(setpoint);
 Serial.print(" | ");
 Serial.print("Speed: ");
 Serial.print(input);
 Serial.print(" | ");
 Serial.print("Output: ");
 Serial.println(output);
 delay(100); // Adjust delay based on your requirements
 }
 // Function to calculate speed from encoder pulses
 double calculateSpeed(int pulses) {
 // Adjust based on your encoder's characteristics
 double pulsesPerRevolution = 1000;
 double timeInterval = 0.1; // seconds
 return (pulses / pulsesPerRevolution) / timeInterval;
 }

Conclusion:
This experiment demonstrated the interfacing of a DC motor with the ESP32 microcontroller
using closed-loop control. By incorporating feedback from an optical encoder and implementing
the PID algorithm, the system achieved precise speed regulation, showcasing the advantages of
closed-loop control in motor control applications. The utilization of Capture Mode enhanced the
accuracy of speed measurements.

52
[M Rizwan Akram]
[2021-MC-293]

Lab # 13,14
Case Studies and Embedded System Design Cycle
Objective:
1. Implementing a case study project from scratch (e.g., temperature monitoring
system with wireless communication and control)
2. Integrating sensors, communication, control, and RTOS
3. Finalizing the project for deployment

Apparatus:
1. Microcontroller (ESP32)
2. Sensors (humidity, temperature, soil moisture)
3. Submersible Pump
4. Buzzer
5. LED
6. IoT module (e.g., ESP32)
7. Cloud platform (e.g., Blynk)

Theory:
My project is IoT-based Plant Monitoring System.

IoT-based Plant Monitoring System:


The IoT-based plant monitoring system aims to collect real-time data from sensors, transmit it
wirelessly, and enable remote control. The system's theory involves integrating hardware
components and implementing control logic to enhance plant care through automated responses.
With the increasing interest in smart agriculture, there is a growing need for systems that can
monitor and manage plant conditions efficiently. The IoT-Based Plant Monitoring System
addresses this need by providing real-time data on soil moisture, temperature, and humidity, and
automating the irrigation process to maintain optimal conditions for plant growth.
1.ESP32 Dev Module
The ESP32 Dev Module is the brain of the system, responsible for processing data from sensors,
controlling actuators, and communicating with the Bylink application.

53
[M Rizwan Akram]
[2021-MC-293]

Sensors:
 Soil Moisture Sensor
The soil moisture sensor measures the volumetric water content in the soil. It provides
continuous data, allowing the system to make informed decisions about irrigation.

 DHT11 Sensor
The DHT11 sensor records the temperature and humidity of the environment, offering
additional insights into the plant's surroundings.

Actuators:
 Submersible Pump
The submersible pump is activated automatically when the soil moisture level is
critically low, ensuring that the plant receives adequate water.

 Buzzer and LEDs

54
[M Rizwan Akram]
[2021-MC-293]

The buzzer alerts users when the soil moisture level is at either extreme. LEDs
visually indicate the status of the buzzer.

Display:
The LCD display provides real-time information on the environmental conditions,
including temperature, humidity, and soil moisture levels.

Circuit Diagram:

Procedure:
Communication Setup:

55
[M Rizwan Akram]
[2021-MC-293]

 Bylink Mobile Application:


The Bylink mobile application allows users to monitor the plant's conditions
remotely and control the system. It provides a user-friendly interface to visualize data and
receive alerts.

56
[M Rizwan Akram]
[2021-MC-293]

System Operation:
 Initialization
Upon system startup, the ESP32 initializes all components, including sensors,
actuators, and the Bylink communication module.
 Data Acquisition
The system continuously reads data from the soil moisture sensor and the DHT11
sensor, updating the internal variables with the latest information.
 Display Update
The LCD display is updated in real-time to show the current temperature,
humidity, and soil moisture levels.
 Alert Mechanism
If the soil moisture level reaches 0% or 100%, the buzzer is activated, and the
corresponding LED lights up to alert users.
 Remote Control
Users can monitor the system remotely through the Bylink mobile application. The application
allows them to view real-time data and control the submersible pump manually.

57
[M Rizwan Akram]
[2021-MC-293]

Results and Testing:


 Sensor Calibration
Calibration of sensors ensures accurate readings. The system undergoes testing in
different environmental conditions to validate the accuracy of sensor data.
 Alert System Validation
The alert system is tested by intentionally altering the soil moisture levels to
trigger the buzzer and observe the corresponding LED status.
 Remote Control Functionality
The Bylink mobile application is tested to ensure seamless communication with
the ESP32 module. Remote control operations, such as activating the pump manually, are
validated.

Code:
 #define BLYNK_TEMPLATE_NAME ""
 #define BLYNK_AUTH_TOKEN ""
 // Your WiFi credentials.
 // Set password to "" for open networks.
 char ssid[] = ""; //WiFi Name
 char pass[] = ""; //WiFi Password
 //Set the maximum wet and maximum dry value measured by the sensor
 int wetSoilVal = 930 ; //min value when soil is wet
 int drySoilVal = 3000 ; //max value when soil is dry
 //Set ideal moisture range percentage(%) in soil
 int moistPerLow = 20 ; //min moisture %
 int moistPerHigh = 80 ; //max moisture %
 #include <Adafruit_SSD1306.h>
 #include <WiFi.h>
 #include <WiFiClient.h>
 #include <BlynkSimpleEsp32.h>
 #include <DHT.h>
 #include <AceButton.h>
 using namespace ace_button;
 // Define connections to sensor
 #define SensorPin 34 //D34
 #define DHTPin 14 //D14
 #define RelayPin 25 //D25
 #define wifiLed 2 //D2

58
[M Rizwan Akram]
[2021-MC-293]

 #define RelayButtonPin 32 //D32


 #define ModeSwitchPin 33 //D33
 #define BuzzerPin 26 //D26
 #define ModeLed 15 //D15
 // Uncomment whatever type you're using!
 #define DHTTYPE DHT11 // DHT 11
 //#define DHTTYPE DHT22 // DHT 22, AM2302, AM2321
 //#define DHTTYPE DHT21 // DHT 21, AM2301
 //Change the virtual pins according the rooms
 #define VPIN_MoistPer V1
 #define VPIN_TEMPERATURE V2
 #define VPIN_HUMIDITY V3
 #define VPIN_MODE_SWITCH V4
 #define VPIN_RELAY V5
 #define SCREEN_WIDTH 128 // OLED display width, in pixels
 #define SCREEN_HEIGHT 32 // OLED display height, in pixels
 // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
 #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
 int sensorVal;
 int moisturePercentage;
 bool toggleRelay = LOW; //Define to remember the toggle state
 bool prevMode = true;
 int temperature1 = 0;
 int humidity1 = 0;
 String currMode = "A";
 char auth[] = BLYNK_AUTH_TOKEN;
 ButtonConfig config1;
 AceButton button1(&config1);
 ButtonConfig config2;
 AceButton button2(&config2);
 void handleEvent1(AceButton*, uint8_t, uint8_t);
 void handleEvent2(AceButton*, uint8_t, uint8_t);
 BlynkTimer timer;
 DHT dht(DHTPin, DHTTYPE);
 void checkBlynkStatus() { // called every 3 seconds by SimpleTimer
 bool isconnected = Blynk.connected();
 if (isconnected == false) {
 Serial.print("Blynk Not Connected ");

59
[M Rizwan Akram]
[2021-MC-293]

 digitalWrite(wifiLed, LOW);
 }
 if (isconnected == true) {
 digitalWrite(wifiLed, HIGH);
 //Serial.println("Blynk Connected");}}
 BLYNK_CONNECTED() {
 Blynk.syncVirtual(VPIN_MoistPer);
 Blynk.syncVirtual(VPIN_RELAY);
 Blynk.syncVirtual(VPIN_TEMPERATURE);
 Blynk.syncVirtual(VPIN_HUMIDITY);
 //Blynk.syncVirtual(VPIN_MODE_SWITCH);
 Blynk.virtualWrite(VPIN_MODE_SWITCH, prevMode);
 }
 BLYNK_WRITE(VPIN_RELAY) {
 if(!prevMode){
 toggleRelay = param.asInt();
 digitalWrite(RelayPin, toggleRelay);
 }
 else{
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);}}
 BLYNK_WRITE(VPIN_MODE_SWITCH) {
 if(prevMode != param.asInt()){
 prevMode = param.asInt();
 currMode = prevMode ? "A" : "M";
 digitalWrite(ModeLed, prevMode);
 controlBuzzer(500);
 if(!prevMode && toggleRelay == HIGH){
 digitalWrite(RelayPin, LOW);
 toggleRelay = LOW;
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);}}}
 void controlBuzzer(int duration){
 digitalWrite(BuzzerPin, HIGH);
 delay(duration);
 digitalWrite(BuzzerPin, LOW);
 }
 void displayData(String line1 , String line2){
 display.clearDisplay();
 display.setTextSize(2);
 display.setCursor(30,2);

60
[M Rizwan Akram]
[2021-MC-293]

 display.print(line1);
 display.setTextSize(1);
 display.setCursor(1,25);
 display.print(line2);
 display.display();
 }
 void getMoisture(){
 sensorVal = analogRead(SensorPin);
 if (sensorVal > (wetSoilVal - 100) && sensorVal < (drySoilVal + 100) ){
 moisturePercentage = map(sensorVal ,drySoilVal, wetSoilVal, 0, 100);
 // Print result to serial monitor
 Serial.print("Moisture Percentage: ");
 Serial.print(moisturePercentage);
 Serial.println(" %");
 }
 else{
 Serial.println(sensorVal);}
 delay(100);}
 void getWeather(){
 float h = dht.readHumidity();
 float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenhei
 if (isnan(h) || isnan(t)) {
 Serial.println("Failed to read from DHT sensor!");
 return;
 }
 else {
 humidity1 = int(h);
 temperature1 = int(t);
 // Serial.println(temperature1);
 // Serial.println(humidity1);} }
 void sendSensor()
 {
 getMoisture(); // get Moisture reading
 getWeather(); // get reading from DHT11
 displayData(String(moisturePercentage) + " %", "T:" + String(temperature1) + " C, H:" +
String(humidity1) + " % " + currMode);
 Blynk.virtualWrite(VPIN_MoistPer, moisturePercentage);
 Blynk.virtualWrite(VPIN_TEMPERATURE, temperature1);
 Blynk.virtualWrite(VPIN_HUMIDITY, humidity1);

61
[M Rizwan Akram]
[2021-MC-293]

 }
 void controlMoist(){
 if(prevMode){
 if (moisturePercentage < (moistPerLow)){
 if (toggleRelay == LOW){
 controlBuzzer(500);
 digitalWrite(RelayPin, HIGH);
 toggleRelay = HIGH;
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);
 delay(1000);} }
 if (moisturePercentage > (moistPerHigh)){
 if (toggleRelay == HIGH){
 controlBuzzer(500);
 digitalWrite(RelayPin, LOW);
 toggleRelay = LOW;
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);
 delay(1000);} } }
 else{
 button1.check();}}
 void setup() {
 // Set up serial monitor
 Serial.begin(115200);
 // Set pinmodes for GPIOs
 pinMode(RelayPin, OUTPUT);
 pinMode(wifiLed, OUTPUT);
 pinMode(ModeLed, OUTPUT);
 pinMode(BuzzerPin, OUTPUT);
 pinMode(RelayButtonPin, INPUT_PULLUP);
 pinMode(ModeSwitchPin, INPUT_PULLUP)
 digitalWrite(wifiLed, LOW);
 digitalWrite(ModeLed, LOW);
 digitalWrite(BuzzerPin, LOW);
 dht.begin(); // Enabling DHT sensor
 config1.setEventHandler(button1Handler);
 config2.setEventHandler(button2Handler);
 button1.init(RelayButtonPin);
 button2.init(ModeSwitchPin);
 if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
 Serial.println(F("SSD1306 allocation failed"));

62
[M Rizwan Akram]
[2021-MC-293]

 for(;;);
 }
 delay(1000);
 display.setTextSize(1);
 display.setTextColor(WHITE);
 display.clearDisplay();
 WiFi.begin(ssid, pass);
 timer.setInterval(2000L, checkBlynkStatus); // check if Blynk server is connected every 2
seconds
 timer.setInterval(3000L, sendSensor); // display and send sensor reading every 3
seconds
 Blynk.config(auth);
 //delay(1000);
 controlBuzzer(1000);
 digitalWrite(ModeLed, prevMode);
 }
 void loop() {
 Blynk.run();
 timer.run(); // Initiates SimpleTimer

 button2.check();
 controlMoist();
 }
 void button1Handler(AceButton* button, uint8_t eventType, uint8_t buttonState) {
 Serial.println("EVENT1");
 switch (eventType) {
 case AceButton::kEventReleased:
 //Serial.println("kEventReleased");
 digitalWrite(RelayPin, !digitalRead(RelayPin));
 toggleRelay = digitalRead(RelayPin);
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);
 break;
 }
 }
 void button2Handler(AceButton* button, uint8_t eventType, uint8_t buttonState) {
 Serial.println("EVENT2");
 switch (eventType) {
 case AceButton::kEventReleased:
 //Serial.println("kEventReleased");

63
[M Rizwan Akram]
[2021-MC-293]

 if(prevMode && toggleRelay == HIGH){


 digitalWrite(RelayPin, LOW);
 toggleRelay = LOW;
 Blynk.virtualWrite(VPIN_RELAY, toggleRelay);
 }
 prevMode = !prevMode;
 currMode = prevMode ? "A" : "M";
 digitalWrite(ModeLed, prevMode);
 Blynk.virtualWrite(VPIN_MODE_SWITCH, prevMode);
 controlBuzzer(500);
 break;
 }
 }

Final:

Conclusion:
The developed IoT-based plant monitoring system showcases the integration of hardware
components, wireless communication, and intelligent control logic. The optional inclusion of an
RTOS enhances system efficiency. This project provides valuable insights into the design and
deployment of IoT solutions for agriculture, promoting sustainable and data-driven plant care.

Lab # 15,16

64
[M Rizwan Akram]
[2021-MC-293]

Review and project showcase


Objective:
1. Review of key concepts and experiments
2. Student presentations showcasing their case study projects

Review and Project Showcase:


1. Review of Key Concepts and Experiments
Smart Agriculture and IoT Integration
The IoT-Based Plant Monitoring System is a culmination of key concepts in smart agriculture
and IoT. The project incorporates:
ESP32 Dev Module:
Serving as the central processing unit, the ESP32 efficiently manages data from various sensors
and controls the system.

Sensors:
Soil moisture and DHT11 sensors provide real-time information on soil conditions, temperature,
and humidity, contributing to optimal plant health.
 Soil Moisture Sensor
The soil moisture sensor measures the volumetric water content in the soil. It provides
continuous data, allowing the system to make informed decisions about irrigation.

 DHT11 Sensor

65
[M Rizwan Akram]
[2021-MC-293]

The DHT11 sensor records the temperature and humidity of the environment, offering
additional insights into the plant's surroundings.
Actuators:
The submersible pump, buzzer, and LEDs automate irrigation and alert users to extreme
conditions.
 Submersible Pump
The submersible pump is activated automatically when the soil moisture level is
critically low, ensuring that the plant receives adequate water.

Blynk Mobile Application:


The integration of the Bylink app enables remote monitoring and control, enhancing
accessibility for users.

Embedded System Implementation


The hardware components, including the ESP32 Dev Module, sensors, and actuators, are
thoughtfully integrated. The circuit design and PCB layout demonstrate reliability and ease of
assembly.
Software Implementation:
The software, a combination of C programming for the ESP32 and the Bylink mobile
application, showcases effective language integration for system control and monitoring.
System Operation:
The operational flow, from system initialization to data acquisition, display updates, alert
mechanisms, and remote control functionality, ensures a comprehensive approach to plant
monitoring and care.

Student Presentations Showcasing Case Study Projects


Project: "Optimal Growth Buddy"
Presented by [Muhammad Rizwan Akram]

66
[M Rizwan Akram]
[2021-MC-293]

Overview:
Optimal Growth Buddy aims to create an intelligent plant care system. By integrating moisture,
temperature, and humidity data, the project ensures an environment conducive to plant growth.

Components:
1. ESP32 Dev Module
2. Soil Moisture Sensor
3. DHT11 Sensor
4. Submersible Pump, Buzzer, LEDs
5. Bylink Mobile Application

Demonstration:
The live demonstration showcases the system's responsiveness to changing soil conditions. The
Bylink app allows users to remotely activate the pump and receive real-time updates.

Challenges Faced:
Overcoming sensor calibration challenges was a key aspect. The team implemented a robust
calibration method to ensure accurate readings.

Learnings:
The project enriched the team's understanding of IoT integration and real-world application of
sensor data in agriculture. Collaboration skills were enhanced during the development process.

Future Enhancements:
Suggestions include implementing machine learning for predictive analysis and exploring solar-
powered solutions for sustainability.

Conclusion:

67
[M Rizwan Akram]
[2021-MC-293]

The "Review and Project Showcase" section highlights the successful integration of theoretical
concepts into practical applications. Student presentations provide insights into the creativity,
problem-solving skills, and collaborative efforts involved in developing IoT-based solutions for
plant monitoring and care.

__________________________
THE END

68

You might also like