0% found this document useful (0 votes)
9 views

Microcontroller Based Design Lab Manual - Updated Mar 2023

The document is a laboratory manual for experiments in microcontroller-based design, specifically using the STM32F103 microcontroller. It includes a list of authors, a preface detailing the background of Dr. Musharraf Ahmed Hanif, and an introduction to the manual's purpose and structure. The manual outlines various experiments, objectives, required equipment, and detailed steps for setting up and programming the microcontroller.

Uploaded by

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

Microcontroller Based Design Lab Manual - Updated Mar 2023

The document is a laboratory manual for experiments in microcontroller-based design, specifically using the STM32F103 microcontroller. It includes a list of authors, a preface detailing the background of Dr. Musharraf Ahmed Hanif, and an introduction to the manual's purpose and structure. The manual outlines various experiments, objectives, required equipment, and detailed steps for setting up and programming the microcontroller.

Uploaded by

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

LABORATORY

MANUAL
EXPERIMENTS IN

MICROCONTROLLER BASED DESIGN

FACULTY OF ENGINEERING

UNIVERSITY OF CENTRAL PUNJAB

M
LIST OF AUTHORS

Sr. # Name Date Modified Contributions


1 Dr. M.A.Hanif 1st Aug 2017 Creation from scratch
2 Engr. Anam Dar 25th Feb, 2019 Revised
3 Addition of Experiments
Engr. Arslan Formatting of Manual
21st Oct, 2021
Ahmad CLO-PLO Mapping
Rubrics
4 Revision and Modification of all
Engr. Jawad Khalid 20th February
STM32 Controller Experiments
Qureshi 2022
5 Addition of Experiments
Dr. Arslan Arif &
Formatting of Manual
Engr. Jawad Khalid 1st March 2023
CLO-PLO Mapping
Qureshi
Rubrics
6
7
8
9
10

Microcontroller Based Design i


LABORATORY MANUAL

EXPERIMENTS IN

MICROCONTROLLER BASED DESIGN


Revised Mar, 2023

DR. MUSHARRAF AHMED HANIF


Assistant Professor of Electrical Engineering

University of Central Punjab, Lahore

Microcontroller Based Design ii


EXPERIMENTS IN

MICROCONTROLLER BASED DESIGN

Copyrights © Reserved with the Electrical Engineering Department (EED)

This manual or parts, thereof, may not be reproduced in any from without Permission of the
EED.

Microcontroller Based Design iii


PREFACE
Dr. Musharraf Ahmed Hanif is an Assistant Professor of Electrical Engineering at the University of
Central Punjab (UCP), Lahore, Pakistan. He got his B.Sc. in Electronics Engineering from Ghulam
Ishaq Khan Institute of Engineering Sciences and Technology (1998-2002). He did his M.Sc. in
Embedded Systems and Controls (2003-2004) and Ph.D. in High Reliability Embedded Systems
(2007-2012) both from University of Leicester, U.K.

Before joining the teaching profession, Dr. Musharraf Ahmed Hanif had extensive experience in
Industrial/Company in terms of Electronics/Embedded system engineer based projects in K.S.A. and
U.K. He had started his teaching carrier as a Lab Instructor in University of Leicester, U.K. during his
Ph.D. studies. He joined University of Lahore in May 2012 as Assistant Professor in Electrical
Engineering Department. In 2014, He helped to setup the newly formed Computer Engineering
Department at University of Central Punjab. He finally transferring to the Electrical Engineering
Department in 2016.

Dr. Musharraf Ahmed Hanif’s areas of interest are:

❖ High Reliability Embedded Systems


❖ Digital Systems and Design
❖ Robotics and Controls Systems
❖ Automation

Microcontroller Based Design iv


INTRODUCTION

Microcontroller based System Designs manual presents a series of experiments dealing with the
understanding of different roles of a microcontroller. The course of Microcontroller based design is
usually offered in the last semesters of engineering as an elective course. Manual is supposed to be
used in conjunction with the reference manual and data sheet of the STM32F103 microcontroller. This
mode of teaching helps the students to develop the skill set necessary to allow them to work with any
known of unknown microcontroller that they might encounter in their future endeavors.

Each experiment is accompanied by a set of objectives, a list of equipment required followed by a


discussion of theoretical concepts that are investigated or analyzed.

The sequence and scope of the experiments in this manual are related to the theoretical material
covered in the text book and analysis based on control system application. All the experiments have
been student tested and revised where necessary to improve clarity. Any comments or suggestions to
improve the style, scope or clarity of any experiment are welcome.

I wish to thank Dr. Ali Nasir who gave me a lot a leeway in redesigning this course and its associated
labs in light of my experience in this field.

DR. MUSHARRAF AHMED HANIF

Authors

Microcontroller Based Design v


MICROCONTROLLER BASED DESIGN

CONTENTS

EXP # NAME OF EXPERIMENT PAGE #


1. Setting Up Development Environment for STM32 8
2. Practice on different scenarios of GPIO pins on STM32-F103 14
3. Getting familiar with Registers and Interfacing of GPIOs of 19
STM32F1xx
Introduction and usage of Debug mode of STM32Cube IDE
4. 27
5. Getting familiar with High Speed Clock configuration of STM32F1xx 31
6. Practice session for Previous lab experiments
7. Interfacing of 20x4 LCD with STM32F1xx 38
8. Integration of Keypad with STM32F1xx Controller 43
9. Integration of UART in STM32F1xx Controller IDE 49
10. Programming Exercises Using STM32F10xx Instructions 53
11. Integration of I2C in STM32F1xx Controller IDE 54
12. Integration of ADC in STM32F1xx Controller using USART 62
13. Integration of Motors with STM32F1xx Controller 67
14. Implementation of External and Timer Interrupts with STM32F1xx 72
Controller
Design Project
15. 76
Appendix A Lab CLOs 77
Appendix B Lab Evaluation Rubrics 77
Appendix C Sample Lab Report 80
Appendix D Lab Evaluation Criteria 82
Appendix E Lab Safety Rules
82

Microcontroller Based Design vi


Experiment No. 1

Setting Up Development Environment for STM32


Objective
To learn how to create a new project and use development tools to build programs.

Equipment
PC with the installed IDE, compiler and link utility software:

STM32CubeIDE 1.7.0 for STM32 (Editor, Linker, Debugger)

STM32 Cube IDE and Workspaces


STM32CubeIDE 1.7.0 is the IDE that will be used in this lab to write our programs for STM32F103
microcontroller. It contains the editor as well as the debugger that we can use to make as well as
test our embedded application. It uses workspace to store and manage our projects. A workspace is
a folder where we can store projects related to each other.
It is recommended to create a workspace folder on your Z Drive.
Creating a new project
The following steps will guide you through the creation of a new projects. These steps will need
to be followed whenever you are starting a new project.
1. Launch STM32CubeIDE 1.7.0 from C:\ST\STM32CubeIDE_1.7.0\STM32CubeIDE\
stm32cubeide.exe
2. When prompted to select workspace directory, click on Browse, go to the desired location
where you want your projects to be stored and create a New Folder.
Make sure that the workspace folder and project names have no spaces. Underscores are
fine.
It is recommended to use your Z Drive to save your workspaces in lab so that it is accessible all
the time.

Figure 1.1 STM32 CubeIDE Workspaces

Microcontroller Based Design 77


3. Click on Start new STM32 Project, a new pop up will appear which require some files
downloading from Internet

4. A new menu option will open as per follow

5. Among Target selection, click on Board Selector option, and type NUCLEO-F103RB (as this
is the board on which we will be working) in Commercial Part Number space.
6. Once Nucleo board is filtered from other options, select the board in the right bottom corner
and click on Next

Microcontroller Based Design 88


7. A new menu option will appear, in which you will be required to type Project Name (without
spaces, underscores are accepted)
8. Targeted language will be C (If you are familiar with C++, you can select it as well as there are
some syntax changes)
9. Targeted Binary Type will be selected Executable and Targeted Project Type will be selected
STM32Cube. Once all options are selected, click on Finish

10. Once you will click on Finish, following pop-up will appear

11. Click on Yes, again a new pop-up will appear, which will ask you to move ahead with
Configuration Tool Perspective, click on Yes

Microcontroller Based Design 99


12. Once selected, Device Configuration Toolbox will start loading with some software packages
download from time to time.
13. Once all software packages are downloaded and installed, following window will appear

14. These windows show STM32 microcontroller with some GPIO pins configured by default
(Green and Yellow).
15. On left, multiple menu pop-ups are available which can show System Core, Analog, Timers
selection, Connectivity options, Computing methods which we select by clicking on them.
16. In this lab, we are going to discuss GPIO pins and their basic configuration.
17. We are going to use PA5 (Port A Pin 5) as Output pin on which led is already connected on
Nucleo board.

18. If we left click on PA5, a pop-up will appear, on which you can see that this pin is already
configured as GPIO Output pin.
19. By default, this pin is configured as LD2. If you want to change User Label, right click on
PA5, and click on Change User Label and Enter new name (without any spaces).

Microcontroller Based Design 10


10
20. Save this configuration, once file is saved. Program will pop-up to confirm to Open Generated
Code. Click YES and a C program will open in Editor containing all preset conditions.
21. This program contains all functions for times, GPIO’s and connectivity.
22. You will start typing your code in the while (1) portion as per following figure

23. Syntax for operating GPIO pin is: HAL_GPIO_WritePin(GPIOx, GPIO_Pin, PinState)
24. HAL→Hardware Abstraction Layer,
25. GPIOx→You will select port on which LED is connected.
26. GPIO_Pin→You will select pin on which LED is connected.
27. PinState→You are going select state of Pin (High or Low). Select Set for 1 value and Reset
for 0 value.
28. For toggling PA5 for 1 second, following code will be written.
HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, SET);
HAL_Delay(1000);
HAL_GPIO_WritePin(LED1_GPIO_Port, LED1_Pin, RESET);
HAL_Delay(1000);

29. Select for Debugger to check if there are any syntax errors. If no errors are detected, press

for compiling the code. Make sure to connect your Nucleo board with your PC before pressing
Compilation.
30. Once your code is compiled, you can check on your Nucleo board that LED is blinking with 1 second
delay.

Lab Assignments:
1. What is an IDE? What is the name and version of the IDE used in this lab?
2. What is a compiler? What are its input and output files? Which compiler is used in this
lab?
3. What is a linker? What are its input and output files? Which linker is used in this lab?
4. What is a simulator? Which simulator is used in this lab?
5. What is the purpose of ST-Link utility?
Microcontroller Based Design 11
11
6. How many LEDs are on our STM32F103 board and what are their purposes?
7. Write down the names of the files in folder ‘Lab1’ that contain software code in them for
the target device.
8. What is the name and extension of file that is downloaded on the STM32 board?
9. What are your observations from running the program in the simulator?
10. Make a program to read state of built-in switch on your Nucleo board through code
11. Make a program to read state of built-in switch and control the built-in LED on your
Nucleo board though code.

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 12


12
EXPERIMENT 2
Practice on different scenarios of GPIO pins on STM32-F103
Objective
To learn how to use and operate GPIO pins using HAL library using different scenarios

Equipment
PC with the installed IDE, compiler and link utility software:

STM32CubeIDE 1.7.0 for STM32 (Editor, Linker, Debugger)

Creating a new project


