0% found this document useful (0 votes)
121 views176 pages

2024 STM32 - Multi Learning Shield

Uploaded by

pankberani
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)
121 views176 pages

2024 STM32 - Multi Learning Shield

Uploaded by

pankberani
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/ 176

Introduction to STM32




by:
Ts. Abd Rahim Kasiman
Department of Skills and Professional
Faculty of Technical and Vocational Education,
Universiti Tun Hussein Onn Malaysia (UTHM)
Tentative Program
-
08.00 09.00 Introduction to STM32 environment
-
09.00 09.30 Refreshment
-
09.30 10.30 Software setup for STM32CubeIDE & Tera Term
1st Day

-
10.30 13.00 Digital Output Control and Task Scheduling
-
13.00 14.00 Lunch + Photoshoot
-
14.00 15.30 SysTick timer concept
-
15.30 17.00 Basic Control Structure and Function Flow

-
08.00 09.00 Digital Input + External Interrupt (EXTI)
-
09.00 09.30 Refreshment
-
09.30 11.00 External Interrupt (EXTI)
2nd Day

-
11.00 13.00 Setting IOC for Arduino Multi Learning Shield on STM32L053
Tentative Program
-
08.00 09.00 Basic control on 7 segment using serial concept
-
09.00 09.30 Refreshment
-
09.30 10.30 7-segment using 74HC595 shift register concept
3rd Day

-
10.30 13.00 Programming 7-segment to display 4-digit display + Timer concept
-
13.00 14.00 Lunch
-
14.00 15.30 Analog concept on STM32L053
-
15.30 17.00 Programming for single and multiple-channel analog input

-
08.00 09.00 Review on WSMB 2023 Pre-Qualification questions for ESP module
-
09.00 09.30 Refreshment
-
09.30 12.00 Answer review on WSMB 2023 Pre-Qualification
4th Day

-
12.00 13.00 Review on KVSkill 2023 Final questions for ESP module
Pre-Training Survey Question

Please click this text to answer


Pre-Training Survey Questions or
Scan the QR code
Instructor
• Ts. Abd Rahim Bin Kasiman
• M.Eng Electrical (Mechatronics), UTHM (2015)
• B.Eng (Hons) Mechatronics, IIUM (2007)
• Work Experience:
• Assembly Engineer TSOP (ST Microelectronics)
• Vocational Training Officer (ADTEC BP)
• Instructor Engineer (UTHM)
• Passion:
• Electronics applications, Robotics
• Contact:
[email protected] (+60177002044)
Undergraduate Programme (TVET)
Fakulti Pendidikan Teknikal dan Vokasional (FPTV)

ISMT

ISMPV
Tuition Fees for Bachelor's Degree Program
Post Graduate Programme
Overview of Nucleo-L053R8
• The STM32 Nucleo board is a low-cost and easy-to-
use development platform used to quickly evaluate
and st ar t developm ent wit h an STM32
microcontroller in the LQFP64 package

• The STM32 Nucleo boards do not require any


separate probe as they integrate the ST-LINK/V2-1
debugger and programmer

User Manual
Nucleo board
Nucleo-L053R8 Features
• Common features
• STM32 microcontroller in LQFP64 or LQFP48 package
• 1 user LED shared with ARDUINO®
• 1 user and 1 reset push-buttons
• 32.768 kHz crystal oscillator
• Board connectors:
• ARDUINO® Uno V3 expansion connector
• ST morpho extension pin headers for full access to all STM32 I/Os
• Flexible power-supply options: ST-LINK USB VBUS or external sources
• On-board ST-LINK debugger/programmer with USB re-enumeration capability: mass storage, Virtual COM port, and debug
port
• Comprehensive free software libraries and examples available with the STM32Cube MCU Package
• Support of a wide choice of Integrated Development Environments (IDEs) including IAR Embedded Workbench®, MDK-ARM,
and STM32CubeIDE
• Board-specific features
• External SMPS to generate Vcore logic supply
• 24 MHz or 48 MHz HSE
• Board connectors:
• External SMPS experimentation dedicated connector
• Micro-B or Mini-B USB connector for the ST-LINK
• MIPI® debug connector
Hardware layout and config
Hardware layout and config
Hardware layout and config
Arduino connectors on Nucleo-L053R8
ST morpho connectors on Nucleo-L053R8

1. The default state of BOOT0 is LOW. It can be set to HIGH when a


jumper is on pin5-7 of CN7. Two unused jumpers are available on CN11
and CN12 (bottom side of the board). GND 8 7 AVDD U5V(2)

2. U5V is 5 V power from ST-LINK/V2-1 USB connector and it rises before


+5V. 8 9 - - 10 9 GND - 10 11 - IOREF 12 11 PA5 PA12 12 13 PA13(3)

3. PA13 and PA14 share with SWD signals connected to ST-LINK/V2-1, it


is not recommended to use them as IO pins if the ST-LINK part is not
cut.
Nucleo-L053R8 schematic pg 1 (MCU)

Schematic for
Nucleo L053R8
Nucleo-L053R8 schematic pg 2 (MCU)
Nucleo-L053R8 schematic pg 3 (STLINK-V2/1)
Nucleo-L053R8 schematic pg 4 (STLINK-V2/1)
Nucleo-L053R8 schematic pg 4 (POWER)
Nucleo-L053R8 schematic pg 4 (EXT CONN)
Installing STM32 on PC
• STM32CubeIDE is an advanced C/C++ development platform with peripheral conf iguration,
code generation, code compilation, and debug features for STM32 microcontrollers and
microprocessors. It is based on the Eclipse®/CDT™ framework and GCC toolchain for the
development, and GDB for the debugging. It allows the integration of the hundreds of
existing plugins that complete the features of the Eclipse® IDE.

