Microcontroller Based Design Lab Manual - Updated Mar 2023
Microcontroller Based Design Lab Manual - Updated Mar 2023
MANUAL
EXPERIMENTS IN
FACULTY OF ENGINEERING
M
LIST OF AUTHORS
EXPERIMENTS IN
This manual or parts, thereof, may not be reproduced in any from without Permission of the
EED.
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.
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.
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.
Authors
CONTENTS
Equipment
PC with the installed IDE, compiler and link utility software:
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
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
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).
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.
Equipment
PC with the installed IDE, compiler and link utility software:
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.
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
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.
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
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:
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.
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 !.
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.
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.
Bitwise logical AND and OR operations can be used to set and clear targeted bits.
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.
Step 1 mask:
111100112
Step 2 data:
000001002
A & mask:
110000102
A | data:
110001102
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.
10011101
AND 00001000
= 00001000
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
To initialize clock and configure for PA5, following functions and commands will be used
To blink led, we need to configure pin 5 of port A. For that, following syntax will be used.
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
Now the third part is to enable timer and set its value.
Now, all the necessary functions have been discussed. To blink led on PA5, following logic can be
implemented.
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;
}
}
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:
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
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.
• 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.
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.
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
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):
• 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.
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.
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:
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.
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.
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).
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.
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.
Now we need to configure it as system clock, for that we need clock configuration register.
Figure 5.4: Clock Configuration Register (Ref. manual 7.3.2) Pg. 101
while ((RCC_CFGR & 0x0000000C) != 0x4); // Wait till HSE is your 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.
Here, we are configuring a 36 MHz clock using PLL and PLL input is HSI div by 2
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
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.
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
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.
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
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
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.
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
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.
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.
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.
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))
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;
void main()
{ RCC_APB2ENR |= 0x0000001C;
RCC_APB1ENR |= 0x00000001;
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
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
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.
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).
𝑓𝑐𝑘
𝑇𝑥/𝑅𝑥𝐵𝑎𝑢𝑑 𝑅𝑎𝑡𝑒 =
(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))
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;
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
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
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.
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.
• 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 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)
• I2C CR1
• I2C CR2
• I2C DR
• I2C SR1
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)
Figure 11.10: I2C CR2 register (Ref. STM32F103RB Reference manual Pg # 772)
Figure 11.11: I2C CCR register (Ref. STM32F103RB Reference manual Pg # 779)
Figure 11.12: I2C TRISE register (Ref. STM32F103RB Reference manual Pg # 780)
Figure 11.14: I2C SR1 register (Ref. STM32F103RB Reference manual Pg # 775)
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))
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))
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))
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)
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
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
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
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
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
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;
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
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
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.
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.
Experiment Name:
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.
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).
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:
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%
➢ 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