The following steps will guide you through the creation of a new projects. These steps will need
to be followed whenever you are starting a new project.
31. Launch STM32CubeIDE 1.7.0 from C:\ST\STM32CubeIDE_1.7.0\STM32CubeIDE\
stm32cubeide.exe
32. When prompted to select workspace directory, click on Browse, go to the desired location
where you want your projects to be stored and create a New Folder.
Make sure that the workspace folder and project names have no spaces. Underscores are
fine.

Figure 2.1 STM32 CubeIDE Workspaces

Microcontroller Based Design 13


13
33. Click on Start new STM32 Project, a new pop up will appear which require some files
downloading from Internet

Figure 2.2: STM32 Project Menu

34. A new menu option will open as per follow

Figure 2.3: STM32 Cube IDE Board Selector Menu

35. Among Target selection, click on Board Selector option, and type NUCLEO-F103RB (as this
is the board on which we will be working) in Commercial Part Number space.

Microcontroller Based Design 14


14
36. Once Nucleo board is filtered from other options, select the board in the right bottom corner
and click on Next

37. A new menu option will appear, in which you will be required to type Project Name (without
spaces, underscores are accepted)
38. Targeted language will be C (If you are familiar with C++, you can select it as well as there are
some syntax changes)
39. Targeted Binary Type will be selected Executable and Targeted Project Type will be selected
STM32Cube. Once all options are selected, click on Finish

40. Once you will click on Finish, following pop-up will appear

Microcontroller Based Design 15


15
41. Click on Yes, again a new pop-up will appear, which will ask you to move ahead with
Configuration Tool Perspective, click on Yes

42. Once selected, Device Configuration Toolbox will start loading with some software packages
download from time to time.
43. Once all software packages are downloaded and installed, following window will appear

44. These windows show STM32 microcontroller with some GPIO pins configured by default
(Green and Yellow).
45. On left, multiple menu pop-ups are available which can show System Core, Analog, Timers
selection, Connectivity options, Computing methods which we select by clicking on them.
46. In this lab, we are going to discuss GPIO pins and their basic configuration.

Microcontroller Based Design 16


16
Figure 2.4: Nucelo F103 board pinout diagram

Lab Assignments:
12. Make a program to read state of built-in switch on your Nucleo board through code
13. Make a program to read state of built-in switch and control the built-in LED on your Nucleo
board though code.
14. Make a program to implement traffic signal through GPIO pins PA7 (Red), PB2 (Yellow)
and PB4 (Green) with a with a delay of 1 sec and 500 ms using external LED’s
15. Make a program to implement traffic signal on a intersection by using 6 GPIO pins as output
pins
16. Make a program to control blinking of LED connected on PA4 by using external button on
PB2 as pe following scenario
a. When button is pressed 1st time, LED blinks with a delay of 500 ms
b. When button is pressed 2nd time, LED blinks with a delay of 1 second
c. When button is pressed 3rd time, LED turns off

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________
Microcontroller Based Design 17
17
Experiment No. 3
Getting familiar with Registers and Interfacing of GPIOs of
STM32F1xx
Objective
• To learn how to debug, flash and run a program on STM board
• To practice finding information from the device’s documentation and applying that information

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
Hexadecimal numbers are used extensively as binary numbers can be compactly and quickly
represented in hexadecimal. Each hexadecimal digit is equivalent to four binary digits.
This is given in the table 3.1:

Table 3.1: Hexadecimal conversion in Binary

Hexadecimal Binary Hexadecimal Binary


0 0000 8 1000
1 0001 9 1001
2 0010 A 1010
3 0011 B 1011
4 0100 C 1100
5 0101 D 1101
6 0110 E 1110
7 0111 F 1111

Example of binary to hexadecimal: the binary number 101101010010 is equal to B52 in


hexadecimal.
Hexadecimal numbers are represented in C by using the prefix 0x before the number. e.g.
the above number will be written as 0xB52 or 0xb52 in C.
Bitwise operators in C
C provides six operators for bit manipulation.
Table 3.2: Bitwise Operators with symbols

Symbol Operator
& bitwise AND
| bitwise inclusive OR
^ bitwise XOR (eXclusive OR)
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)
Microcontroller Based Design 18
18
Bitwise AND &

The bitwise AND operator is a single ampersand: &. It is just a representation of AND which
does its work on the bits of the operands rather than the truth value of the operands. Bitwise
binary AND does the logical AND (as shown in the table above) of the bits in each position
of a number in its binary form.

Bitwise OR |

Similar to bitwise AND, bitwise OR only operates at the bit level. Its result is a 1 if one of the either
bits is 1 and zero only when both bits are 0. Its symbol is | which can be called a pipe.

Bitwise XOR ^

The bitwise XOR (exclusive or) performs a logical XOR function, which is equivalent to
adding two bits and discarding the carry. The result is zero only when we have two zeroes or
two ones. XOR can be used to toggle the bits between 1 and 0. Thus i = i ^ 1 when used in a
loop toggles its values between 1 and 0.

Bitwise NOT ~ / ones' complement (unary)

The ones' complement (~) or the bitwise complement gets us the complement of a given
number. Thus we get the bits inverted, for every bit 1 the result is bit 0 and conversely for
every bit 0 we have a bit 1. This operation should not be confused with logical negation !.

Right shift >>

The symbol of right shift operator is >>. For its operation, it requires two operands. It shifts
each bit in its left operand to the right. The number following the operator decides the number
of places the bits are shifted (i.e. the right operand). Thus by doing ch >> 3 all the bits will be
shifted to the right by three places and so on.

Left shift <<

The symbol of left shift operator is <<. It shifts each bit in its left-hand operand to the left by
the number of positions indicated by the right-hand operand. It works opposite to that of right
shift operator. Thus by doing ch << 1 in the above example we have 11001010. Blank spaces
generated are filled up by zeroes as above.

Bit manipulation using read-modify instructions

Bitwise logical AND and OR operations can be used to set and clear targeted bits.

Microcontroller Based Design 19


19
Masking bits to 1

To turn certain bits on, the bitwise OR operation can be used, following the principle that Y OR
1 = 1 and Y OR 0 = Y. Therefore, to make sure a bit is on, OR can be used with a 1. To leave a
bit unchanged, OR is used with a 0.

Example: Masking on (1) the higher nibble (bits 4, 5, 6, 7) the lower nibble (bits 0, 1, 2, 3)
unchanged.

10010101

OR

11110000

= 11110101

Masking bits to 0

To turn certain bits off, the bitwise AND operation can be used, following the principle that Y
AND 1 = Y and Y AND 0 = 0. Therefore, to make sure a bit is off, AND can be used with a 0. To
leave a bit unchanged, AND is used with a 1.

Example: Masking off (0) the higher nibble (bits 4, 5, 6, 7) the lower nibble (bits 0, 1, 2, 3)
unchanged.

10010101 10100101
AND 00001111 00001111
= 00000101 00000101

Using Read-Modify to change only some bits while leaving the rest unchanged

Two steps are involved if we want to change only some bits of a variable or register while
leaving the rest unchanged:

• Bitwise AND with a mask to clear only the bits that we want to change.
• Logical OR with the data that we want to store at the bits that we want to modify.

Example: To change bits 3:2 of A to 012.

Step 1 mask:
111100112

Step 2 data:
000001002

Microcontroller Based Design 20


20
A:
110010102

A & mask:
110000102

A | data:
110001102

This will be written in C as either

A &= 0xF3; A |= 0x04; Or as

A = (A & 0xF3) | 0x04;

Querying the status of a bit

It is possible to use bitmasks to easily check the state of individual bits regardless of the other bits.
To do this, turning off all the other bits using the bitwise AND is done as discussed above and
the value is compared with 1. If it is equal to 0, then the bit was off, but if the value is any other
value, then the bit was on. What makes this convenient is that it is not necessary to figure out what
the value actually is, just that it is not 0.

Example: Querying the status of bit number 3

10011101

AND 00001000

= 00001000

Blinking LED on PA5:

In STM32Cube IDE, we are going to use GPIO PA5 as output and blink led with defined delay.
We are going to perform this task with the help of registers. Our program flow will be as follows

• Clock initialization and configuration


• GPIO pins configuration
• Timer initialization and integration

To initialize clock and configure for PA5, following functions and commands will be used

#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))


#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
RCC_APB2ENR |=0x00000004; // This value is for selecting Port A
RCC_APB1ENR |=0x00000001; // This value is for selecting Timer 2

Microcontroller Based Design 21


21
Figure 3.2: APB2ENR Register (Ref. manual 7.3.7) Pg. 113

Figure 3.3: APB1ENR Register (Ref. manual 7.3.8) Pg. 115

To blink led, we need to configure pin 5 of port A. For that, following syntax will be used.

#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))


#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

GPIOA_CRL &=0xFF2FFFFF;
GPIOA_CRL |=0xFF2FFFFF;

Figure 3.4: GPIO PA5 mode and configuration selection (Ref. manual 9.2.1)
GPIOA_BSRR=0x00000020; //For setting pin 5
GPIOA_BSRR=0x00200000; //For resetting pin 5

Figure 3.5: GPIO_BSRR Pin (Set/Reset) selection (Ref. manual 9.2.5)

Now the third part is to enable timer and set its value.

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

Microcontroller Based Design 22


22
TIM2_CR1=0; //To stop
TIM2_CNT=0; //To reset counter
TIM2_PSC=value; //To assign value to prescale
TIM2_ARR=value; //To assign value which serves as limit
TIM2_CR1=1; //To start process

Now, all the necessary functions have been discussed. To blink led on PA5, following logic can be
implemented.

#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))


#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))

#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))


#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

void main ()
{ RCC_APB2ENR |=0x00000004;
RCC_APB1ENR |=0x00000001;

TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=999;

GPIOA_CRL &=0xFF2FFFFF;
GPIOA_CRL |=0xFF2FFFFF;
while (1)
{ GPIOA_BSRR=0x00000020; //SET
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
GPIOA_BSRR=0x00200000; //RESET
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}
}

Microcontroller Based Design 23


23
Lab Assignments:
1. Connect led’s on PA2, PA4, PA6 and PA8.Write a code on STM32cube IDE to display them
in pattern
2. Write a code on STM32Cube IDE to control led on PC8 by user button
3. Connect led’s on PA2, PB12, PC6, PC9. Write a code on STM32cube IDE to control these
leds by user button in following order
1st press Led on PA2 turns on

2nd press Led on PA2 turns off and led on PB12 turns on

3rd process Led on PA2 & PB12 remains off and led on PC6 turns on

4th press Led on PA2, PB12, PC6 remain off and led on PC9 turns on

4. Write a code on STM32cube IDE to configure the pins of Port A according to the following
table:

Pin Operating mode Pin Operating mode


PA0 Input floating PA8 Alternate Function 2 MHz Push-Pull.
PA1 General purpose 2 MHz Open Drain. PA9 Alternate Function 10 MHz Push-Pull.
PA2 Alternate Function 50MHz Push-Pull. PA10 Alternate Function 50 MHz Open drain.
PA3 Input pull up. PA11 Input pull down
PA4 Analog PA12 NO CHANGE
PA5 General purpose 10 MHz Push-Pull. PA13 Input floating
PA6 Analog PA14 NO CHANGE
PA7 Analog PA15 NO CHANGE

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 24


24
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Getting familiar with Registers and Interfacing of GPIOs of STM32F1xx
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 25