Download
STM32CubeIDE
Installing Tera Term
• Tera Term (alternatively TeraTerm) is an open-source, free, software implemented,
terminal emulator (communications) program. It emulates different types of computer
terminals and supports telnet, SSH 1 & 2 and serial port connections.

Download
Tera Term
Hello World in STM…

Create STM32 Project file

Open STM32CubeIDE
Hello World in STM…
1 1. Select MCU/MPU selector
2. Type “STM32L053R8” in
2 commercial part number
3. Select STM32L053R8T6 from
list
4. Click Next

4
Hello World in STM…
1. Type the project’s name
2. Click Finish
1

2
Hello World in STM…
1. Right click PA5 and choose
GPIO_OUTPUT
1
2. Right click PC13 and choose
GPIO_INPUT

2
PA5

2
PC13

1
Hello World in STM…
Enabling USART2
1. Click connectivity in Categories
3 2. Choose USART2
3. Choose Asynchronous at Mode
4. Click NVIC Settings at Configuration
1 5. Tick global interrupt

5
2
Hello World in STM…
4

1
Clock Configuration
1. Click Clock Configuration Tab
2. Change from MSI to PLLCLK
3. Ensure 24MHz at HCLK
4. Click Device Config Tool Code Generation

3
2
Hello World in STM…
You will be presented with this display.
Follow instruction if your display is still in IOC
1 1. At Project Explorer, click Core and Src
2
3 2. Double click on main.c
Hello World in STM…
• Always write code in between the BEGIN and END comment
• NEVER write code outside these boundaries, as it will be omitted during the code generation of
IOC
Hello World in STM…
• Write the codes below according to the comment title

Keyboard shortcut (RUN


):
Alt + R + Enter

• Click icon to build the project (check for errors and warnings)
• If connected to hardware, click to download directly to board.
Hello World in STM…
• Once the code is downloaded, view the output on Tera Term
• Open Tera Term and choose STMicroelectronics on Serial

1 2
3
Hello World in STM…
• Go to Setup and choose Serial port…
• Change baudrate from 9600 to 115200 and click New setting

2 1
Hello World in STM…
• Click the black button on STM32 (RESET) and a text will appear on Tera
Term which is “HELLO WORLD!”

Congratulation on your STM32


Hello World! program

Keyboard shortcut (CLEAR):


Alt + E + B
Hello World in STM…
• If we observe the program, it only run once after the RESET button
was pressed.
• This is because, we wrote in between /*USER CODE BEGIN2*/ which is not in
a loop.
• How to always display the text on serial?
Hello World in STM…
What is HAL?
• The STM32 Hardware Abstraction Layer (HAL) provides a simple,
generic multi-instance set of APIs (application programming
interfaces) to interact with the upper layers like the user application,
libraries, and stacks.
• How do you check the list of HAL for certain features?
Opening List of HAL APIs

1
2
3

List of supported HAL API


4

Double Click

• User can view list of HAL such as


GPIO, UART, dma, etc.
Counting on STM32
Counting on STM32
• Observe the numbers on the serial.
• What is the minimum and maximum number?
-128 to 127
• Why?
Because we use int8_t data type
• How to have non negative numbers?
change from int8_t to uint8_t  0-255
Data Types Basics
Data Type Description Example Range

-2,147,483,648 to
int Whole numbers -2, 0, 42
2,147,483,647 (32-bit)
±1.7E-308 to ±1.7E+308
float Numbers with fractional parts 3.14, -0.001
(double precision)

char Single character 'a', '1', '$' 0 to 255 (ASCII)

bool Truth values true, false N/A

array Collection of elements, same type [1, 2, 3] Varies

string Sequence of characters "Hello, World!" Varies


DIGITAL OUTPUT
• Either HIGH / LOW depends on the system voltage.

• STM32 command uses:


• HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); or
• HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);

• GPIO_PIN_SET is HIGH
• GPIO_PIN_RESET is LOW
DIGITAL OUTPUT
• All items below are considered as digital output devices
• However, some of them can be controlled by the PWM technique
Blinking LED (A5)

OR
Warning – unused variable
• Observe that a warning will be indicated by a
yellow line marked on the right side of the main
window.
• Clicking the yellow line will bring you to the
problematic line. Put your arrow on top of the
exclamation mark to read the message.
• This warning is for unused variables.
• It can be omitted.
Blinking LED with condition

This program will blink LED for 5 times at 2Hz,


Then it will turn OFF the LED,
However, how do we know that the program is still running?
Blinking LED with condition

This program will blink LED for 5 times at 2Hz,


Then it will blinks the LED at an interval of 10Hz.
Blinking LED with SysTick
Blinking LED with SysTick
Blinking LED with SysTick

Try adding more sysTick function such as counting


