Embedded Final Lab Report PDF
Embedded Final Lab Report PDF
[2021-MC-293]
2021-MC-293
Section A
1
[M Rizwan Akram]
[2021-MC-293]
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
3
[M Rizwan Akram]
[2021-MC-293]
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:
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:
9
[M Rizwan Akram]
[2021-MC-293]
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]
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]
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]
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.
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.
22
[M Rizwan Akram]
[2021-MC-293]
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.
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.
26
[M Rizwan Akram]
[2021-MC-293]
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
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.
29
[M Rizwan Akram]
[2021-MC-293]
30
[M Rizwan Akram]
[2021-MC-293]
31
[M Rizwan Akram]
[2021-MC-293]
Device Selection:
32
[M Rizwan Akram]
[2021-MC-293]
33
[M Rizwan Akram]
[2021-MC-293]
34
[M Rizwan Akram]
[2021-MC-293]
35
[M Rizwan Akram]
[2021-MC-293]
Verifying:
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.
37
[M Rizwan Akram]
[2021-MC-293]
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]
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]
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.
42
[M Rizwan Akram]
[2021-MC-293]
43
[M Rizwan Akram]
[2021-MC-293]
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]
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.
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]
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.
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.
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]
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]
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]
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]
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]
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.
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