25
Experiment No. 4
Introduction and usage of Debug mode of STM32Cube IDE
Objective
• To learn how to use debug mode of STM32Cube IDE
• To practice finding information from the debug mode (Registers, GPIO’s, variables)

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
Debugging information is generated by the compiler together with the machine code. It is a
representation of the relationship between the executable program and the original source code.
This information is encoded into a pre-defined format and stored alongside the machine code.
Debugging information is mandatory to set breakpoint or get the content of a variable.

It can be utilized to check movement and manipulation of data as instructions are given.

Debug can be selected by clicking Debug Button in Toolbar. To utilize Debug option, STM32-
F103 Nucleo board should be connected to your computer.

Figure 4.1: STM32 Cube IDE Toolbar option for Debug

Once Debug option is selected, a new window will open

Figure 4.2: STM32 Cube IDE Debug Window

Microcontroller Based Design 26


26
Figure 4.3: STM32 Cube IDE Debug Menu Options

• Step Over: This function will execute every command and loads its result in respective
register/variable/expression.
• Step Into: This function will go into the function and then executes every single command
and load its result in respective register/variable/expression.
• Terminate: This function will exit the Debug Window and reload actual program in Cube
IDE
• Resume: This function will start to execute the functions/commands in normal manner
• Terminate and Relaunch: This function will disconnect Debug mode and reload Debug
mode.

As in Lab 3 manual, we started to perform Bare metal coding and toggled built-in LED on PA5
with a delay of 1 second. Here, we will check the results as every single command is executed.

PA5 is in GPIO A.

Figure 4.4: GPIOA registers

Figure 4.5: TIM2 registers with their memory addresses

Microcontroller Based Design 27


27
As you will click Step Over function, single command will be executed. You can see results in
registers and understand execution of every command and how values move in Hexadecimal,
decimal and binary format.

Lab Assignments:
5. Write a code on STM32Cube IDE to control led on PC8 by user button and validate through
Debug mode.
6. Connect leds on PA2, PB12, PC6, PC9. Write a code on STM32cube IDE to control these leds
by user button in following order and validate through Debug mode
1st press Led on PA2 turns on

2nd press Led on PA2 turns off and led on PB12 turns on

3rd process Led on PA2 & PB12 remains off and led on PC6 turns on

4th press Led on PA2, PB12, PC6 remain off and led on PC9 turns on

7. Write a code to toggle LED on PC2 with turn on delay of 750 ms and turn off delay of 250 ms
and validate through Debug mode.

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 28


28
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Introduction and usage of Debug mode of STM32Cube IDE
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 29


29
EXPERIMENT 5
Getting familiar with High Speed Clock configuration of STM32F1xx
Objective
• To learn how to configure different clock sources available to run program on STM board
• To practice finding information from the device’s documentation and applying that information

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
Three different clock sources can be used to drive the system clock (SYSCLK):

• HSI oscillator clock


• HSE oscillator clock
• PLL clock

The devices have the following two secondary clock sources:

• 40 kHz low speed internal RC (LSI RC), which drives the independent watchdog and
optionally the RTC used for Auto-wakeup from Stop/Standby mode.
• 32.768 kHz low speed external crystal (LSE crystal), which optionally drives the real-time
clock (RTCCLK)

Each clock source can be switched on or off independently when it is not used, to optimize power
consumption.

Several prescalers allow the configuration of the AHB frequency, the high-speed APB(APB2) and
the low speed APB (APB1) domains. The maximum frequency of the AHB and the APB2 domains
is 72 MHz. The maximum allowed frequency of the APB1 domain is 36 MHz. The SDIO AHB
interface is clocked with a fixed frequency equal to HCLK/2

The RCC feeds the Cortex System Timer (SysTick) external clock with the AHB clock (HCLK)
divided by 8. The SysTick can work either with this clock or with the Cortex clock (HCLK),
configurable in the SysTick Control and Status Register. The ADCs are clocked by the clock of
the High-Speed domain (APB2) divided by 2, 4, 6 or 8.

The Flash memory programming interface clock (FLITFCLK) is always the HSI clock.

Microcontroller Based Design 30


30
Figure 5.6: Clock Tree (Ref. manual) Pg. 93

HSI clock

The HSI clock signal is generated from an internal 8 MHz RC Oscillator and can be used directly
as a system clock or divided by 2 to be used as PLL input.

The HSI RC oscillator has the advantage of providing a clock source at low cost (no external
components). It also has a faster startup time than the HSE crystal oscillator however, even with
calibration, the frequency is less accurate than an external crystal oscillator or ceramic resonator.

Microcontroller Based Design 31


31
Calibration

RC oscillator frequencies can vary from one chip to another due to manufacturing process
variations, therefore each device is factory calibrated by ST for 1% accuracy at T =25°C.

After reset, the factory calibration value is loaded in the HSICAL [7:0] bits in the Clock control
register (RCC_CR).

If the application is subject to voltage or temperature variations this may affect the RC oscillator
speed. You can trim the HSI frequency in the application using the HSITRIM [4:0] bits in the
Clock control register (RCC_CR).

The HSIRDY flag in the Clock control register (RCC_CR) indicates if the HSI RC is stable or not.
At startup, the HSI RC output clock is not released until this bit is set by hardware. The HSI RC
can be switched on and off using the HSION bit in the Clock control register (RCC_CR).

The HSI signal can also be used as a backup source (Auxiliary clock) if the HSE crystal oscillator
fails. Refer to Section 7.2.7: Clock security system (CSS) in Reference Manual.

HSE Clock

The high-speed external clock signal (HSE) can be generated from two possible clock sources:

1. HSE external crystal/ceramic resonator


2. HSE user external clock

The resonator and the load capacitors must be placed as close as possible to the oscillator pins to
minimize output distortion and startup stabilization time. The loading capacitance values must be
adjusted according to the selected oscillator.

External source (HSE bypass)

In this mode, an external clock source must be provided. It can have a frequency of up to 25 MHz.
You select this mode by setting the HSEBYP and HSEON bits in the Clock control register
(RCC_CR). The external clock signal (square, sinusoidal or triangle) with ~50% duty cycle has to
drive the OSC_IN pin while the OSC_OUT pin should be left hi-Z.

External crystal/ceramic resonator (HSE crystal)

The 4 to 16 MHz external oscillator has the advantage of producing a very accurate rate on the
main clock. The associated hardware configuration is shown in Figure 5.2. Refer to the electrical
characteristics section of the datasheet for more details.

The HSERDY flag in the Clock control register (RCC_CR) indicates if the high-speed external
oscillator is stable or not. At startup, the clock is not released until this bit is set by hardware. An
interrupt can be generated if enabled in the Clock interrupt register (RCC_CIR).

Microcontroller Based Design 32


32
The HSE Crystal can be switched on and off using the HSEON bit in the Clock control register
(RCC_CR).

Figure 5.2: External Clock Sources (Ref. manual) Pg. 94

PLL

The internal PLL can be used to multiply the HSI RC output or HSE crystal output clock frequency.

The PLL configuration (selection of HSI oscillator divided by 2 or HSE oscillator for PLL input
clock, and multiplication factor) must be done before enabling the PLL. Once the PLL enabled,
these parameters cannot be changed.

An interrupt can be generated when the PLL is ready if enabled in the Clock interrupt register
(RCC_CIR).

If the USB interface is used in the application, the PLL must be programmed to output 48 or 72
MHz. This is needed to provide a 48 MHz USBCLK.

Enabling HSE (or HIS) as system clock:

By default, when STM32F103 boots, HSI is enabled as system clock. To run the system on external
oscillator, we need to configure it. Following is the set of logical steps that you need to follow in
order to shift the system on HSE. (Same set of steps with appropriate value can be followed to
switch to HSI as clock source.)

• Clock initialization
• Wait till source is ready
• Configure it as system clock
• Wait till it is applied as system clock
Microcontroller Based Design 33
33
To initialize HSE, we need to configure HSEON bit and check when its ready we have to look at
HSERDY bit. Both bits are in clock control register.

#define RCC_CR ( * ((volatile unsigned long*) 0x40021000))

Figure 5.3: Clock Control Register (Ref. manual 7.3.1) Pg. 99

RCC_CR |=0x00010000; // To switch on HSE


while ((RCC_CR & 0x0002000) == 0); // Wait till HSE is ready

Now we need to configure it as system clock, for that we need clock configuration register.

#define RCC_CFGR ( * ((volatile unsigned long*) 0x40021004))

Figure 5.4: Clock Configuration Register (Ref. manual 7.3.2) Pg. 101

RCC_CFGR &=0xFFFFFFFC; // To reset system clock switch


RCC_CFGR |=0x00000001; // To configure system clock switch as 01 for HSE

while ((RCC_CFGR & 0x0000000C) != 0x4); // Wait till HSE is your system clock

Enabling PLL based system clock:

To run the system on external oscillator, we need to configure it. Following are the set of logical
steps that you need to follow in order to shift the system on PLL based system clock.

• Select PLL source using PLLSRC and PLLXTPRE.


• Decide multiplier as per your requirements using PLLMUL [3:0] bits. (Caution: Frequency
must not exceed 72MHz.)
• PLL Clock initialization using PLLON bit
• Wait till PLL source is ready
• Configure it as system clock
Microcontroller Based Design 34
34
• Wait till it is applied as system clock

Here, we are configuring a 36 MHz clock using PLL and PLL input is HSI div by 2

RCC_CFGR &=0xFFFCFFFF; // Selecting HSI divided by 2 as input


RCC_CFGR |=0x001C0000; //Selecting multiplying factor of 9
RCC_CR |= 0x01000000; //Switch ON PLL
while((RCC_CR & 0x02000000)==0); //wait while PLL is ready

RCC_CFGR &=0xFFFFFFFC; // To reset system clock switch


RCC_CFGR |=0x00000002; // To configure system clock switch as 10 for PLL
while ((RCC_CFGR & 0x0000000C) != 0x8); // Wait till PLL is your system clock

Configuring Pre-scalers for AHB, APB1 and APB2:

The pre-scalers are used to divide the system frequency with a factor so that peripherals on that bus
can be operated with lower frequencies (if required). Pre-scalers can be configured for each bus as
per requirement using the following bits in configuration register.
• HPRE [3:0] for Advanced High-performance Bus
• PPRE1 [2:0] for Advanced Peripheral Bus 1
• PPRE2 [2:0] for Advanced Peripheral Bus 2

Refer to the Reference Manual for appropriate bit values of pre-scalers.

Lab Assignments:
1. Use HSE oscillator as system clock and repeat task 1 from Lab 3. (i.e. Connect LEDs on PA2,
PA4, PA6 and PA8.Write a code on STM32cube IDE to display them in pattern)
2. Configure the following clock configurations and make them your system clock. Verify them
using oscilloscope and debug mode.
a. 48 MHz using HSI
b. 32 MHz using HSE
c. 52 MHz using (HSE)/2
3. If we set SW bits in configuration register as 11, what effect will it make? Use debug to monitor
and explain the reason of this behavior.
4. If we use the blink LED code from lab manual 2 with clock configurations stated in Question
2, how does this effect the blinking frequency? State the reason for that.
5. If we select the appropriate values of pre-scaler for busses, we can negate the effect of higher
frequency on our timer. Select appropriate values for relevant pre-scaler so that if the system
clock is 32MHz, the delay function works as before.

Microcontroller Based Design 35


35
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Getting familiar with High Speed Clock configuration of STM32F1xx
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 36