unsigned number until 50 and reset back to 0 at an
interval of 0.2 sec
Blinking LED with SysTick
Blinking LED with SysTick
Basics of Control Structure
• We will be discussing briefly the usage of:
• For command
• While command
Control Structure: FOR statement
• FOR statement is used for conditional loop where it will perform the
commands if the condition is TRUE
• General term: for (initial value ; condition ; inc/dec)
• Example:
- for(int i=0;i<5;i++) [loops 5 times starting the no 0 until 4 by +1]
- for(int i=1;i<=4;i++) [loops 4 times starting the no 1 until 4 by +1]
- for(int i=10;i>2;i--) [loops 8 times starting the no 10 until 3 by -1]
Control Structure: FOR statement
int x, led=13;
x:
void setup()
{ pinMode (led, OUTPUT);
0
}
1
void loop()
{ for(x=0;x<3;x++)
2
{ digitalWrite(led, HIGH); delay(500);
digitalWrite(led, LOW); delay(500);
3
}
digitalWrite(led, HIGH); delay(3000);
digitalWrite(led, LOW); delay(500);
}
Control Structure: WHILE statement
• WHILE statement is also a conditional loop
• However, initial value and increment needs to be declared
• So, I usually use it as an infinite loop (condition always TRUE)
• General term: while (condition)
• Example:
- while(1) [loops forever]
- while (x<=10) [loops while the value of x is less than or equal to 10]
Control Structure: WHILE statement
int x, led=13;

void setup()
{ pinMode (led, OUTPUT);
• loop() subroutine
} will run once
void loop()
{ digitalWrite(led, HIGH);
delay(2000); • kelip2() will loop
digitalWrite(led, LOW);
delay(500); forever
kelip2();
}

void kelip2()
{ while(1)
{ digitalWrite(led, HIGH); delay(100);
digitalWrite(led, LOW); delay(100);
}
}
Control Structure: WHILE statement
int limitSwitch,motor=13;
void setup() • motorUp() subroutine will
{ pinMode(motor,OUTPUT);
pinMode(12,INPUT_PULLUP); run once
digitalWrite(motor,HIGH); //OFF
}

void loop() • WHILE will do infinite loop


{ motorUp();
while(1); //program run once
until limitSwitch is triggered
}

void motorUp()
{ digitalWrite(motor,LOW); //ON
• RETURN will invoke last
while(1) subroutine and enter infinite
{ limitSwitch = digitalRead(12);
if(limitSwitch==0) //pressed loop without any
{ digitalWrite(motor,HIGH); //OFF commands
return;
}
}
}
Control Structure: LOOP conclusion

Video
Programming Basics - Comments
• Ev e ry p ro g ram c an hav e a c o m m e nt d e p e nd i ng o n the
programmer itself.
Comments is not considered a
• Two ways of comment: programming instruction.
Therefore it can be omitted.
• Single line statement
//This is a single line comment

• Multiple line statement


/*This is a multiple statement comment.
This line is still a comment and it stops
at the end of this symbol*/
Programming Basics - Comments
Multiple line statement
/* Program : LED Blinking
Programmer : Abd Rahim Bin Kasiman
Tarikh : 15 DEC 2017
*/

void setup()
{ // initializes digital pin LED_BUILTIN as an output
pinMode (LED_BUILTIN, OUTPUT);
}
Single line statement
// the loop function runs over and over again forever
void loop()
{ digitalWrite(LED_BUILTIN,HIGH); //turn the LED ON
delay(1000); //wait for a second
digitalWrite(LED_BUILTIN,LOW); //turn the LED OFF
delay(1000); //wait for a second
}
Programming Basics - Indentation
• Indentation is a good programming behaviour to make reading
and troubleshooting of a program much easier and faster.
• To emphasize structured programming.
void setup() { void setup()
pinMode (LED_BUILTIN, OUTPUT); { pinMode (LED_BUILTIN, OUTPUT);
} }

void loop() { void loop()


digitalWrite(LED_BUILTIN,HIGH); { digitalWrite(LED_BUILTIN,HIGH);
delay(1000); delay(1000);
digitalWrite(LED_BUILTIN,LOW); digitalWrite(LED_BUILTIN,LOW);
delay(1000); K& delay(1000);
} }
Horstman
R n
Programming Basics - Identation
void setup()
{ for(int i=10;i<=13;i++) pinMode(i, OUTPUT);
Serial.begin(9600);
} Bracket for SETUP subroutine

void loop()
{ for(int i=0;i<3;i++)
{ digitalWrite(13,HIGH); delay(500);
digitalWrite(13,LOW); delay(500);
} Bracket for FOR structure
for(int j=0;j<5;j++)
{ digitalWrite(12,HIGH); delay(500);
digitalWrite(12,LOW); delay(500); Bracket for FOR structure
while(1)
{ digitalWrite(11,HIGH);
}
Bracket for WHILE structure
}
}
Bracket for LOOP subroutine
Programming Basics - Indent
Before formatting After formatting
void setup() void setup()
{pinMode(13, OUTPUT); { pinMode(13, OUTPUT);
} }

void loop() void loop()


{for(int i=0;i<3;i++) { for(int i=0;i<3;i++)
{kelip(); { kelip();
} }
while(1) while(1)
{digitalWrite(13,HIGH); { digitalWrite(13,HIGH);
} }
} }
void kelip() void kelip()
{digitalWrite(13,HIGH); delay(1000); { digitalWrite(13,HIGH); delay(1000);
digitalWrite(13,LOW); delay(1000); digitalWrite(13,LOW); delay(1000);
return; return;
} }
Programming Basics - Subroutines
• A subroutine (also called a subprogram) is an abstraction of a
process that is called which can:
• Receive data,
• Process data, and
• Return a value.

• Not all of these features need to be fulfilled.


• In short, three types of subroutines are commonly used in all
programming languages.
Programming Basics - Subroutines
int cnt=0;

void setup()
• Setup subroutine is being read once.
{ Serial.begin(9600);
} • In Loop subroutine, it calls upon tambah
void loop()
subroutine.
{ tambah();
} • The Tambah subroutine will process the
void tambah() variable value and print it.
{ cnt++;
delay(1000); • “return” will invoke the subroutine caller
Serial.println(cnt);
return; and loop these processes as it is the
} nature of the loop subroutine.
STATU
Subroutine Feature
S
Send data
NO
(argument)
Return data NO
Programming Basics – Subroutines 1
int cnt=13;

void setup() Caller function  no argument passed


{ Serial.begin(9600);
}

void loop()
{ tambah(); Callee function  no argument received
}

void tambah()
{ cnt++;
delay(1000);
Return value  no return value
Serial.println(cnt);
return;
}
Programming Basics – Subroutines 2
int cnt=5;
• In the Loop subroutine, it calls upon the
void setup()
{ Serial.begin(9600); t a m ba h s u br o u t i n e w i t h a s i n gl e
}
argument of data passed.
void loop()
{ tambah(15); • The Tambah subroutine will receive the
}
data while declaring a data type.
void tambah(int no1)
{ cnt = cnt+no1; • After that, it will process the variable
Serial.println(cnt);
return; value and print it.
}
• “return” will invoke the subroutine caller
STATU
Subroutine Feature without any value returned.
S
Send data
YES
(argument)
Return data NO
Process data YES
Programming Basics – Subroutines 2
int cnt=0,nombor=120;

void setup()
{ Serial.begin(9600);
STATU
} Subroutine Feature
S
void loop() Send data
{ tambah(15,20,nombor); YES
(argument)
}
Return data NO
void tambah(int no1, int no2, int no3) Process data YES
{ cnt = no3 / no2 + no1;
Serial.println(cnt);
return;
}

• 3 arguments are passed to tambah subroutine.


Programming Basics – Subroutines 3
int cnt=0;
• In Loop subroutine, cnt will push a
void setup() va lue of 3 (single a rgument ) to
{ Serial.begin(9600);
} subroutine tambah.
void loop() • Tambah subroutine will receive the
{ cnt = tambah(3);
Serial.println(cnt); value of 3 and insert it in a variable no1.
}
• It will process and the result is saved in
int tambah(int no1)
{ int hasil = no1 + 10; variable named hasil.
return hasil;
} • “return” sends this value to the caller
STATU and data received is saved in cnt.
Subroutine Feature
S
• Program will print the value on serial
Send data
YES
(argument) monitor.
Return data YES
Subroutines - Conclusions
void main (void) int arg1; int arg1;
{ ..
.. void main (void) void main (void)
subroutine(); { .. { ..
} .. ..
subroutine(arg1); int call = subroutine(arg1);
void subroutine (void) } }
{ ..
.. void subroutine (int no) int subroutine (int no)
return; { .. { ..
} .. int sum = no + 15;
return; ..
} return sum;
}

STATU STATU STATU


Feature Feature Feature
S S S
Send data NO Send data YES Send data YES
Return data NO Return data NO Return data YES
Process Process Process
YES YES YES
data data data
DIGITAL INPUT

Active High Active Low

Current Sourcing /
PULL_DOWN

Current Sinking /
PULL_UP
PB on Nucleo
PB on Nucleo
• At the IOC, ensure the digital pin has been declared.
• The PB on PC13 is wired as Active LOW, giving a reading of 0 (LOW)
if it is being pushed.
• If the PB is not pushed (idle mode), it will give a value of 1 (HIGH).
PB on Nucleo
DIGITAL INPUT: Debouncing
• Bouncing is the tendency of two metal contacts in an electronic
device to generate multiple signals as the contacts close or open.

• Debouncing is any kind of hardware device or software that ensures


that only a single signal will be acted upon for a single opening or
closing of a contact.
DIGITAL INPUT: Debouncing

Video
Bouncing on Nucleo
When PB is pushed and released, the cnt
should be incremented by 1 but the result
differs because of the bouncing!
Debouncing on Nucleo
We have debounced the signal. However, when PB is
pushed & HOLD, the value still increases at an interval
of 0.2s. How to solve?
Debouncing on Nucleo
This program ensures that even though the
push button is pushed and hold, the cnt
value only increase by +1
Debouncing on Nucleo
Same function but different technique!
EXTI on STM32
• An external interrupt (EXTI) is a computer system interrupt that
happens as a result of outside interference, whether that's from the
user, from peripherals, from other hardware devices or through a
network.
EXTI on STM32
• We are going to make a NEW program which will:
1. Display cnt value which is incremented every 0.1 second.
2. Toggle LED on PA5 when PB1 (PC13) is pushed via EXTI
EXTI setting on IOC

2
6

3
1

• Change from GPIO_INPUT to GPIO_EXT13


• Change to EXTI with Falling Edge Detection
• Click NVIC to enable Interrupt

5
EXTI setting on IOC

• Tick to Enable EXTI interrupt


• Click Code Generation to start programming
EXTI Code

• Notice that no reading of digital input