36
EXPERIMENT 7
Interfacing of 20x4 LCD with STM32F1xx
Objective
• To learn how to interface 20x4 LCD on STM board
• To practice finding information from the device’s documentation and applying that information

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
We are going to use the parallel connection between STM32 and LCD. LCD can be connected in
parallel mode either using 8 data pins or by using 4 bits. In this experiment, we are going to
integrate LCD with STM32 using 4-bit mode. LCD will be connected with STM32 as per given
GPIO pins

• RS → PA8
• RW→ GND
• EN → PA9
• D4 → PA4
• D5 → PA5
• D6 → PA6
• D7 → PA7

Firstly, we are going to set required pins as output pins. Secondly, Timer will be set for delay
purpose.

RCC_APB2ENR |= 0x00000004; → To set Port A


RCC_APB1ENR |= 0x00000001; → To set Timer 2
GPIOA_CRL &= 0x2222FFFF; → To select Pins 4, 5, 6, 7 of Port A
GPIOA_CRL |= 0x22220000; → To select Pins 4, 5, 6, 7 of Port A
GPIOA_CRH &= 0xFFFFFF22; → To select Pins 8 & 9 of Port A
GPIOA_CRH |= 0x00000022; → To select Pins 8 & 9 of Port A

To initialize LCD in 4 bit mode, following sequence must be implemented


void LCD_init(void)
{ Delay(5000);
LCD(0x33,0);
Delay(50);
LCD(0x32,0);
Delay(50);
LCD(0x28,0); //4 bit mode, 2 Line

Microcontroller Based Design 37


37
Delay(50);
LCD(0x01,0); //Clear display
LCD(0x06,0); //Entry mode
LCD(0x80,0); //Force Cursor to beginning of 1st row
LCD(0x0F,0); //Display on, Cursor blinking
}

Once LCD has been initialized in 4-bit mode, we have to consider following settings to operate
LCD

• Higher nibble will be executed first, then lower nibble will be executed as we are connected in
4-bit mode
• When data is sent on data pins, RS value should be 1
• When instructions are sent on data pins, RS value should be 0.
• To execute given command, EN Pin should bet HIGH → LOW

For this, following function will be performed

void LCD(unsigned char val, unsigned char cmd)


{
unsigned char val_1;
val_1 = ((val)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;
GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);

val_1 = ((val<<4)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;
GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);
}

Once all these settings has been made, now we test our LCD by sending 1 as data

LCD(0x31,1); //ASCII 1 value is 0x31 with RS=1

Microcontroller Based Design 38


38
Code:
#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))
#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

void LCD_init(void);
void Delay(int x);
void LCD(unsigned char val, unsigned char cmd);

//RS PA8
//EN PA9
//D4 PA4
//D5 PA5
//D6 PA6
//D7 PA7

void main(void)
{ RCC_APB2ENR |= 0x00000004;
RCC_APB1ENR |= 0x00000001;
GPIOA_CRL &= 0x2222FFFF;
GPIOA_CRL |= 0x22220000;
GPIOA_CRH &= 0xFFFFFF22;
GPIOA_CRH |= 0x00000022;

LCD_init();
LCD(0x31,1);
}
void LCD_init(void)
{ Delay(5000);
LCD(0x33,0);
Delay(50);
LCD(0x32,0);
Delay(50);
LCD(0x28,0); //4 bit mode, 2 Line
Delay(50);
LCD(0x01,0); //Clear display
LCD(0x06,0); //After command/data, shift cursor to right
LCD(0x80,0); //Force Cursor to beginning of 1st row
Microcontroller Based Design 39
39
LCD(0x0F,0); //Display on, Cursor blinking
}
void Delay(int x)
{ TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=x-1;
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}
void LCD(unsigned char val, unsigned char cmd)
{ unsigned char val_1;
val_1 = ((val)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;
GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);

val_1 = ((val<<4)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;
GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);
}

Lab Assignments:
1. Write a code on STM32 to display digits from 0 to 9 with a delay of 500 ms
2. Write a code on STM32 to display your name on First Line of LCD
3. Write a code on STM32 to display appropriate message on LCD when user button is pressed
and released.

Microcontroller Based Design 40


40
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Interfacing of 20 x 4 LCD with STM32F10xx
Name: Reg. No.: Section:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level S Trait Excellent Good Average Poor Grade
r
N
o
.
P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Respons precisely the objectives of follow the objectives of the Good
Tool e follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 quality exceptional easy to read. readable only by organized and very 5
Individual A2 ly well someone who difficult to read. Good
and Team Respon organized knows what it is 4
Work ding to and very supposed to be Average
Phenom easy to doing. 3
ena follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivity is working working properly. partially working. 5
properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 41


41
EXPERIMENT 8
Integration of Keypad with STM32F1xx Controller
Objective
• To learn how to use keypad (3x4 and 4x4)
• To practice different scenarios using Keypad and STMF103rb

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
The matrix keypad is usually a 3 x 4 or 4 x 4 array of buttons arranged in rows and columns. In 3
x 4 keypad, there are three column lines and four row lines (in 4 x 4, there are four column and
four row lines). When any button is pressed it connects its corresponding row and column lines.

Figure 8.7: Four row three column matrix keypad

The main advantage of using a matrix keypad is that it reduces the number of pins required to
connect the buttons to the microcontroller. A 4 x 4 keypad is composed of 16 buttons. Using
conventional means, we would require 16 pins to connect these buttons to the microcontroller.
However, in the matrix configuration, this number is reduced to 8 (4 for the columns and 4 for the
rows respectively.

This reduction in HW resources required for interfacing is achieved at the cost of increased software
complexity. With conventional switches, we read the corresponding pin to see if the switch is
pressed. In the matrix keypad, the rows and columns have to be scanned by the software to detect
which buttons are pressed at any one time.

Microcontroller Based Design 42


42
Keypad Scanning Algorithm

In order to find which key is pressed, a scanning algorithm can be used.

1. In this algorithm the pins are divided into two groups (one for rows and the other for columns).
2. One group of connections (either columns or rows) the output group, are driven to known states
which put only one of the wires in an active state and the other in an inactive state.
3. For each state, the other group (i.e. rows or columns) the input group, are checked to see if a
button press is shorting the corresponding row and column lines.

NOTE: It is important that the input group connections remain in an inactive state as long as no
button is pressed connecting that wire to an output connection in active state.

The keypad connections with STMF103 are stated below:

R1 PC0 will be configured as Input


R2 PC1 will be configured as Input
R3 PC2 will be configured as Input
R4 PC3 will be configured as Input
C1 PB5 will be configured as Output
C2 PB6 will be configured as Output
C3 PB7 will be configured as Output

Keypad Pin Configuration

For scanning, the pins connected to the output group have to be in general purpose push-pull output
mode.

The pins connected to the input group have to be configured such that when no button connected
to the input lines is pressed (i.e. The pins are not connected to anything), the pins should be read as
inactive. e.g. For a setup where the columns are the output group (active high) and the rows are the
input group, the row pins should read as low when no button is pressed. This can be achieved by
either configuring the row pins as floating input with external pull down resistors attached or as
input with pull up/pull down and the corresponding bits in the ODR cleared so that the pins as at
input pins with internal pull down resistors.

Code:
#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))
#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_IDR ( * ((volatile unsigned long*) 0x40010808))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

Microcontroller Based Design 43


43
#define GPIOB_CRL ( * ((volatile unsigned long*) 0x40010C00))
#define GPIOB_CRH ( * ((volatile unsigned long*) 0x40010C04))
#define GPIOB_IDR ( * ((volatile unsigned long*) 0x40010C08))
#define GPIOB_ODR ( * ((volatile unsigned long*) 0x40010C0C))
#define GPIOB_BSRR ( * ((volatile unsigned long*) 0x40010C10))

#define GPIOC_CRL ( * ((volatile unsigned long*) 0x40011000))


#define GPIOC_CRH ( * ((volatile unsigned long*) 0x40011004))
#define GPIOC_IDR ( * ((volatile unsigned long*) 0x40011008))
#define GPIOC_ODR ( * ((volatile unsigned long*) 0x4001100C))
#define GPIOC_BSRR ( * ((volatile unsigned long*) 0x40011010))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

void Delay(int x)
{ TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=x-1;
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}
void LCD(unsigned char val, unsigned char cmd)
{ unsigned char val_1;
val_1 = ((val)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;

GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);
val_1 = ((val<<4)&0xF0);
GPIOA_ODR=val_1;
if(cmd==0)
GPIOA_BSRR=0x01000000;
else
GPIOA_BSRR=0x00000100;

Microcontroller Based Design 44


44
GPIOA_BSRR=0x00000200;
Delay(10);
GPIOA_BSRR=0x02000000;
Delay(10);
}
void keypadgetkey()
{ GPIOB_ODR=0;
GPIOB_BSRR =0x00700080; //C1 set C2, C3 Reset
Delay(20);
if ((GPIOC_IDR&0x0001)!=0) //Check R1
{ LCD('1',1); }
else if ((GPIOC_IDR&0x0002)!=0) //Check R2
{ LCD('4',1); }
else if ((GPIOC_IDR&0x0004)!=0) //Check R3
{ LCD('7',1); }
else if ((GPIOC_IDR&0x0008)!=0) //Check R4
{LCD('*',1); }
GPIOB_BSRR =0x00D00020; //C2 set C1, C3 Reset
Delay(20);
if ((GPIOC_IDR&0x0001)!=0) //Check R1
{ LCD('2',1); }
else if ((GPIOC_IDR&0x0002)!=0) //Check R2
{ LCD('5',1); }
else if ((GPIOC_IDR&0x0004)!=0) //Check R3
{ LCD('8',1); }
else if ((GPIOC_IDR&0x0008)!=0) //Check R4
{LCD('0',1); }
GPIOB_BSRR =0x00B00040; //C3 set C1, C2 Reset
Delay(20);
if ((GPIOC_IDR&0x0001)!=0) //Check R1
{ LCD('3',1); }
else if ((GPIOC_IDR&0x0002)!=0) //Check R2
{ LCD('6',1); }
else if ((GPIOC_IDR&0x0004)!=0) //Check R3
{LCD('9',1); }
else if ((GPIOC_IDR&0x0008)!=0) //Check R4
{LCD('#',1); }
}
void LCD_init(void)
{ Delay(50);
LCD(0x33,0);
Delay(500);
LCD(0x32,0);
Delay(500);
LCD(0x28,0);
Delay(500);
LCD(0x02,0); //2 Lines 5*7 matrix
LCD(0x01,0); //Shift cursor to right

Microcontroller Based Design 45


45
LCD(0x06,0); //Clear screen
LCD(0x80,0); //Force cursor to beginning
}

void main()
{ RCC_APB2ENR |= 0x0000001C;
RCC_APB1ENR |= 0x00000001;

GPIOA_CRL &= 0x2222FFFF;


GPIOA_CRL |= 0x22220000;

GPIOA_CRH &= 0xFFFFFF22;


GPIOA_CRH |= 0x00000022;

GPIOB_CRL &= 0x2222FFFF;


GPIOB_CRL |= 0x22220000;

GPIOC_CRL &= 0xFFFF8888;


GPIOC_CRL |= 0x00008888;

LCD_init();
while(1)
{ GPIOB_BSRR =0x000000E0; //Set all columns as 1
while ((GPIOC_IDR&0x000F)==0); //Checking Idle state
keypadgetkey();
GPIOB_BSRR =0x000000E0; //Set all columns as 1
while ((GPIOC_IDR&0x000F)!=0); //Checking Idle state
}
}
Lab Assignments:
4. Write a C program to display string on 20x4 LCD
5. Write a C program to detect key from keypad and display its square on LCD
6. Write a C program to detect key from keypad and turn on key pressed number of LED’s
7. Write a C program to display name of student if last 2 digits of his reg. no. are entered through
keypad (Take data of 5 students)
1st line: L1F18BSEE00xx→I/P Entered through Keypad
2nd line: xxxxxxxxxxxxxx→Student name should be printed on LCD

Microcontroller Based Design 46


46
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Integration of Keypad with STM32F1xx Controller
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 47


47
EXPERIMENT 9
Integration of UART in STM32F1xx Controller IDE
Objective
• To learn how to use UART
• To practice different scenarios using Keypad, LCD and STMF103rb UART

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
The universal synchronous asynchronous receiver transmitter (USART) offers a flexible
means of full-duplex data exchange with external equipment requiring an industry standard
NRZ asynchronous serial data format. The USART offers a very wide range of baud rates
using a fractional baud rate generator. It supports synchronous one-way communication and
half-duplex single wire communication. It also supports the LIN (local interconnection
network), Smartcard Protocol and IrDA (infrared data association) SIR ENDEC
specifications, and modem operations (CTS/RTS). It allows multiprocessor communication.
High speed data communication is possible by using the DMA for multi-buffer configuration.

There are total 6 (UART &USARTS) available in STMF32F103.

The main features of UARTS are

• Separate enable bits for Transmitter and Receiver


• Programmable data word length (8 or 9 bits)
• Full duplex, asynchronous communications
• Single wire half duplex communication

The interface is externally connected to another device by three pins. Any USART bidirectional
communication requires a minimum of two pins: Receive Data In (RX) and Transmit Data Out
(TX)

RX: Receive Data Input is the serial data input. Oversampling techniques are used for data recovery
by discriminating between valid incoming data and noise.

TX: Transmit Data Output. When the transmitter is disabled, the output pin returns to its I/O port
configuration. When the transmitter is enabled and nothing is to be transmitted, the TX pin is at
high level. In single-wire and smartcard modes, this IO is used to transmit and receive the data (at
USART level, data are then received on SW_RX).

Microcontroller Based Design 48


48
The baud rate for receiver and transmitter are both set to same value as programmed in Mantissa
and Fraction values of USARTDIV.

𝑓𝑐𝑘
𝑇𝑥/𝑅𝑥𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 =
(16 ∗ 𝑈𝑆𝐴𝑅𝑇𝐷𝐼𝑉)

Code:
#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
#define USART2_SR ( * ((volatile unsigned long*) 0x40004400))
#define USART2_CR1 ( * ((volatile unsigned long*) 0x4000440C))
#define USART2_DR ( * ((volatile unsigned long*) 0x40004404))
#define USART2_BRR ( * ((volatile unsigned long*) 0x40004408))

#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))


#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_IDR ( * ((volatile unsigned long*) 0x40010808))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

void Delay(int x)
{ TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=x-1;
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}
void main()
{
RCC_APB2ENR |= 0x00000004; //Enable Port A
RCC_APB1ENR |= 0x00020001; //Enable Timer 2 & USART 2

GPIOA_CRL &=0xFFFF89FF;
GPIOA_CRL |=0x00008900;

GPIOA_BSRR = 0x8;

Microcontroller Based Design 49


49
USART2_CR1 = 0x200C; //Enable USART 2 and Tx/Rx
USART2_BRR = 0x45; //Select Mantissa and Fraction of Baudrate
while(1)
{
usart1_sendByte('u');
usart1_sendByte('c');
usart1_sendByte('p');
usart1_sendByte('\n'); //go to new line
usart1_sendByte('\r'); //carrier return
Delay(1000); //wait 1 second
}
}
void usart1_sendByte(unsigned char c)
{
USART2_DR = c;
while((USART2_SR&(1<<6)) == 0); //wait until the TC flag is set
}

Lab Assignments:
1. Write a C program to blink LED on PA5 and display appropriate message on UART
2. Write a program to control LED on PA5 by User Button and display appropriate message on
UART.
3. Write a C program to display string of your name on STM32F103 UART

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 50


50
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Integration of UART in STM32F1xx Controller IDE
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

Microcontroller Based Design 51


51
EXPERIMENT 10
Programming Exercises Using STM32F10xx Instructions
Objective
• To practice on different scenarios using STM32F10xx bare metal code

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Lab Assignments:
1. Generate the following waves each on channel 2 of timer 2, 3 and 4 respectively. Also state
the average voltage received in each case. Frequency 1KHz. Can we generate these on channels
of same timer?

2. Write a C code for bare metal that will perform the following functions on STM32F103rb.
(LCD D4, D5, D6 and D7 are connected at A12,A13,A14 and A15)
a) Initialize LCD and its functions in 4 bit mode.
b) If numeric keys (0-9) are pressed on keypad, the same should be communicated to LCD. If
‘*’ is pressed, It prints your name as string and if # is pressed it prints your roll number.
3. Write a C code to Enable USART and enter 4 digit password from keypad and display message
on screen if correct password is entered or not. Use appropriate messages to display on screen
Submit a separate report about the experiment which you have
concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 52