in the loop structure
• How does this flag changes value to
toggle the LED?

• Flag changes value by


interrupt request which is
from PB at PC13
configured as EXTI13
Active and Passive Buzzer
• Active buzzers:
• Apply a DC voltage to the pins and it will make a sound.
• Active buzzers have polarity.
• Downside: frequency of sound is fixed.

• Passive buzzers:
• Needs an AC signal to produce sound.
• Downside: need more complex circuitry to control them, like an oscillating
555 timer or a programmable microcontroller for PWM
Timer concept

• TIM2, TIM21 & TIM22: synchronizable general purpose timers


• Usually used for input capture / output compare, PWM or one-pulse mode output

• TIM6: basic timer


• Usually used for DAC trigger generation
Types of Timers
• General-Purpose Timers:
• These timers are versatile and can be used for a variety of tasks.
• They consist of a 16-bit auto-reload counter driven by a programmable prescaler.
• General-purpose timers can perform functions such as:
• Input Capture: Measuring the pulse lengths of input signals.
• Output Compare: Generating output waveforms.
• PWM (Pulse Width Modulation): Used for controlling motor speed, LED brightness, and other
applications.

• Timers 2, 21 & 22 fall into the category of general-purpose timers.


Types of Timers Which timer is
suitable for a passive
buzzer?
• Basic Timers:
• Basic timers are simpler and serve as a timebase for triggering other
operations.
• They are typically used to provide a reference time for tasks like triggering
digital-to-analog converters (DACs).
• Basic timers include Timer 6.
• Unlike general-purpose timers, basic timers do not have advanced features
like input capture or output compare.
PWM for Passive Buzzer
• The wiring on the buzzer is at pin PB10.
• If we click at PB10, there will be a list and there is an option of
TIM2_CH3 which represents Timer 2, Channel 3.
• Setup your IOC accordingly as in picture.
IOC setting for PWM
1. Go to TIM2 and set PWM
Generation CH3
2. At the parameter setting,
33
key in as below:
1
a. Prescaler : 24-1

2
2
b. Counter Period : 100-1

c. Pulse (16 bits value) : 50

3. Click Tool Code Generation


4
4
5 4. Start to program.
5

6
6
Programming PWM on buzzer
1 2
1 2

33
AML IOC on STM32CubeIDE
AML IOC on STM32CubeIDE
1. Connectivity
a) USART2 = Mode: Asynchronous
b) NVIC setting: Tick Global Interrupt

2. Clock Config
a) Tick from MSI to PLLCLK.
b) Ensure 24MHz on HCLK

3. Set pins according to AML Table…


AML IOC on STM32CubeIDE
AML IOC on STM32CubeIDE

Change GPIO input to Pull-up for PA1, PA4 & PB0 (digital input)
AML IOC on STM32CubeIDE

Change GPIO output to Push Pull for PA5 (digital output)


AML IOC on STM32CubeIDE

Change GPIO output to Open Drain for PA6 & PA7 & PB6 (digital output)
Then, click Device Config Tool Code Generator
AML LEDs
1 4

3 WHAT IS THE DISADVANTAGE OF WRITING CODE


USING THIS TECHNIQUE?
AML LEDs
Type the subroutine below and the calling function accordingly

Subroutine Calling function

D1
D4 D3 D2 D1

D2 0 1 0 1

D3
01012 = 510

D4 You can turn on any LED using any numbering system as follows…
Basic Numbering System
Numbering System LEDs
Decimal Binary Code Hex Code D4 D3 D2 D1
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F
AML LEDs
From the table, we can use any numbering system to light any LED for any sequence

or or

decimal binary hexadecimal

Any numbering system chosen above will produce the same result, which is:

D4 D3 D2 D1
Programming Basics - Subroutines
• A subroutine (also called a subprogram) is an abstraction of a
process that is called which can:
• Receive data,
• Process data, and
• Return a value.

• Not all of these features need to be fulfilled.


• In short, there are 3 types of subroutines that are commonly used in
all programming languages.
Programming Basics – Subroutines 1
int cnt=0;

void setup() • Setup subroutine is being read once.


{ Serial.begin(9600);
} • In Loop subroutine, it calls upon tambah
void loop() subroutine.
{ tambah();
} • Tambah subroutine will process the
void tambah() variable value and print it.
{ cnt++;
delay(1000);
Serial.println(cnt);
• “return” will invoke the subroutine caller
return; and loops these process as it is the
} STATU
Subroutine Feature
S nature of loop subroutine.
Send data
NO
(argument)
Return data NO
Process data YES
Programming Basics – Subroutines 1
int cnt=13;

void setup() Caller function  no argument passed


{ Serial.begin(9600);
}

void loop()
{ tambah(); Callee function  no argument received
}

void tambah()
{ cnt++;
delay(1000);
Return value  no return value
Serial.println(cnt);
return;
}
Programming Basics – Subroutines 2
int cnt=5;
• In Loop subroutine, it calls upon tambah
void setup()
{ Serial.begin(9600);
subroutine with a single argument of
} data passed.
void loop()
{ tambah(15);
• Tambah subroutine will receive the data
} while declaring a data type.
void tambah(int no1)
{ cnt = cnt+no1;
• After that, it will process the variable
Serial.println(cnt); value and print it.
return;
}
STATU • “return” will invoke the subroutine caller
Subroutine Feature
S without any value returned.
Send data
YES
(argument)
Return data NO
Process data YES
Programming Basics – Subroutines 2
int cnt=0,nombor=120;

void setup() STATU


{ Serial.begin(9600); Subroutine Feature
S
}
Send data
void loop()
YES
(argument)
{ tambah(15,20,nombor);
} Return data NO
Process data YES
void tambah(int no1, int no2, int no3)
{ cnt = no3 / no2 + no1;
Serial.println(cnt);
return;
}
• 3 arguments are passed to tambah subroutine.
Programming Basics – Subroutines 3
int cnt=0;
• In Loop subroutine, cnt will push a
void setup() va lue of 3 (single a rgument ) to
{ Serial.begin(9600);
} subroutine tambah.
void loop() • Tambah subroutine will receive the
{ cnt = tambah(3);
Serial.println(cnt); value of 3 and insert it in a variable no1.
}
• It will process and the result is saved in
int tambah(int no1)
{ int hasil = no1 + 10; variable named hasil.
return hasil;
}
STATU
• “return” sends this value to the caller
Subroutine Feature
S and data received is saved in cnt.
Send data
YES • Program will print the value on serial
(argument)
Return data YES monitor.
Process data YES
Subroutines - Conclusions
void main (void) int arg1; int arg1;
{ ..
.. void main (void) void main (void)
subroutine(); { .. { ..
} .. ..
subroutine(arg1); int call = subroutine(arg1);
void subroutine (void) } }
{ ..
.. void subroutine (int no) int subroutine (int no)
return; { .. { ..
} .. int sum = no + 15;
return; ..
} return sum;
}

STATU STATU STATU


Feature Feature Feature
S S S
Send data NO Send data YES Send data YES
Return data NO Return data NO Return data YES
Process Process Process
YES YES YES
AML LEDs Exercise
1. Make a running LED by incrementing the value of argument (1-15)
in the LEDs subroutine (use FOR control structure)
2. Make a running LED but use sysTick to increment the value of
argument for LEDs().
3. Make a knight rider effect.
AML Push Button

This is the basic digital input whereby we read the


pins directly and give output to LED
AML Push Button
• Can we read all the push button at once without reading it
individually?
• The subroutine introduced will read the push button in 3 bit form.
• How does a 3 bit value represented by 3 push buttons?
AML Push Button
Decimal PB3 PB2 PB1
0 0 0 0
Bit 2 Bit 1 Bit 0 1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
Legend:
1 = Pushed
PB1 PB2 PB3 0 = NOT pushed
(A1) (A4) (B0)
AML Push Button

• If PB1 and PB3 is pushed, 1012 = 510


• If PB3 is pushed, 1002 = 410
• If PB2 and PB3 is pushed, 1102 = 610

• This algorithm can be applied to any digital input.


• This type of algo can be used with a returning value for
the called function.
• The programming are as follows:

PB1 PB2 PB3


(A1) (A4) (B0)
AML Push Button
AML Push Button
• The previous program can only read the PB status in 3 bit.
• We shall code the STM32 for:
• Increment cnt value as we press PB3
• Decrement cnt value as we press PB1
• Reset cnt value as we press PB2
AML Push Button
• All codes below are not edited which are:
• Includes
If PB is pressed and hold, cnt value will
• PD increase at an interval of 0.2s

• PTD
How to solve?
• PV
• BEGIN 0
AML Push Button
AML LEDs + PB Exercise
• Make a program to:
1. Blink LED on PA5 at an interval of 1s.
2. Display value of time interval on serial.
3. If S3 is pressed, it will decrease the interval by -0.2s
4. If S1 is pressed, it will increase the interval by 1s
5. Lowest time interval is 0.2s and highest is 3s
6. If S2 is pressed, it will reset the time interval to 1s
7. If the time interval is 0.2s and the user press the PB for 3s, it will display on
serial “HI RAHIM”
AML Buzzer
• Your buzzer is wired on B3 as Active HIGH interfaced with the PNP
transistor as load switching.
• Add buzzer by going to IOC, declaring it as GPIO_OUTPUT, and
renaming it BUZZER.
• Set GPIO mode as Open Drain and generate code.
• Add the necessary code as follows:
AML Buzzer AMLBuzz

Now, every time you press PB, a beeping sound will occur.
Make a subroutine that beeps according to the argument value
AML Buzzer

Every time you press PB, two beeping sounds will occur!
AML 7 Segment
• The 7 segment LED is interfaced with 74HC595 which is an 8 bit
shift register.
• In order to control the 7-segment, we need to understand the
working principle of a shift register.
• It uses a SIPO register where it stands for Serial Input, Parallel
Output.
• In general, the input data is given bit by bit serially.
• Once the Latch pin is enabled, the content of shift register is copied
to 2 register which is storage/latch register that is connected to Q
nd
0

–Q 7
74595 concept on LEDs
7-segment CA
DE
dp g f e d c b a BIN HEX
C
1111111
1 1 1 1 1 1 1 1 nil FF
1
1100000
1 1 0 0 0 0 0 0 0 C0
0
1111100
1 1 1 1 1 0 0 1 1 F9
1
1010010
1 0 1 0 0 1 0 0 2 A4
0
1011000
1 0 1 1 0 0 0 0 3 B0
0
1001100
1 0 0 1 1 0 0 1 4 99
1
1001001
1 0 0 1 0 0 1 0 5 92
0
1000001
1 0 0 0 0 0 1 0 6 82
74595 concept on 7-segment CA
74595 on 2 units of 7-segment
• The Q7’ of the 1st 74595 is fed to Data Pin
on 2nd 74595
• Other pin such as Latch, Clk & reset on 2nd
74595 is shared with the 1st pin of 74595
7-segment circuit on AML
This circuit is triggered manually.
Let’s wire each PB to signal pins.