52
EXPERIMENT 11
Integration of I2C in STM32F1xx Controller IDE
Objective
• To learn how to use Inter-Integrated Circuit (I2C)
• I2C Sending & Receiving algorithm
• To practice different scenarios using Keypad, LCD and STMF103rb using I2C & UART

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
I2C (inter-integrated circuit) bus Interface serves as an interface between the microcontroller
and the serial I2C bus. It provides multi master capability, and controls all I2C bus-specific
sequencing, protocol, arbitration and timing. It supports the standard mode (Sm, up to 100
kHz) and Fm mode (Fm, up to 400 kHz). It may be used for a variety of purposes, including
CRC generation and verification, SMBus (system management bus) and PMBus (power
management bus). Depending on specific device implementation DMA capability can be
available for reduced.

The main features of I2C are

• Parallel-bus / I2C protocol converter


• Multi master capability: the same interface can act as Master or Slave
• I2C Master features:
o Clock generation
o Start and Stop generation
• I2C Slave features:
o Programmable I2C Address detection
o Dual Addressing Capability to acknowledge 2 slave addresses
o Stop bit detection
• Generation and detection of 7-bit/10-bit addressing and General Call
• Supports different communication speeds:
o Standard Speed (up to 100 kHz)
o Fast Speed (up to 400 kHz)
• Analog noise filter
• Status flags:
o Transmitter/Receiver mode flag
o End-of-Byte transmission flag
o I2C busy flag
Microcontroller Based Design 53
53
• Error flags:
• 2 Interrupt vectors:
• Optional clock stretching
• 1-byte buffer with DMA capability
• Configurable PEC (packet error checking) generation or verification:
• SMBus 2.0 Compatibility:
• PMBus Compatibility

The interface can operate in one of the four following modes:

• Slave transmitter
• Slave receiver
• Master transmitter
• Master receiver

By default, it operates in slave mode. The interface automatically switches from slave to
master, after it generates a START condition and from master to slave, if an arbitration loss
or a Stop generation occurs, allowing multi master capability.

I2C Line Characteristics:

I2C devices use only 2 bidirectional open-drain pins for data communication. To implement
I2C, a 4.7k ohm pull-up resistor for each of bus lines is needed (Figure 11.1). This
implements a wired-AND which is needed to implement I2C protocols. It means that if one
or more devices pull the line to low (zero) level, the line state is zero. The level of the line
will be 1 only if none of the devices pull the line to low level.