00100101 00101111

LS
MSB B
7-segment circuit on AML

This circuit is wired to the signal


pins described below.

How to program?
Programming 7-segment on AML pg1
Programming 7-segment on AML pg2

To trigger 74595 ic for


shift register

Combining the number to be displayed To segregate 4 digit number to

& segment number to lit individual digit


Programming 7-segment on AML pg3

Upload the code and observe the 7-segment.


Did the number lit accordingly (4587) ?

Did you update IOC for PA8, PA9 & PB5 as


GPIO_OUTPUT?

Try updating the IOC and generate the code. Did it


work?
7-segment program explanation
If x = 4536;

Case 0: 4536 / 1000 = 4


buff [0] = num[4] = 0x99 = 1001 1001
buff [0] = num[4]<<8 = 1001 1001 0000 0000
buff [0] = (num[4]<<8) | seg [0]
= 0x99 | 0xF1
= 1001 1001 0000 0000 (0x99)
= 0000 0000 1111 0001 (0xF1) +
= 1001 1001 1111 0001

0 1 2 3 4 5 6 7 8 9
7-segment program explanation
If x = 4536;

Case 1: (4536 % 1000) = 536 / 100 = 5


buff [1] = num[5] = 0x92 = 1001 0010
buff [1] = num[5]<<8 = 1001 0010 0000 0000
buff [1] = (num[5]<<8) | seg [1]
= 0x92 | 0xF2
= 1001 0010 0000 0000 (0x92)
= 0000 0000 1111 0010 (0xF2) +
= 1001 0010 1111 0010

0 1 2 3 4 5 6 7 8 9

Continue the same steps for case 2 and case 3


Programming cnt on 7-segment
• The previous program displays the number but the number is f ixed
value which is 4587.
• How to make a counter which is 1 Hz and resets at number 12?
• We will need to make another sysTick having 1 Hz in order to
change the value of argument inside multiplexSegment subroutine.
• The upcoming code is edited in the while loop only.
Programming cnt on 7-segment
• t0 is to refresh the individual digits of the seven segment at a
rate of 4ms
• t1 is to change the argument value of multiplexSegment
having an initial value of 0 and are incremented at a rate of 1s
until the value reaches the number 12, then the value is reset
to 0
Timer to trigger displaySegment
• Although we have a running 7 segment, it is running on sysTick.
• sysTick timer is usually found in ARM cores while timers are from
chip vendors.
• sysTick timers are commonly used for polling or interrupts of
simple durations.
• Timers on the other hand, can do much more and sometimes, have
multiple timers having features different from each others.
Timer concept

• TIM2, TIM21 & TIM22: synchronizable general purpose timers


• Usually used for input capture / output compare, PWM or one-pulse mode output

• TIM6: basic timer


• Usually used for DAC trigger generation
TIM6
• STM32 currently on 24MHz, (based on clock config during IOC).
• 1 cycle = 1/24,000,000 which is 42 x 10-9s = 42ns. This is too fast.
• We use prescaler within 16 bit value to reduce clock speed.
• If prescaler = 2400, then frequency is : 2400 / 24,000,000 = 1µs.
• Even though the timer capability is 16 bit (65536) before rolling
over, we can limit this to 1000.
• This will generate a timer of: 1µs x 1000 = 1ms.
TIM6 exercise

ANS1 ANS2 ANS3 ANS4


Prescaler 2,400 24,000 12,000 240
Counter Period 10,000 1,000 2,000 100,000

How to apply TIMER in STM32


programming?
TIM6 IOC on STM32
1. Open IOC and expand Timers
under Categories.
3
2. Select TIM6 and activate it.
3. Select Parameter Settings and
1
change the parameter:
7 • Prescaler : 2,400-1
4
2 • Cnt Period : 10,000-1
8
4. Select NVIC Settings
5
• Tick Enable for interrupt
6
5. Click Tool Code Generation
TIM6 code on STM32
Attach this instruction on the previous
To start interrupt timer program

The output is a blinking LED with a


frequency of 1Hz

This subroutine is to access the timer function

Insert instructions within this bracket


Timer to trigger displaySegment
• Modify the program so that it will run the displaySegment
subroutine using TIM6.

Is the 7-segment displaying the numbers correctly?

Did you change the frequency from 1Hz to 250Hz


(4ms)? How to change the frequency?
Timer to trigger displaySegment
• Frequency needed = 250Hz (4ms)
• Suggested values for Timer Parameter Settings:
• Prescaler value : 2400-1
• Counter Period : 40-1

• Don’t forget to click the Tool Code Generation icon


• Run the program and the 7-segment will display the correct
sequence.
Analog Input
• Analog input is the ability to convert voltage levels to digital
numbers.
• Digital input can only read HIGH or LOW status.
• However, analog inputs read numbers between HIGH (5V) and LOW
(0V).
• It has 16 external channels where channel PA0, PA4 & PA5 are fast
channels.
• It performs conversions in a single-shot or scan mode.
Analog Input Concept
Let’s
Let’s
12 upgrade
bit analogueConclusion
start with
to12bit
bit=analogue
input 2n = 212 =input
analogue input
4096 Binary no
voltage(v)