Figure 18.1: I2C Bus characteristics (Ref. STM32 ARM Programming for Embedded Systems by Mazidi Pg # 314)

The main registers for I2C are

• I2C CR1
• I2C CR2
• I2C DR
• I2C SR1

Microcontroller Based Design 54


54
• I2C SR2
• I2C CCR
• I2C TRISE

I2C Initialization:

void I2C2_init( )
{ RCC_APB2ENR |= 8; // Enable GPIOB clock
RCC_APB1ENR |=0x00400001; // Enable I2C2 clock and Timer 2
GPIOB_CRH &= 0xFFFFFFFF; // PB10, PB11 I2C2 SCL, SDA
GPIOB_CRH |= 0x0000FF00;
// PB10, PB11 use alternate function output open-drain with pull-ups
// Use 4.7Kohms resistors for SCL & SDA and provide 3.3V Vcc
I2C2_CR1 = 0x8000; // software reset I2C2
I2C2_CR1 &= ~0x8000; // out of reset

Figure 11.9: I2C CR1 Register (Ref. STM32F103RB Reference manual Pg # 770)

I2C2_CR2 = 0x0008; // peripheral clock is 8 MHz

Figure 11.10: I2C CR2 register (Ref. STM32F103RB Reference manual Pg # 772)

I2C2_CCR = 40; // standard mode, 100kHz clock

Figure 11.11: I2C CCR register (Ref. STM32F103RB Reference manual Pg # 779)

I2C2_TRISE = 9; // maximum rise time

Figure 11.12: I2C TRISE register (Ref. STM32F103RB Reference manual Pg # 780)

I2C2_CR1 |= 0x0001; // enable I2C2 module


}

I2C Sender Algorithm:


void I2C2_byteWrite(char saddr, char data)
{ volatile int tmp;
while (I2C2_SR2 & 2); // wait until bus not busy

Microcontroller Based Design 55


55
Figure 11.13: I2C SR2 register (Ref. STM32F103RB Reference manual Pg # 778)

I2C2_CR1 |= 0x100; // generate start


while (!(I2C2_SR1 & 1)); // wait until start flag is set

Figure 11.14: I2C SR1 register (Ref. STM32F103RB Reference manual Pg # 775)

I2C2_DR = saddr << 1; // transmit slave address

Figure 11.15: I2C DR register (Ref. STM32F103RB Reference manual Pg # 775)

while (!(I2C2_SR1&2)); // wait until addr flag is set


tmp=I2C2_SR2; // clear addr flag
while (!(I2C2_SR1 & 0x80)); // wait until data register empty
I2C2_DR = data; // send memory address
while (!(I2C2_SR1 & 4)); // wait until transfer finished
I2C2_CR1|=0x200; // generate stop
}

I2C Receiver Algorithm;


int I2C1_Read()
{ while (!(I2C2_SR1 & 2)); // wait until ADDRESS MATCHED
int temp = I2C2_SR2;
while(!(I2C2_SR1&0X10)) // stop bit not detected
{ while(!(I2C2_SR1&0X40));// wait to receive data
usart1_sendByte(I2C2_DR);//send to UART for display
}
}

I2C Sender Code:


#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))
#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_IDR ( * ((volatile unsigned long*) 0x40010808))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

Microcontroller Based Design 56


56
#define GPIOB_CRL ( * ((volatile unsigned long*) 0x40010C00))
#define GPIOB_CRH ( * ((volatile unsigned long*) 0x40010C04))
#define GPIOB_IDR ( * ((volatile unsigned long*) 0x40010C08))
#define GPIOB_ODR ( * ((volatile unsigned long*) 0x40010C0C))
#define GPIOB_BSRR ( * ((volatile unsigned long*) 0x40010C10))

#define GPIOC_CRL ( * ((volatile unsigned long*) 0x40011000))


#define GPIOC_CRH ( * ((volatile unsigned long*) 0x40011004))
#define GPIOC_IDR ( * ((volatile unsigned long*) 0x40011008))
#define GPIOC_ODR ( * ((volatile unsigned long*) 0x4001100C))
#define GPIOC_BSRR ( * ((volatile unsigned long*) 0x40011010))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

#define I2C2_CR1 ( * ((volatile unsigned long*) 0x40005800))


#define I2C2_CR2 ( * ((volatile unsigned long*) 0x40005804))
#define I2C2_DR ( * ((volatile unsigned long*) 0x40005810))
#define I2C2_SR1 ( * ((volatile unsigned long*) 0x40005814))
#define I2C2_SR2 ( * ((volatile unsigned long*) 0x40005818))
#define I2C2_CCR ( * ((volatile unsigned long*) 0x4000581C))
#define I2C2_TRISE ( * ((volatile unsigned long*) 0x40005820))

#define SLAVE_ADDR 0x1B //Declare Slave Device Address


void I2C2_init(void);
void I2C2_byteWrite(char saddr, char data);
void I2C2_string (char saddr,unsigned char *word);
void main()
{ I2C2_init();
I2C2_string(SLAVE_ADDR, "UCP FOE ");
while(1);
}

void I2C2_init(void)
{ RCC_APB2ENR |= 8; // Enable GPIOB clock
RCC_APB1ENR |=0x00400001; // Enable I2C2 clock and Timer 2
GPIOB_CRH &= 0xFFFFFFFF; // PB10, PB11 I2C2 SCL, SDA
GPIOB_CRH |= 0x0000FF00;
// PB10, PB11 use alternate function output open-drain with pull-ups
// Use 4.7Kohms resistors for SCL & SDA and provide 3.3V Vcc
I2C2_CR1 = 0x8000; // software reset I2C2
I2C2_CR1 &= ~0x8000; // out of reset
I2C2_CR2 = 0x0008; // peripheral clock is 8 MHz
I2C2_CCR = 40; // standard mode, 100kHz clock
I2C2_TRISE = 9; // maximum rise time
Microcontroller Based Design 57
57
I2C2_CR1 |= 0x0001; // enable I2C2 module
}
/* A device with I2C slave device address saddr. For simplicity, no error checking or error report
is done.*/
void I2C2_byteWrite(char saddr, char data)
{ volatile int tmp;
while (I2C2_SR2 & 2); // wait until bus not busy
I2C2_CR1 |= 0x100; // generate start
while (!(I2C2_SR1 & 1)); // wait until start flag is set
I2C2_DR = saddr << 1; // transmit slave address
while (!(I2C2_SR1&2)); // wait until addr flag is set
tmp=I2C2_SR2; // clear addr flag
while (!(I2C2_SR1 & 0x80)); // wait until data register empty
I2C2_DR = data; // send memory address
while (!(I2C2_SR1 & 4)); // wait until transfer finished
I2C2_CR1|=0x200; // generate stop
}
I2C Receiver Code:
#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))
#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))
#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_IDR ( * ((volatile unsigned long*) 0x40010808))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

#define GPIOB_CRL ( * ((volatile unsigned long*) 0x40010C00))


#define GPIOB_CRH ( * ((volatile unsigned long*) 0x40010C04))
#define GPIOB_IDR ( * ((volatile unsigned long*) 0x40010C08))
#define GPIOB_ODR ( * ((volatile unsigned long*) 0x40010C0C))
#define GPIOB_BSRR ( * ((volatile unsigned long*) 0x40010C10))
#define GPIOC_CRL ( * ((volatile unsigned long*) 0x40011000))
#define GPIOC_CRH ( * ((volatile unsigned long*) 0x40011004))
#define GPIOC_IDR ( * ((volatile unsigned long*) 0x40011008))
#define GPIOC_ODR ( * ((volatile unsigned long*) 0x4001100C))
#define GPIOC_BSRR ( * ((volatile unsigned long*) 0x40011010))
#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))
#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))
#define I2C2_CR1 ( * ((volatile unsigned long*) 0x40005800))
#define I2C2_CR2 ( * ((volatile unsigned long*) 0x40005804))
#define I2C2_OAR1 ( * ((volatile unsigned long*) 0x40005808))
#define I2C2_DR ( * ((volatile unsigned long*) 0x40005810))
#define I2C2_SR1 ( * ((volatile unsigned long*) 0x40005814))
#define I2C2_SR2 ( * ((volatile unsigned long*) 0x40005818))
Microcontroller Based Design 58
58
#define I2C2_CCR ( * ((volatile unsigned long*) 0x4000581C))
#define I2C2_TRISE ( * ((volatile unsigned long*) 0x40005820))
#define USART2_SR ( * ((volatile unsigned long*) 0x40004400))
#define USART2_CR1 ( * ((volatile unsigned long*) 0x4000440C))
#define USART2_DR ( * ((volatile unsigned long*) 0x40004404))
#define USART2_BRR ( * ((volatile unsigned long*) 0x40004408))
void I2C1_init(void);
int I2C1_Read();
void usart1_sendByte(unsigned char c)
{ USART2_DR = c;
while((USART2_SR&(1<<6)) == 0); //wait until the TC flag is set
}
void main()
{ RCC_APB2ENR |= 4; // Enable GPIOA clock
RCC_APB1ENR |=0x00020000; // Enable I2C2 clock and Timer 2
GPIOA_CRL &=0xFFFF89FF; // PA2 & PA3 as AFIO O/P & I/P
GPIOA_CRL |=0x00008900;
GPIOA_BSRR = 0x8; // Enable PA3 as Pull up
USART2_CR1 = 0x200C; // Enable USART 2 and Tx/Rx
USART2_BRR = 0x45; // Select Mantissa and Fraction of Baudrate
I2C1_init();
while (1)
{ I2C1_init();
I2C1_Read();
}
}
void I2C1_init(void)
{ RCC_APB2ENR |= 8; // Enable GPIOB clock
RCC_APB1ENR |=0x00400001; // Enable I2C2 clock
GPIOB_CRH &= 0xFFFFFFFF; // PB10, PB11 I2C2 SCL, SDA
GPIOB_CRH |= 0x0000FF00;
I2C2_CR1 = 0x8000; // software reset I2C2
I2C2_CR1 &= ~0x8000; // out of reset
I2C2_CR2 = 0x0008; // peripheral clock is 8 MHz
I2C2_CCR = 40; // standard mode, 100kHz clock
I2C2_TRISE = 9; // maximum rise time
I2C2_OAR1=0X36; // setting slave address
I2C2_CR1 |= 0x0401; // enable I2C2 and ACK
}
int I2C1_Read()
{ while (!(I2C2_SR1 & 2)); // wait until ADDRESS MATCHED
int temp = I2C2_SR2;
while(!(I2C2_SR1&0X10)) // stop bit not detected
{ while(!(I2C2_SR1&0X40)); // wait to receive data
usart1_sendByte(I2C2_DR); //send to UART for display }
}

Microcontroller Based Design 59


59
Lab Assignments:
1. Write a C program to print string through I2c and display on console through USART

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

Microcontroller Based Design 60


60
EXPERIMENT 12
Integration of ADC in STM32F1xx Controller using USART
Objective
• To learn how to use ADC to check Analog Input
• To practice different scenarios using potentiometer as ADC input and STMF103rb UART

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
The 12-bit ADC is a successive approximation analog-to-digital converter. It has up to 18
multiplexed channels allowing it measure signals from sixteen external and two internal sources.
A/D conversion of the various channels can be performed in single, continuous, scan or
discontinuous mode. The result of the ADC is stored in a left-aligned or right-aligned 16-bit data
register. The analog watchdog feature allows the application to detect if the input voltage goes
outside the user-defined high or low thresholds.

ADC Features
• 12-bit resolution
• Interrupt generation at End of Conversion, End of Injected conversion and Analog
• Single and continuous conversion modes
• Scan mode for automatic conversion of channel 0 to channel ‘n’
• Self-calibration
• Data alignment with in-built data coherency
• Channel by channel programmable sampling time
• External trigger option for both regular and injected conversion
• Discontinuous mode
• Continuous mode

We are going to detect input of Potentiometer on PA0 and display its value on console
through USART

Code:
#define RCC_APB2ENR ( * ((volatile unsigned long*) 0x40021018))
#define RCC_APB1ENR ( * ((volatile unsigned long*) 0x4002101C))

#define USART2_SR ( * ((volatile unsigned long*) 0x40004400))

61
Microcontroller Based Design
#define USART2_CR1 ( * ((volatile unsigned long*) 0x4000440C))
#define USART2_DR ( * ((volatile unsigned long*) 0x40004404))
#define USART2_BRR ( * ((volatile unsigned long*) 0x40004408))

#define GPIOA_CRL ( * ((volatile unsigned long*) 0x40010800))


#define GPIOA_CRH ( * ((volatile unsigned long*) 0x40010804))
#define GPIOA_IDR ( * ((volatile unsigned long*) 0x40010808))
#define GPIOA_ODR ( * ((volatile unsigned long*) 0x4001080C))
#define GPIOA_BSRR ( * ((volatile unsigned long*) 0x40010810))

#define TIM2_CR1 ( * ((volatile unsigned long*) 0x40000000))


#define TIM2_CNT ( * ((volatile unsigned long*) 0x40000024))
#define TIM2_PSC ( * ((volatile unsigned long*) 0x40000028))
#define TIM2_ARR ( * ((volatile unsigned long*) 0x4000002C))
#define TIM2_SR ( * ((volatile unsigned long*) 0x40000010))

#define ADC1_SR ( * ((volatile unsigned long*) 0x40012400))


#define ADC1_CR2 ( * ((volatile unsigned long*) 0x40012408))
#define ADC1_SMPR2 ( * ((volatile unsigned long*) 0x40012410))
#define ADC1_SQR3 ( * ((volatile unsigned long*) 0x40012434))
#define ADC1_DR ( * ((volatile unsigned long*) 0x4001244C))

void Delay(int x)
{ TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=x-1;
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}

void main()
{ int x=0;
float f;
char z[4];
RCC_APB2ENR |= 0x00000204; //Enable Port A and ADC 1
RCC_APB1ENR |= 0x00020001; //Enable Timer 2 and USART 2
uart_init();
GPIOA_CRL &=0xFFFFFF00; //Port A pin 0&1 as Analog I/P
GPIOA_CRL |=0x00000000;
ADC1_CR2 = 0; //Disable ADC
//ADC1_CR2 = 2; //Continuous mode

62
Microcontroller Based Design
Figure 12.16: ADC_CR2 Register (Ref. Manual 11.12.3 Pg # 240)

ADC1_SMPR2 = 8; //ADC sample time 7.5 cycles

Figure 12.17: ADC_SMPR2 Register (Ref. manual 11.12.5 Pg # 245)

ADC1_SQR3 = 0; //1st conversion on PA0

Figure 12.18: ADC_SQR3 Register (Ref. manual 11.12.11 Pg # 249)

ADC1_CR2 |= 1; //Enable ADC1 to power up


//ADC1_CR2 |= 1; //Enable ADC1 for continuous mode
while(1)
{ ADC1_CR2 = 1; //Enable ADC1 to start conversion
while ((ADC1_SR & 0x2)==0); //wait till TC flag is set
x=(ADC1_DR & 0xFFF);
itoa(x,z,10); //C++ function to convert int to Array
usart1_string (z);
usart1_sendByte('\n'); //go to new line
usart1_sendByte('\r'); //carrier return
Delay(500); //wait 500 ms
}
}
void uart_init()
{ GPIOA_CRL &=0xFFFF89FF; //Port A pin 2&3 as AFIO (USART 2)
GPIOA_CRL |=0x00008900;
GPIOA_BSRR = 0x8;
USART2_CR1 = 0x200C; //Enable USART and Tx/Rx
USART2_BRR = 0x45; //Set Baud Rate 115200
}

63
Microcontroller Based Design
void usart1_sendByte(unsigned char c)
{ USART2_DR = c;
while((USART2_SR & 0x40)==0); //wait until the TC flag is set
}
void usart1_string (unsigned char *word)
{ while (*word)
{ USART2_DR = *word++;
while((USART2_SR & 0x40)==0);
}
}

Lab Assignments
1. Write a program in C to detect input of 2 potentiometers and display their values

2. Modify the question 1 code to check value of potentiometer is replaced by temperature sensor

3. Write a program in C to read temperature of built in temperature sensor of STM32F103 board


and display its values through USART

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

64
Microcontroller Based Design
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Integration of ADC in STM32F1xx Controller using USART
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

65
Microcontroller Based Design
EXPERIMENT 13
Integration of Motors with STM32F1xx Controller
Objective
• To learn how to integrate DC motor and control its speed
• To learn how to integrate Servo motor
• To learn how to integrate Stepper motor
• To practice different scenarios with motors and STMF103rb

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
A DC motor can be controlled using a microcontroller such as the STM32F103RB. The
STM32F103RB has built-in support for PWM (pulse width modulation), which can be used to
control the speed of the DC motor. The microcontroller can also be programmed to control the
direction of rotation of the motor. The STM32F103RB can be connected to the DC motor through
a motor driver, which is a device that can provide the necessary current and voltage to the motor.

A servo motor can also be controlled using the STM32F103RB microcontroller. The
STM32F103RB can be used to generate PWM (pulse width modulation) signals, which can be used
to control the position of the servo motor. The microcontroller can be programmed to send a specific
PWM signal to the servo motor, which will cause the servo to rotate to a specific angle.

To control the Servo Motor with STM32F103RB, you need to use the TIM module to generate
PWM signals. The TIM module can be configured to generate PWM signals of a specific frequency
and duty cycle, which can be used to control the position of the servo motor. The PWM signal can
be sent to the servo motor through a digital output pin of the microcontroller.

In addition, you can use libraries like the Servo Library for STM32F103RB which can ease the
PWM generation and controlling the Servo Motor.

A stepper motor can be controlled using the STM32F103RB microcontroller by using the built-in
timer and PWM module. The microcontroller can be programmed to generate a series of pulses,
also known as step pulses, to the stepper motor, which will cause the motor to rotate a specific
number of steps.

To control the stepper motor with the STM32F103RB, you will need to use the TIM module to
generate the step pulses. The TIM module can be configured to generate pulses of a specific
frequency, which will determine the speed of rotation of the stepper motor. The step pulses can be
sent to the stepper motor through digital output pins of the microcontroller.

66
Microcontroller Based Design
It is also possible to use libraries or pre-written code that can handle the low-level details of
generating step pulses and controlling the stepper motor, which can simplify the programming
process.

It's important to note that the STM32F103RB doesn't have built-in support for stepper motor
control, you'll need to use an external stepper driver circuit to control the stepper motor.

Servo Motor
Code:
void Delay(int x)
{ TIM3_CR1=0;
TIM3_CNT=0;
TIM3_PSC=7999;
TIM3_ARR=x-1;
TIM3_CR1=1;
while ((TIM3_SR & 0x0001) ==0);
TIM3_CR1=0;
TIM3_CNT=0;
TIM3_SR=0;
}

int main(void)
{ RCC_APB2ENR |=0x00000004; //selection of port A
RCC_APB1ENR |=0x00000003; //selection of Timer 2

GPIOA_CRL &=0xFFFFFFFA; //Selection of Port A Pin as AFIO


GPIOA_CRL |=0x0000000A; //Selection of Port A Pin 0 as AFIO

TIM2_CR1=0; //Stop Timer 2 process


TIM2_CNT=0; //Reset Timer Counter
TIM2_PSC=159; //Prescalar value
TIM2_ARR=999; //ARR Value
TIM2_CCR1=20; //Duty Cycle
TIM2_CCMR1=0x60; //Selecting PWM mode 1

TIM2_CCER=0x01; //Selecting Polarity 0 and Enable mode 1


TIM2_CR1=1; //Start Timer 2 process
while(1)
{ for(int i=20;i<100;i++)
{ TIM2_CCR1=i;
Delay(100);
}
for(int i=100;i>20;i--)
{ TIM2_CCR1=i;
Delay(100);
}
}
67
Microcontroller Based Design
}
Stepper Motor
Code:
void Delay(int x)
{ TIM2_CR1=0;
TIM2_CNT=0;
TIM2_PSC=7999;
TIM2_ARR=x-1;
TIM2_CR1=1;
while ((TIM2_SR & 0x0001) ==0);
TIM2_CR1=0;
TIM2_CNT=0;
TIM2_SR=0;
}
long step_delay, number_of_steps;
void stepMotor(int thisStep)
{ switch (thisStep)
{ case 0: // 1010
GPIOA_BSRR=0x005000A0;
break;
case 1: // 0110
GPIOA_BSRR=0x00900060;
break;
case 2: //0101
GPIOA_BSRR=0x00A00050;
break;
case 3: //1001
GPIOA_BSRR=0x00600090;
break;
}
}

void Stepper_step(int steps_to_move, int direction)


{int steps_left = steps_to_move; // how many steps to take
int step_number=0;
// determine direction based on whether steps_to_mode is + or -:
// if (steps_to_move > 0) { direction = 1; }
// if (steps_to_move < 0) { direction = 0; }

// decrement the number of steps, moving one step each time:


while (steps_left > 0)
{ if (direction == 1)
{step_number++;
if (step_number == steps_to_move)
{step_number = 0;}
}

68
Microcontroller Based Design
else
{if (step_number == 0)
{step_number = steps_to_move;}
step_number--;
}
steps_left--;
stepMotor(step_number % 4);
Delay(2);
}
}
void main()
{ RCC_APB2ENR |= 0x0000001C;
RCC_APB1ENR |= 0x00000001;
GPIOA_CRL &= 0x2222FFFF;
GPIOA_CRL |= 0x22220000;
while(1)
{ Stepper_step(200,1);
Delay(500);
Stepper_step(200,0);
Delay(500);
}
}

Lab Assignments
1. Write a program in C to control DC motor with PWM of 75%
2. Write a program in C to control Servo motor as Input is given by Keypad
3. Write a program in C to control Stepper motor as Input is given by Potentiometer

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________
69
Microcontroller Based Design
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Integration of Motors with STM32F1xx Controller
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

70
Microcontroller Based Design
EXPERIMENT 14
Implementation of External and Timer Interrupts with STM32F1xx
Controller
Objective
• To learn how to use External Interrupt
• To learn how to use Timer Interrupt
• To practice different scenarios with interrupts and STMF103rb

Equipment
• PC with the installed IDE, compiler and link utility software:
• STM32Cube IDE

Introduction
External Interrupt:
All the I/O pins of STM32F1xx may generate an external interrupt. To use external interrupt lines,
the port pin must be configured in input mode.

There is not a separate interrupt assigned to each I/O pin of each port. If pin 0 of any port (Px0) is
used for an external interrupt it is directed to the EXTI0. There are up to 16 pins for each port,
therefore there are 16 external interrupt lines (EXTIx). Although multiple pins are mapped into a
single EXTIx signal but only one can be responded to at a time.

Timer Interrupt:
To use a timer interrupt in this microcontroller, you can follow these steps:

i. Enable the clock for the timer you want to use. The STM32F103RB has several timers, each
with its own clock that needs to be enabled before the timer can be used. For example, to use
Timer 2, you need to enable the clock for TIM2 by setting the appropriate bit in the
RCC_APB1ENR register.
ii. Configure the timer. Once the clock for the timer is enabled, you need to configure it to suit
your needs. This includes setting the prescaler, the counter mode, and the period.
iii. Configure the interrupt. To enable the timer interrupt, you need to set the appropriate bit in
the TIMx_DIER register. You also need to set the priority of the interrupt in the NVIC.
iv. Write an interrupt handler. When the timer interrupt occurs, the microcontroller will jump to
the interrupt handler.

71
Microcontroller Based Design
External Interrupt:
Code:
void main()
{ RCC_APB2ENR |= 0x00000015; //Enable Port A and C
RCC_APB1ENR |= 0x00020001; //Enable Timer 2 & USART 2

GPIOA_CRL &=0xFFFF89FF;
GPIOA_CRL |=0x00008900;
GPIOC_CRH &=0xFF8FFFFF;
GPIOC_CRH |=0x00800000;

GPIOA_BSRR = 0x8;

USART2_CR1 = 0x200C; //Enable USART 2 and Tx/Rx


USART2_BRR = 0x45; //Select Mantissa and Fraction of Baudrate

NVIC_ISER1 = 0X100; //Enable External Interrupt on bit 40


AFIO_EXTICR4 = 0x20; //Enable PortC Pin13 as External Interrupt
EXTI_IMR = 0X2000; //Set value on 13 bit
EXTI_RTSR = 0X2000; //Enable 13 bit for rising edge
EXTI_FTSR = 0; //Disable for falling edge
while(1)
{}
}
void usart1_sendByte(unsigned char c)
{ USART2_DR = c;
while((USART2_SR&(1<<6)) == 0); //wait until the TC flag is set
}
void EXTI15_10_IRQHandler()
{
usart1_sendByte('u');
EXTI_PR = 0x2000;
}

Timer Interrupt:
Code:
int count =0;
void main()
{ RCC_APB2ENR |= 0x00000004; //enable clock to GPIO port A
RCC_APB1ENR |= 0x00000001; //enable TIM2
GPIOA_CRL &=0xFF2FFFFF;
GPIOA_CRL |=0x00200000;
Tim_2_Init(500);
while(1)
{}
}

72
Microcontroller Based Design
void Tim_2_Init(int x)
{ TIM2_CR1 = 0;
TIM2_CNT = 0;
if(x > 1)
{ TIM2_PSC = 7999; //prescaler for 1ms
TIM2_ARR = x - 1; //interrupt after PERIOD ms
}
else
{ TIM2_PSC = 799; //prescaler for 1e-4 s
TIM2_ARR = 9; //interrupt after PERIOD ms
}
TIM2_DIER = 0x0001; //enable interrupt in timer peripheral
TIM2_CR1 = 0x0001; //start timer 2
NVIC_ISER0 = 1<<28; //enable the correct channel in the NVIC
}
void TIM2_IRQHandler(void)
{ if(count%2)
GPIOA_BSRR = 0x00000020;
else
GPIOA_BSRR = 0x00200000;
count++;
TIM2_SR = 0; // Clear the interrupt flag
}

Lab Assignments
1. Write a program in C to control DC motor with Timer 2 Interrupt.
2. Write a program in C to control Stepper motor using push buttons

Submit a separate report about the experiment which you have


concluded from it. Also your report should contain the codes and
verified results of the above experiments.

Student Name: __________________________


Student Registration No. __________________________
Teachers Initials: __________________________
Date Performed: __________________________

73
Microcontroller Based Design
MicroController Based Design Laboratory
Lab Report Rubrics
Experiment Name: Implementation of External and Timer Interrupts with STM32F1xx
Name: Section: Roll Number:
CLO: 1. Students will be able to follow the instructions given and display the operation of µC based embedded systems in Labs through
practical hardware and computer aided simulations.
2. Students, working alone or in a team/group environment, will be able to compile and integrate the code with hardware.
PLO Level Sr Trait Excellent Good Average Poor Grade
N
o.

P3 1 Objective Student Student was able Student was not Student was unable Excellent
5 Guided Clarity was able to to precisely follow able to precisely to follow the 5
Modern Response precisely the objectives of follow the objectives of the Good
Tool follow the the experiment , objectives of the experiment and 4
Usage objectives however was not experiment , explain them Average
of the able to explain however was not 3
experiment them accurately able to explain Poor
and explain them accurately 2
them
accurately

2 Code The code is The code is fairly The code is The code is poorly Excellent
9 A2 quality exceptional easy to read. readable only by organized and very 5
Individu Respondi ly well someone who difficult to read. Good
al and ng to organized knows what it is 4
Team Phenome and very supposed to be Average
Work na easy to doing. 3
follow. Poor
2
3 Hardware Hardware Hardware is Hardware is Hardware is not Excellent
connectivi is working working properly. partially working. 5
ty properly. Wires are not working. Circuit Connections are Good
Connection connected neatly is connected incomplete. 4
are firm but there is no lose loosely and Average
and neat. connection. messy. 3
Poor
2
4 Report The report The report The report The report structure Excellent
Format structure structure was in structure was in was not in 5
was in accordance to the accordance to accordance to the Good
accordance provided format. the provided provided format. 4
to the Everything was format. Everything was not Average
provided listed properly, Everything was listed properly, 3
format. results were not listed results were not Poor
Everything shown properly properly, results shown properly and 2
was listed and the report was were not shown the report was not
properly, not tidy properly and the tidy
results were report was not
shown tidy
properly
and the
report was
tidy

Assessed by: Name: Jawad Khalid Qureshi____________________ Signature:_____________________ Total


Date:__________________

74
Microcontroller Based Design
DESIGN PROJECT LAB
Question: [CLO2 → A2] (10)

Write a C code for bare metal CortexM3 that will implement the calculator using STM32F103RB
board, 4x4 keypad and 20x4 LCD. The calculator should be able to perform addition, subtraction,
multiplication and division, and basic trigonometric functions as entered by the user.

(Hint: Map A as +, B as -, C as / and D as = on keypad.) Furthermore, if user press # after one


value, he should be able to perform trigonometric calculations.)

The display on the LCD should be as follows

Line 1: STM32F103rb Calc.


Line 2:’value1 by user’ ‘operation to perform’ ‘value2 by user’ =
Line 3: Answer is: ‘answer’

75
Microcontroller Based Design
Appendeix A: Lab CLOs
Course Learning Outcomes (CLOs), their Mapping and Assessment

CLO Taxonomy
CLO STATEMENT PLO LEVEL
NO
Students will be able to follow the instructions given and
1 display the operation of µC based embedded systems in Labs 5 P3
through practical hardware and computer aided simulations.
2 Students, working alone or in a team/group environment, A2
9
will be able to compile and integrate the code with hardware.

Appendix B: Lab Evaluaion Rubrics


ETN-3241 Microcontroller based Design Lab

Lab Report Rubrics

Experiment Name:

Name: Section: Roll No.

CLO Students will be able to follow the instructions given and display the operation of µC based embedded systems in
1 Labs through practical hardware and computer aided simulations.

CLO Students, working alone or in a team/group environment, will be able to compile and integrate the code with
2 hardware.

CLO PLO Level Trait Excellent Good Average Poor Grade

Student was Student Student Student was Excellent 5


able to was able to was not unable to Good 4
precisely precisely able to follow the Average 3
follow the follow the precisely objectives Poor 2
objectives of objectives follow the of the
5 the of the objectives experiment
(Modern P3 (Guided Objective experiment experiment, of the and explain
1 and explain however experiment them
Tool Response) Clarity
them was not , however
Usage)
accurately able to was not
explain able to
them explain
accurately them
accurately

9 The code is The code is The code is The code is Excellent 5


2 A2 Code Quality exceptionally fairly easy readable poorly Good 4
(Individ
(Responding well to read. only by organized
ual and
76
Microcontroller Based Design
Team to organized someone and very Average 3
and very who knows difficult to Poor 2
Work) Phenomena)
easy to what it is read.
follow. supposed
to be
doing.

Hardware is Hardware Hardware Hardware is Excellent 5


working is working is partially not Good 4
properly. properly. working. working. Average 3
Connection Wires are Circuit is Connections Poor 2
Hardware are firm and not connected are
connectivity neat. connected loosely and incomplete.
neatly but messy.
there is no
lose
connection.

The report The report The report The report Excellent 5


structure is structure is structure is structure is Good 4
as per as per as per not as per Average 3
format. format. format. format. Poor 2
Controller Controller Controller Controller
code is as code is as code is code is
Report
per lab per lab missing missing
Format assigned assigned major
question. question. functions
Conclusion Conclusion
was drawn was not
properly drawn
properly

Assessed by: Name: _______________________ Date: ____________ Signature______________ Total:

77
Microcontroller Based Design
78
Microcontroller Based Design
Appendix C: Sample Lab Report
For software labs, the format of the report will be as given below:

1. Introduction: Introduce the new constructs/ commands being used, and their significance.
2. Objective: What are the learning goals of the experiment?
3. Design: If applicable, draw the flow chart for the program. How do the new constructs facilitate
achievement of the objectives; if possible, a comparison in terms of computational tractability with
the alternate constructs?
4. Issues: The bugs/issues encountered and the way they were removed.
5. Conclusions: What conclusions can be drawn from experiment?
6. Application: Suggest a real world application where this exercise may apply.
7. Answers to post lab questions (if any).

Sample Lab Report for Networks Labs

Introduction

The ability to control the flow of the program, letting it make decisions on what code to execute, is important
to the programmer. The commands allow the Engineer to control and select respective use of the command.

Switch >
Switch >enable
Switch #
Switch #disable

Objective:

Introduction of Switch and its basic configuration. To draw network as per provided topology diagram.
Create basic switch configuration and assigning IP to it and verify through Ping command

Design:

Switch >
Switch >enable
Switch #
Switch # configure terminal
Switch (config)# hostname UCP
UCP (config)# line console 0
UCP (config-line)# password cisco
UCP (config-line)# login
UCP (config-line)# exit
UCP (config)# line vty 0 15
UCP (config-line)# password cisco
UCP (config-line)# login
UCP (config-line)# exit
UCP (config)# enable secret class
UCP (config)# interface vlan 1
UCP (config-if)# ip address 192.168.0.1 255.255.255.0
UCP (config-if)# no shutdown
UCP (config-if)# exit
79
Microcontroller Based Design
UCP (config)# exit
UCP # copy running -config startup-config
UCP # disable
UCP >

Issues:

Encountered bugs and issues; how were they identified and resolved.

Conclusions:

The output indicates correct execution of the given task

80
Microcontroller Based Design
Appendix D: Lab Evaluation Criteria
• Lab Experiment Performance and Lab Reports 60%
• Mid Term Evaluation (Lab Performance and Viva) 20%
• Final Term Evaluation (Lab Performance and Viva) 20%

Appendix E: Lab Safety Rules


In all the Electrical Engineering (EE) labs, with an aim to prevent any unforeseen accidents during conduct
of lab experiments, following preventive measures and safe practices shall be adopted:

➢ Remember that the voltage of the electricity and the available electrical current in EE labs has enough
power to cause death/injury by electrocution. It is around 50V/10 mA that the “cannot let go” level is
reached. “The key to survival is to decrease our exposure to energized circuits.”
➢ If a person touches an energized bare wire or faulty equipment while grounded, electricity will instantly
pass through the body to the ground, causing a harmful, potentially fatal, shock.
➢ Each circuit must be protected by a fuse or circuit breaker that will blow or “trip” when its safe carrying
capacity is surpassed. If a fuse blows or circuit breaker trips repeatedly while in normal use (not
overloaded), check for shorts and other faults in the line or devices. Do not resume use until the trouble
is fixed.
➢ It is hazardous to overload electrical circuits by using extension cords and multi-plug outlets. Use
extension cords only when necessary and make sure they are heavy enough for the job. Avoid creating
an “octopus” by inserting several plugs into a multi-plug outlet connected to a single wall outlet.
Extension cords should ONLY be used on a temporary basis in situations where fixed wiring is not
feasible.
➢ Dimmed lights, reduced output from heaters and poor monitor pictures are all symptoms of an
overloaded circuit. Keep the total load at any one time safely below maximum capacity.
➢ If wires are exposed, they may cause a shock to a person who comes into contact with them. Cords
should not be hung on nails, run over or wrapped around objects, knotted or twisted. This may break the
wire or insulation. Short circuits are usually caused by bare wires touching due to breakdown of
insulation. Electrical tape or any other kind of tape is not adequate for insulation!
➢ Electrical cords should be examined visually before use for external defects such as: Fraying (worn out)
and exposed wiring, loose parts, deformed or missing parts, damage to outer jacket or insulation,
evidence of internal damage such as pinched or crushed outer jacket. If any defects are found the electric
cords should be removed from service immediately.
➢ Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
➢ Plug your heavy current consuming or any other large appliances into an outlet that is not shared with
other appliances. Do not tamper with fuses as this is a potential fire hazard. Do not overload circuits as
this may cause the wires to heat and ignite insulation or other combustibles.
➢ Keep lab equipment properly cleaned and maintained.
➢ Ensure lamps are free from contact with flammable material. Always use lights bulbs with the
recommended wattage for your lamp and equipment.
➢ Be aware of the odor of burning plastic or wire.
➢ ALWAYS follow the manufacturer recommendations when using or installing new lab equipment.
Wiring installations should always be made by a licensed electrician or other qualified person. All
electrical lab equipment should have the label of a testing laboratory.
➢ Be aware of missing ground prong and outlet cover, pinched wires, damaged casings on electrical
outlets.
81
Microcontroller Based Design
➢ Inform Lab engineer / Lab assistant of any failure of safety preventive measures and safe practices as
soon you notice it. Be alert and proceed with caution at all times in the laboratory.
➢ Conduct yourself in a responsible manner at all times in the EE Labs.
➢ Follow all written and verbal instructions carefully. If you do not understand a direction or part of a
procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT BEFORE PROCEEDING WITH THE
ACTIVITY.
➢ Never work alone in the laboratory. No student may work in EE Labs without the presence of the Lab
engineer / Lab assistant.
➢ Perform only those experiments authorized by your teacher. Carefully follow all instructions, both
written and oral. Unauthorized experiments are not allowed.
➢ Be prepared for your work in the EE Labs. Read all procedures thoroughly before entering the
laboratory. Never fool around in the laboratory. Horseplay, practical jokes, and pranks are dangerous
and prohibited.
➢ Always work in a well-ventilated area.
➢ Observe good housekeeping practices. Work areas should be kept clean and tidy at all times.
➢ Experiments must be personally monitored at all times. Do not wander around the room, distract other
students, startle other students or interfere with the laboratory experiments of others.
➢ Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or baggy clothing
are a hazard in the laboratory. Long hair must be tied back, and dangling jewelry and baggy clothing
must be secured. Shoes must completely cover the foot.
Know the locations and operating procedures of all safety equipment including fire extinguisher.
Know what to do if there is a fire during a lab period; “Turn off equipment, if possible and exit EE lab
immediately.”

82
Microcontroller Based Design

You might also like