3.3
1
11

1 bit 2 bit 8 bit 10 bit 12 bit


2.475
ADC 0-1 0-3 0 - 255 0 - 1023 10 0-4095
Range 1.65 V 0.825 V 0.01289 V 0.003223 V 0.000805 V
1.65
Accuracy Very low Very low High High Very high
0
01

0.825
00
Analog Pins on STM32L053

ADC_IN10 -
ADC_IN11 -
ADC_IN12 -
ADC_IN13 -

ADC_IN0 -
ADC_IN1 -
ADC_IN2 -
ADC_IN3 -

ADC_IN4 -
ADC_IN5 -
ADC_IN6 -
ADC_IN7 -
ADC_IN14 -
ADC_IN15 -
ADC_IN8 -
ADC_IN9 -
IOC for Analog on STM32
1. Open Analog in Categories.
2. Select ADC.
3. Tick IN0 as our variable resistor is
wired to PA0.
4. In parameter setting, change:
a. Resolution : 10-bit

b. Continuous Conversion : Enabled

c. Sampling time : 160.5 cycles

5. Click icon Tool Code Generation.


Programming to read Analog
Add calling function at 10ms interval
Add subroutine to read Analog in USER CODE 0

Add global variable

Insert GetTick in t2
Reading multiple ADC on STM32
• The previous program only reads single ADC at IN0.
• What if there are 3 analog inputs to be read?
• We will read each channel and save them in an array before displaying it
on USART.
• Connect LM35 and a variable resistor to the label PA4 and PA5 on AML
shield according to the picture.

• Change IOC to activate:


• ADC_IN11 (PC1) [Arduino A4] - LM35
• ADC_IN10 (PC0) [Arduino A5] – pin header
Wiring 2 ADC components on AML

LM35
• Arduino A4 = PC1
(ADC_IN11)
• Arduino A5 = PC0
(ADC_IN10)
IOC setup for multiple ADC

1. In IOC, just tick IN10 & IN11.


2. Click icon Tool Code Generation.
Reading multiple ADC on STM32

Edit the previous program by adding:


1. Variables to read array
2. Add control structure FOR to store ADC
in array
LM35 Temperature Sensor (°C)
+10mV/°C for a range of -55°C to 150°C

0°C = 0V
1°C = 10mV = 0.01V
10°C = 100mV = 0.1V
100°C = 1000mV = 1.0V
150°C = 1500mV = 1.5V
LM35: Exercise
What is the voltage for these readings?

• 23°C = 230mV = 0.23V


• 30°C = 300mV = 0.3V
• 37°C = 370mV = 0.37V HOW to display
• 50°C = 500mV = 0.5V temperature in STM32?

What is the temperature for these readings?

• 0.17V = 170mV / 10mV = 17°C


• 1.21V = 1210mV / 10mV= 121°C
• 0.95V = 950mV / 10mV = 95°C
• 1.77V = undefined
Analog OUTPUT, what is it?

Modify the current program by


adding these commands

Run the command. Did it display voltage?


Displaying float value
1
1. Click Project and select Properties
3 5 2. Select Settings > Miscellaneous.
3. Click the add icon.

6 4. Type in –u _printf_float and click OK.


5. Click Apply and Close.
7 6. Try running the program again and
2 observe the output on serial.
4

8
Displaying temperature AMLanC

• From the previous slides, there are exercise that states if 0.17V =
17⁰C
• From observation, the voltage is multiplied with 100 to obtain the
temperature in celcius
ANALOG CASE STUDY
Analog Input: Analog in Linear Graph
Flame Sensor Module

How to measure distance


if given 3.2V??

• Used to detect fire or other light source with wavelength of 760nm ~ 1100nm light.

• Interface: Analog or digital

• Detection range: 20cm(1V) ~ 100cm(4.8V)


Analog Input: Analog in Linear Graph
Step 1: Coordinate
X Y (x,y)

20cm 1V (20,1)

100cm 4.8V (100,4.8)

Step 2: Graph
Y (volt)
4.8V

1V

X (dist)
20cm 100cm
Analog Input: Analog in Linear Graph

Can you calculate the voltage


if the distance is:

a) 25cm
b) 105cm
Analog Input: Analog in Linear Graph
Anemometer
• Output signal range: 0-5V
• Supply Voltage: DC12-24V
• Resolution: 0.1m/s
• Effective range: 0-30m/s
• Type: 3 cups
• System error: ±3%
• Connection mode: 3 wires
• Wiring map: 12V, Gnd, analog

Calculate the speed if


voltage measured is 4.2V
Analog Input: Analog in Linear Graph
50A current sensor
• Supply Voltage: DC5V
• Output sensitivity: 40mV/A
• System error: ±0.8% at 25°C
• Output voltage proportional to DC/AC current
• Extremely stable output offset voltage
• Monolithic Hall IC for high reliability

1. Calculate the range of


voltage for 0A to 50A.

2. Calculate the voltage if


current is 11A.
EXPRESS CREATIVITY THROUGH CODING
Practise Makes Perfect
Thank you
Answers AML LEDs Q1
Answers AML LEDs Q2
Answers AML LEDs Q3
Answer AML PB, pg1
Answer AML PB, pg2

You might also like