Sunteți pe pagina 1din 180

12/17/2016

PEMROGRAMAN
MIKROKONTROLER LANJUT

Program Studi Teknik Elektro Industri


Departemen Teknik Elektro
Politeknik Elektronika Negeri Surabaya
eka@pens.ac.id
Department of electrical engineering PENS
© Maret 2016
1

Materi
1. A Conceptual of Power Electronics Device and Control System based on microcontroller
2. Controlling DC–DC Converters (SMPS) with Microcontroller (Concept of isolated controller for DC-DC Converter)
3. Controlling DC–DC Converters (SMPS) with Microcontroller (Design of Voltage and Current Sensor )
4. Controlling DC–DC Converters (SMPS) with Microcontroller (Concept of programmable DC power supply)
5. Controlling DC–DC Converters (SMPS) with Microcontroller (Concept of DC-DC converter for PV MPPT)
6. Controlling DC–AC Converters (Inverter) with Microcontroller
7. Controlling DC–AC Converters (Inverter) with Microcontroller (Scalar Control)
8. Digital Firing Angle Control of Thyristor with Microcontroller
9. UART Serial Communication (Pooling method)
10. UART Serial Communication (Interrupt method)
11. UART Serial Communication (DMA method)
12. Programming Microcontroller with Matlab (Simulink & Waijung Blockset)
13. Programming Microcontroller with Matlab (LCD Character and ADC)
14. Programming Microcontroller with Matlab Regular DAC and Arbitrary Waveform Generator
15. Programming Microcontroller with Matlab Basic PWM and Advanced PWM
16. Programming Microcontroller with Matlab Timer Encoder And Timer Capture
2

1
12/17/2016

Ilmu Pendukung
Belajar mikrokontroler lanjutan memerlukan ilmu
pendukung yang lain untuk meng-aplikasikan ke sistem
elektronik yang kompleks, diantaranya:
• Bahasa Pemrograman
• Rangkaian Listrik.
• Rangkaian Elektronika.
• Elektronika digital.
• Elektronika Daya.
• Teknik sistem kendali/teknik pengaturan

2
12/17/2016

Minggu Ke - 1

A Conceptual of Power Electronics Device


and Control System based on microcontroller
6

3
12/17/2016

A Conceptual Power Electronics Device


Control System Block Diagram

PC or
High Level
Controller
device
Microcontroller,
FPGA, etc IGBT, MOSFET

4
12/17/2016

• Power Electronic device (Si-MOSFET, IGBT, SiC-MOSFET, GaN) diataur dengan


memberikan modulasi lebar pulsa (PWM) pada Gate.
• Tegangan yang diperlukan untuk mengoperasikan Gate dari Power Electronic
device bervariasi sesuai dengan karakteristik masing-masing komponen.
• GPIO dari microcontroller tidak mampu menghasilkan tegangan yang sesuai
dengan kebutuhan Gate dari Power Electronic device sehingga diperlukan
Gate Driver 9

Implementing an Isolated IGBT/MOSFET Gate Driver


on Microcontroller Control System

Pulse Transformer Gate Driver (Traditional)


Optocoupler Gate Driver
• Driving the output to up to 1 MHz
• Driving the output to speeds up to 1 MHz • Not requiring isolated power supplies to drive the secondary
• Required isolated power supplies to drive the secondary side IGBT/MOSFETs.
side IGBT/MOSFETs. • Limitation of pulse transformers is that they may not work
• The LED current must be increased to more than 10 mA well in applications that require signals with more than 50%
10
duty cycle

5
12/17/2016

Implementing an Isolated IGBT/MOSFET Gate Driver


on Microcontroller Control System

PS9552

Example
IGBT/MOSFET
Gate Driver

11
FOD3182 PS9552 TLP250

Implementing an Isolated IGBT/MOSFET Gate Driver


on Microcontroller Control System

12

6
12/17/2016

Setting Dead-Time
• The inverter control circuit
provides output to drive its
load by switching IGBT1
(Upper Arm) and IGBT2
(Lower Arm) alternately on
and off .
• If the dead-time is
insufficient, IGBT1 and
IGBT2 could both switch on,
causing a short-circuit Normal Operation of the Short Circuit of the Inverter
current and breakdown Inverter Control Circuit Control Circuit
of the IGBTs

13

Setting Dead-Time

• Dead-time, TDEAD, should be Driver


set so that IGBT1 and IGBT2
are not on at the same time.
• A value greater than the Driver
difference between the
maximum total turn-off
time (tOFF Total max) and the
minimum total turn-on time
(tON Total min)

14

7
12/17/2016

Implementing an Isolated DC-DC power supply


for Driving IGBT/MOSFET
• One of the main features of
the majority of DC/DC -
converters is their high
galvanic isolation capability

15

Isolated Alternative Supply Configurations


for Driving IGBT/MOSFET

Current sharing resistors used to Isolating diodes used for parallel Outputs connected in series include
parallel two converters redundant connection of two converters reverse voltage protection diodes

16

8
12/17/2016

Isolated Supply for Driving IGBT/MOSFET

17

Non-Isolated Alternative Supply Configurations


for Driving IGBT/MOSFET

Non isolated negative rail Input and output in series

18

9
12/17/2016

Recommended Input and output filtering circuit


Reduce ripple
• C1: EMI Filter and to reduce input ripple:
connect aluminum electrolytic capacitor,
please refer to datasheet to verify
maximum capacitance value.
• L2/L3/L4: Form an LC filter network to
reduce output noise and ripple. It is
recommended to use powered iron
magnetic cores and copper magnet wire
suitably rated.
• C2/C3: Form an LC filter network to
reduce output noise and ripple. It is
recommended to
use aluminum electrolytic capacitors.
Please see datasheet for maximum
values.

19

Recommended Input and output filtering circuit


noise reduction

20

10
12/17/2016

A Conceptual of Isolation Amplifier Module


for Sensor interface
Voltage,
Current,
temperature
pressure
location
Isolated DC-DC Microcontroller /
speed Processor
Converter
flux
humidity
etc..

21

A Conceptual of Isolation Amplifier Module


for Sensor interface

22

11
12/17/2016

A Conceptual of Isolation Amplifier Module


for Sensor interface

23

A Conceptual of Isolation Amplifier Module


for Sensor interface

24
Transformerless Power Supply

12
12/17/2016

Minggu Ke - 2

25

Controlling DC–DC Converters (SMPS) with Microcontroller


(Concept of isolated controller for DC-DC Converter)

26

13
12/17/2016

Review SMPS topologies and output power

• Switch mode power supply


(SMPS) circuits contain
networks of energy storage
inductors and capacitors
as well as power handling
electronic switches and
rectifiers.

27

Review on Non Isolated DC-DC Converter

Control

28

14
12/17/2016

Review on Isolated DC-DC Converter

Control

29

Review on SMPS Circuit and its transfer function

• Each converter type are controlled with duty cycle (D)


• Proper duty cycle is key point on controlling converter 30

15
12/17/2016

Review on SMPS Circuit and its transfer function

• Each converter type are controlled with duty cycle (D)


• Proper duty cycle is key point on controlling converter 31

Concept of isolated controller for DC-DC Converter

GND for Power Side

32
GND for Control Side

16
12/17/2016

Concept of isolated controller for DC-DC Converter

GND for Power Side

GND for
GND for IGBT/MOSFET
IGBT/MOSFET (floating)
(floating)

33
GND for Control Side
Concept of isolated controller for
DC-DC Converter

GND for Power Side


GND for High Side IGBT/MOSFET
(floating)

Use different power supply for


IGBT/MOSFET Driver

GND for High Side IGBT/MOSFET


(floating)

GND for Low Side IGBT/MOSFET is


connected to GND of Power Sinde

34
GND for Control Side

17
12/17/2016

Concept of isolated controller for

GND for Power Side


DC-DC Converter

Voltage Sensor

Use different power


supply for
IGBT/MOSFET Driver
and Isolation Amplifier

differential
ampifier
GND for Control Side
GND for Isolation
35
Amplifier (floating)
Concept of isolated controller for

GND for Power Side


DC-DC Converter

Use different power


supply for
GND IGBT/MOSFET Driver
for IGBT/MOSFET and Isolation Amplifier
Driver (floating)

differential
ampifier
GND for Control Side
GND for Isolation
36
Amplifier (floating)

18
12/17/2016

Concept of isolated controller for

GND
GND for Power Side for IGBT/MOSFET Voltage Sensor
DC-DC Converter

Driver (floating)

Use different power supply


for IGBT/MOSFET Driver and
Isolation Amplifier

differential
ampifier

GND for Isolation


Amplifier (floating)

GND for Control Side 37

38

19
12/17/2016

39

40

20
12/17/2016

41

42

21
12/17/2016

43

44

22
12/17/2016

45

46

23
12/17/2016

Minggu Ke - 3

47

Controlling DC–DC Converters (SMPS) with Microcontroller


(Design of Voltage and Current Sensor )

48

24
12/17/2016

Voltage and Current Sensor Design


Voltage
The voltage between two points is the energy required to move a unit of positive charge from a
lower to a higher potential. Voltage is measured in Volts (V)

Current
Current is the rate of electric charge through a point. The unit of measure is the Ampere or Amp (A)

Resistance
Given a piece of conducting material connected to a voltage difference V, which drives through it a
current I, the resistance is defined as

Power
The power dissipated by a resistor is

49

Voltage and Current Sensor Design


• Kirchhoff’s Laws

50

25
12/17/2016

Voltage and Current Sensor Design


• Voltage divider

51

Isolated Voltage Measurement

The AMC1200 and AMC1200B can


also be used for isolated voltage
measurement applications, as
shown in a simplified way in Figure
In such applications, usually a
resistor divider (R1 and R2) is used
to match the relatively small input
voltage range of the AMC device.
R2 and the input resistance RIN of
the AMC1200 also create a
resistance divider that results in
additional gain error. With the
assumption that R1 and RIN have a
considerably higher value than R2,
the resulting total gain error can be
estimated using Equation 1:

52

26
12/17/2016

Isolated Voltage Measurement

53

Isolated Current Measurement


Shunt-Based Current Sensing
The floating ground reference
(GND1) is derived from the end
of the shunt resistor, which is
connected to the negative
input of the AMC1200 (VINN).
If a four-terminal shunt is used,
the inputs of the AMC1200 are
connected to the inner leads
and GND1 is connected to one
of the outer shunt leads. The
differential input of the
AMC1200 ensures accurate
operation even in noisy
environments

The differential output of the AMC1200 can either directly drive an analog-to-digital converter
(ADC) input or cane further filtered before being processed by the ADC. 54

27
12/17/2016

Isolated Current Measurement

Shunt-Based Current Sensing 55

Isolated Voltage and Current Measurement

Isolated Current and Voltage Sensing in Frequency Inverters 56

28
12/17/2016

Voltage and Current


Measurement

R-Shunt as
Isolated

current sensor

Voltage divider as
voltage sensor

57
shunt-based current sensing in smart electricity meter (e-meter)

Transformerless Power Supply for isolation power


supply in AC system

58

29
12/17/2016

Getting Voltage or Current value from ADC

Vsen= ∗ Vs= ∗

Vsen = ∗ _

Vs= ∗ ∗ _

59

Getting Voltage or Current value from ADC

Vsen= ∗ P=
.
Vsen= ∗ 60
. P=
. .
Vsen= ∗ 60
.
Vsen= 0.05564 ∗ 60 P=
.
Vsen= 3.3384 P= 60.70

R1 and R2 ratio value must


R1 and R2 value are not properly
be designed according to
very high power dissipation
maximum ADC input voltage
60

30
12/17/2016

Getting Voltage or Current value from ADC

Vsen= ∗ P=
Vsen= ∗ 60
P=
Vsen= ∗ 60
Vsen= 0.05564 ∗ 60 P=
Vsen= 3.3384 P= 0.06070

R1 and R2 ratio value must


be designed according to
maximum ADC input voltage
and R1 and R2 should have R1 and R2 value are acceptable
high resistant Low power dissipation
61

Getting Voltage or Current value from ADC

Vrsh = ℎ∗ ℎ Prsh = ℎ ∗ ℎ
Vrsh = 10 ∗ 1 Prsh = 10 ∗ 1
Vrsh = 10 Prsh = 100

Rsh value are not properly


Rsh value are not properly very high power dissipation
very high drop voltage
62

31
12/17/2016

Getting Voltage or Current value from ADC

Vrsh = ℎ∗ ℎ Prsh = ℎ ∗ ℎ
Vrsh = 10 ∗ 0.1 Prsh = 10 ∗ 0.1
Vrsh = 1 Prsh = 10

Rsh value are acceptable Rsh value are not properly


very high power dissipation

63

Getting Voltage or Current value from ADC

Vrsh = ℎ∗ ℎ Prsh = ℎ ∗ ℎ
Vrsh = 10 ∗ 0.01 Prsh = 10 ∗ 0.01
Vrsh = 0.1 Prsh = 1

Rsh value are acceptable, but Rsh value are value are
need amplifier and high ADC acceptable
resulotion Low power dissipation

64

32
12/17/2016

Getting Voltage or Current value from ADC

Determine R value for circuit below

65

66

33
12/17/2016

Minggu Ke - 4

67

Controlling DC–DC Converters (SMPS) with Microcontroller


(Concept of programmable DC power supply)

68

34
12/17/2016

Concept of Controlling SMPS

A voltage loop and


current loop are used
in the system. The
error signal is
generated by the
comparison
between the
reference and the
sample value of the
output voltage.

69

Controlling SMPS with Microcontroller


Work flow
1. We need define CPU
Clock Init clcok

2. We need multi channel ADC to


ADC_Init(); read Voltage and Current value

TIMER_Init(); 3. We need to generate PWM


signal

lcd_Init(); 4. We need to displaying information such as


Voltage and Current value

Keypad_init(); 5. We need to interface input

Control loop(); 6. Voltage or Current control algorithm

70

35
12/17/2016

Configure GPIO
for Multi channel ADC

71

Configure GPIO for Multi channel ADC

72

36
12/17/2016

• Untuk memulai
pemrograman pada
MDK-ARM, Buka project
window, cari sub folder 1. Click
Application/User
kemudian buka main.c
• Selanjutnya anda harus
menambahkan file LCD 2. Click File lcd driver
driver yaitu : berhasil
• lcd_character.c ditambahkan
• lcd_character.h
3. Click
• Selanjutnya atur
inisialisasi LCD melalui
wizard
73

Contoh Program <ADC - DMA>

int main(void)
#include "stm32f4xx_hal.h" {
#include "lcd_character.h" char buffer[20];
#include "stdio.h“ HAL_Init();
/* Configure the system clock */
/* Private variables -------------------------*/ SystemClock_Config();
ADC_HandleTypeDef hadc1; /* Initialize all configured peripherals */
DMA_HandleTypeDef hdma_adc1; MX_GPIO_Init();
TIM_HandleTypeDef htim2; MX_DMA_Init();
MX_ADC1_Init();
__IO uint16_t ADC_value[8]; MX_TIM2_Init();
HAL_ADC_Start_DMA(&hadc1,(uint32_t*) &ADC_value,8);
/* Private function prototypes ---------*/ lcd_init();
void SystemClock_Config(void); lcd_gotoxy(0,0);
static void MX_GPIO_Init(void); lcd_puts("Tes ADC");
static void MX_DMA_Init(void); while (1)
static void MX_ADC1_Init(void); {
static void MX_TIM2_Init(void); sprintf(buffer,"P1 %4d P2 %4d",ADC_value[4],ADC_value[5]);
lcd_gotoxy(0,1);
lcd_puts(buffer);
HAL_Delay(100);
}
} 74

37
12/17/2016

PWM Frequency ?

• Pada microcontroller ARM Cortex M4, PWM dapat dihasilkan melalui


timer dengan frekwensi dan duty cycle yang dapat diatur sesuai
dengan kebutuhan. Ilustrasi cara menghasilkan PWM melalui timer
seperti ditunjukkan pada gambar berikut ini.
Timer Period (Maximum 16 or 32bit)

Compare Value

Timer CNT

Timer_CNT_Clock

PWM Ouput

PWM period 75

PWM Frequency ?

Besarnya frekwesi PWM dapat dihitung melalui persamaan berikut :

_ ( )
( ) = (1)

_ ( )
= (2)
( )

Contoh Frekwensi PWM yang dikehendaki 10 KHz, menggunakan timer


1, dengan clock CPU 168 MHz.

76

38
12/17/2016

PWM Frequency ?

Timer 1 merupakan timer dibawah kendali APB 2 serpti pada gambar berikut :

77

PWM Frequency ?
PWM Frequency ?
MAX INTERFACE MAX TIMER
Timer Type Resolution Prescaler Channels APB
CLOCK CLOCK*
TIM1, TIM8 Advanced 16bit 16bit 4 SysClk/2 SysClk 2
TIM2, TIM5 General purpose 32bit 16bit 4 SysClk/4 SysClk, SysClk/2 1
TIM3, TIM4 General purpose 16bit 16bit 4 SysClk/4 SysClk, SysClk/2 1
TIM9 General purpose 16bit 16bit 2 SysClk/2 SysClk 2
TIM10, TIM11 General purpose 16bit 16bit 1 SysClk/2 SysClk 2
TIM12 General purpose 16bit 16bit 2 SysClk/4 SysClk, SysClk/2 1
TIM13, TIM14 General purpose 16bit 16bit 1 SysClk/4 SysClk, SysClk/2 1
TIM6, TIM7 Basic 16bit 16bit 0 SysClk/4 SysClk, SysClk/2 1

78

39
12/17/2016

PWM Frequency ?

dapat dihitung dengan persamaan berikut :



=
_

Dalam hal ini, diasumsikan timer 1 menggunakan frekwensi yang paling tinggi sehingga dipilih pre scaler 0,
maka :

= è = 168000000

Untuk frekwensi PWM 10 kHz, dapat dihitung sebagai berikut :


_ ( )
= è = è 16801.68
( ) ( )

Karena counter pada microcontroller berupa bilangn bulat, maka semua perhitungan berlaku pembulatan kebawah
sehingga menjadi 16801, Timer CNT dihitung mulai 0 to 16800.

79

Configure for Multi channel PWM


Output
 PWMmerupakan sailitas
yang disediakan oleh
TIMER, dalam satu timer
dapat menghasilkan
beberapa chanel output
PWM
 Inisialisai GPIO PWM
adalah TIMx_CHx

80

40
12/17/2016

Configure for Multi channel PWM


Output

81

Configure for Multi channel PWM


Output

10000

82

41
12/17/2016

Contoh Program PWM

83

Review Keypad & LCD

 Pada dasarnya STM32CubeMX tidak


dilengkapi library 4x4 matrix keypad
 Untuk dapat berinteraksi dengan 4x4
matrix keypad dapat dilakukan dengan
menambahkan file C code driver matrix
keypad pada MDK-ARM
 Inisialisai GPIO untuk matrix keypad
adalah GPIO OUTPUT untuk baris dan
GPIO INPUT untuk kolom
 Pada Pelatihan ini matrix keypad
terpasang pada GPIOE, E8-E11 sebagai
kolom dan E12-E15 sebagai baris

84

42
12/17/2016

Review Keypad & LCD

• Untuk memulai
pemrograman pada MDK-
ARM, Buka project
window, cari sub folder
Application/User 1. Click
kemudian buka main.c
• Selanjutnya anda harus
menambahkan file keypad
dan LCD driver yaitu :
• keypad_4x4.c
2. Click File lcd driver
• keypad_4x4.h berhasil
• lcd_character.c ditambahkan
• lcd_character.h
• Selanjutnya atur 3. Click
inisialisasi file keypad dan
LCD melalui wizard

85

Review Keypad & LCD

 Stelah menambahkan file


LCD driver :
 keypad_4x4.c
 keypad_4x4.h

 Selanjutnya atur inisialisasi


LCD melalui wizard dengan
cara CLICK keypad_4x4.c
Kemudian CLICK
configuration Wizad
 Pada module keypad
terhubung ke GPIOE
 K0-K3 pada bit 8-11
 B0-B3 pada bit 12-15
1. Click

1. Click
86

43
12/17/2016

Review Keypad & LCD

 Stelah menambahkan file


LCD driver :
 lcd_character.c
 lcd_character.h

 Selanjutnya atur inisialisasi


LCD melalui wizard dengan
cara CLICK lcd_character.c
Kemudian CLICK
configuration Wizad
 Pada module LCD
terhubung ke GPIOD
 LDC D4-D7 pada bit 4-7
 LDC RS pada bit 0
1. Click
 LDC RW pada bit 1
 LDC EN pada bit 2
1. Click
87

Program scaning keypad


char keypad_get_key_value(void)
{ char key; HAL_GPIO_WritePin(KEYPAD_PORT,__B2_BIT,GPIO_PIN_RESET);
key=' '; HAL_Delay(10);
if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K0_BIT)==0) key = '7';
HAL_GPIO_WritePin(KEYPAD_PORT,__B0_BIT,GPIO_PIN_RESET); else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K1_BIT)==0) key ='8';
HAL_Delay(10); else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K2_BIT)==0) key ='9';
if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K0_BIT)==0) key = '1'; else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K3_BIT)==0) key ='C';
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K1_BIT)==0) key ='2'; HAL_GPIO_WritePin(KEYPAD_PORT,__B2_BIT,GPIO_PIN_SET);
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K2_BIT)==0) key ='3';
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K3_BIT)==0) key ='A'; HAL_GPIO_WritePin(KEYPAD_PORT,__B3_BIT,GPIO_PIN_RESET);
HAL_GPIO_WritePin(KEYPAD_PORT,__B0_BIT,GPIO_PIN_SET); HAL_Delay(10);
if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K0_BIT)==0) key = '.';
HAL_GPIO_WritePin(KEYPAD_PORT,__B1_BIT,GPIO_PIN_RESET); else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K1_BIT)==0) key ='0';
HAL_Delay(10); else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K2_BIT)==0) key ='#';
if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K0_BIT)==0) key = '4'; else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K3_BIT)==0) key ='D';
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K1_BIT)==0) key ='5'; HAL_GPIO_WritePin(KEYPAD_PORT,__B3_BIT,GPIO_PIN_SET);
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K2_BIT)==0) key ='6';
else if(HAL_GPIO_ReadPin(KEYPAD_PORT,__K3_BIT)==0) key ='B'; return key;
HAL_GPIO_WritePin(KEYPAD_PORT,__B1_BIT,GPIO_PIN_SET);
}

88

44
12/17/2016

Contoh Program <Keypad part1>


/* Includes --------------------- while (1)
--------*/ {

#include "stm32f4xx_hal.h" #define maxdigit 3


static unsigned char index=0;
#include "stdio.h"
static char bufferkey[maxdigit+1];
#include "lcd_character.h"
static short int datakey;
#include "keypad_4x4.h“
#include “stdlib.h“
key_val = keypad_get_key_value();
sprintf(buffer,"Key presed= %c",key_val);
lcd_gotoxy(0,0);
int main(void)
lcd_puts(buffer);
{
char buffer[20]; if(key_val >= '0' && key_val<='9' ) // number for decimal value
char key_val; { if(index < maxdigit)
HAL_Init(); { bufferkey[index] = key_val;
SystemClock_Config(); index++;
/*Initialize all peripherals */ HAL_Delay(200);
MX_GPIO_Init(); }
lcd_init(); }
keypad_init(); else if (key_val =='D') // for delete
lcd_gotoxy(0,0); { if(index > 0)
lcd_puts("Tes Keypad"); { index--;
HAL_Delay(1000); bufferkey[index] = ' ';
89
lcd_clear(); HAL_Delay(200);

Contoh Program <Keypad part2>


else if (key_val =='D') // for delete
{ if(index > 0)
{ index--;
bufferkey[index] = ' ';
HAL_Delay(200);
}
}
else if (key_val =='#') // for enter key
{
datakey = atoi(bufferkey); // convert from string/ascii to integer
datakey = atof(bufferkey); // convert from string/ascii to float
GPIOE->ODR = datakey;
bufferkey[0] = ' ';
bufferkey[1] = ' ';
bufferkey[2] = ' ';
index=0;
HAL_Delay(500);
}
lcd_gotoxy(0,1);lcd_puts("key=");
lcd_puts(bufferkey);
lcd_gotoxy(9,1); sprintf(buffer,"val=%3d",datakey);
lcd_puts(buffer);
} 90
}

45
12/17/2016

SMPS Voltage Mode vs. Current Mode Control

Voltage Mode Control

The major characteristics of this


design are that there is a single
voltage feedback path, with pulse
width modulation performed by
comparing the voltage error signal
with a constant ramp waveform.

Current limiting must be done


separately.

91

SMPS Voltage Mode vs. Current Mode Control


The advantages of voltage-mode control are:
1. A single feedback loop is easier to design and analyze
2. A large-amplitude ramp waveform provides good noise margin for a stable modulation
process.
3. A low-impedance power output provides better cross-regulation for multiple output
supplies.

Voltage-mode’s disadvantages can be listed as:


1. Any change in line or load must first be sensed as an output change and then corrected
by the feedback loop. This usually means slow response.
2. The output filter adds two poles to the control loop requiring either a dominant-pole
low frequency roll-off at the error amplifier or an added zero in the compensation.
3. Compensation is further complicated by the fact that the loop gain varies with input
voltage.
92

46
12/17/2016

SMPS Voltage Mode vs. Current Mode Control

Current Mode Control

The major characteristics of this


design are that there is a single
Current feedback path (the current
value represented with voltage on
R_sense ), with pulse width
modulation performed by comparing
the current error signal with a
constant ramp waveform.

Current limiting must be done


separately.

93

SMPS Voltage Mode vs. Current Mode Control


Consider the use of current-mode if:
1. The power supply output is to be a current source or very high output voltage.
2. The fastest dynamic response is needed with a given switching frequency.
3. The application is for a DC/DC converter where the input voltage variation is relatively constrained.
4. Modular applications where parallel ability with load sharing is required.
5. In push-pull circuits where transformer flux balancing is important.
6. In low-cost applications requiring the absolute fewest components.

Consider voltage-mode (with feed-forward) if:


1. There are wide input line and/or output load variations possible.
2. Particularly with low line - light load conditions where the current ramp slope is too shallow for
stable PWM operation.
3. High power and/or noisy applications where noise on the current waveform would be difficult to
control.
4. Multiple output voltages are needed with relatively good cross-regulation.
5. Saturable reactor controllers are to be used as auxiliary secondary-side regulators.
6. Applications where the complexities of dual feedback loops and/or slope compensation is to be
94
avoided.

47
12/17/2016

Simple SMPS Voltage Mode Control


START
#define DUTY_STEP 5
void voltage_mode(void)
Define
Measure
Vref, V,
I_limit
I { float iin,vin,vref,i_limit;
vref = 7.5; //example reference value
Measure V, I i_limit = 3.5; //example limit current
value
iin=read_current_value();
N vin=read_voltage_value();
I < I_imit

Y if(iin < i_limit)


{ if(vin < vref) duty += DUTY_STEP;
N else duty -= DUTY_STEP;
V < Vref
}
Y
else duty -= DUTY_STEP;
Decrease Increase Decrease
update_duty_cycle(duty);
Duty Cycle Duty Cycle Duty Cycle }
}
END

95

Simple SMPS Current Mode Control


START
#define DUTY_STEP 5
void current_mode(void)
Define
Measure
V_limit,
V, IIref { float iin,vin,iref,v_limit;

Measure V, I
iref = 7.5; //example reference value
v_limit = 3.5; //example limit voltage

N iin=read_current_value();
V < V_imit
vin=read_voltage_value();
Y
if(vin < v_limit)
N
I <Iref { if(iin < iref) duty += DUTY_STEP;
else duty -= DUTY_STEP;
Y
}
Decrease Increase Decrease else duty -= DUTY_STEP;
Duty Cycle Duty Cycle Duty Cycle update_duty_cycle(duty);
}
END }

96

48
12/17/2016

Simple SMPS with Voltage Mode and Current Mode Control

Please design a programmable power


supply and controller system using
STM32F407 microcontroller, with the
following requirement:
• Control mode are select able for voltage
and current
• Set-point voltage can be set via the
keypad, the voltage value with accuracy
0.01
• Set-point voltage can be set via the
keypad, the voltage value with accuracy
0.01
• Rated voltage and current through the
programmable DC power supply block diagram
LCD display with a accuracy 0.01

97

98

49
12/17/2016

Minggu Ke - 5

99

Controlling DC–DC Converters (SMPS) with Microcontroller


(Concept of DC-DC converter for PV MPPT)

100

50
12/17/2016

Overview of Maximum Power Point


Tracking Control Methods for PV Systems
Solar PV modules is a power output is
greatly influenced by environmental
conditions such as solar radiation, wind
speed and direction,
ambient temperature, humidity, and
atmospheric dust.

Using a solar panel or an array of panels


without a controller that can perform
Maximum Power Point Tracking (MPPT)
will often result in wasted power, which
ultimately results in the need to install
more panels for the same power
requirement.
V-I and V-P curves at constant temperature (25°C) and three different insolation101
values.

Block diagram of the MPPT method

102

51
12/17/2016

Controlling SMPS with Microcontroller


Current Sensor
(Concept of DC-DC converter for PV MPPT)

Voltage Sensor

GND
for IGBT/MOSFET
Driver (grounded)

Controller Side

Voltage Use different power supply


measurement for IGBT/MOSFET Driver and
Isolation Amplifier

differential
ampifier
Current
measurement GND for Isolation
Amplifier (grounded)
103

Concept of SMPS for PV MPPT with Microcontroller

Work flow
1. We need define CPU clcok
Clock Init

ADC_Init(); 2. We need Multi channel ADC to read Voltage and Current value

TIMER_Init(); 3. We need to generate PWM signal

lcd_Init(); 4. We need to displaying information such as Voltage and Current value

MPPT control loop 5. MPPT Algorithm process

104

52
12/17/2016

PERTURB AND OBSERVE (P&O) 1

float power,l_power;
#define MPPT_STEP 5
void mppt_PO(void)
{ float iin,vin;
iin=read_current_value();
vin=read_voltage_value();
power = vin * iin;
if(power < l_power) updown ^= 1;
if(!updown) vinref -= MPPT_STEP;
else vinref += MPPT_STEP;
l_power = power;
convert_vref_to_duty();
}
105

PERTURB AND OBSERVE (P&O) 2


float power,l_power;
#define MPPT_STEP 5
void mppt_PO(void)
{ float iin,vin,l_vin;
Calculate P(k) iin=read_current_value();
vin=read_voltage_value();
power = vin * iin;

???
l_power = power;
l_vin = vin;
convert_vref_to_duty();
}
}

106

53
12/17/2016

PERTURB AND OBSERVE (P&O) 2


float power,l_power;
#define MPPT_STEP 5
void mppt_PO(void)
{ float iin,vin,l_vin;
Calculate P(k) iin=read_current_value();
vin=read_voltage_value();
power = vin * iin;
if(power -l_power !=0)
{ if(power - l_power >0)
{if(vin-l_vin>0) vinref += MPPT_STEP;
else vinref -= MPPT_STEP;
}
else
{if(vin-l_vin>0) vinref += MPPT_STEP;
else vinref -= MPPT_STEP;
}
l_power = power;
l_vin = vin;
convert_vref_to_duty();
}
}
107

INCREMENTAL CONDUCTANCE
float power,l_power;
#define MPPT_STEP 5
void mppt_INCCOND(void)
{
float delta_i,delta_v,delta_p;
float f_iin,f_vin;
iin=read_current_value();
vin=read_voltage_value();
power = f_iin * f_vin;
delta_p = power - l_power;
delta_i = f_iin - fl_iin;
delta_v = f_vin - fl_vin;
if(delta_v)
{
ineq = delta_p / delta_v;
if(ineq > 0) vinref += MPPT_STEP;
else if(ineq < 0) vinref -= MPPT_STEP;
}
else
{
if(delta_i > 0) vinref += MPPT_STEP;
else if(delta_i < 0) vinref -= MPPT_STEP;
}
fl_iin = f_iin;
fl_vin = f_vin;
l_power = power;
convert_vref_to_duty();
}
108

54
12/17/2016

COMBINED P & O WITH CV


float power,l_power;
#define MPPT_STEP 5
void mppt_combined_PO_CV(void)
{
float f_iin,f_vin;

???

l_power = power;
convert_vref_to_duty();
}

109

COMBINED dP-P & O


float power,l_power;
#define MPPT_STEP 5
void mppt_combined_PO_CV(void)
{
float f_iin,f_vin;

???

l_power = power;
convert_vref_to_duty();
}

110

55
12/17/2016

TEMPERATURE METHOD
float power,l_power;
#define MPPT_STEP 5
void mppt_combined_PO_CV(void)
{
float f_iin,f_vin;

???

l_power = power;
convert_vref_to_duty();
}

111

A B
Firefly algorithm

A B

112

56
12/17/2016

Grey Wolf Optimization Technique


A B

A B

113
MPPT Application for hybrid Charging

General block diagram for hybrid battery charging system 114

57
12/17/2016

MPPT Application for hybrid Charging

General control system for hybrid battery charging 115


MPPT Application for hybrid Charging

Characteristic of Standalone PV for battery charging


Characteristic of hybrid PV for battery charging
with power sharing algorithm

116

58
12/17/2016

Minggu Ke - 6

117

Controlling DC–AC Converters (Inverter) with Microcontroller

118

59
12/17/2016

Review on Inverter operating principle.


Voltage Source Inverters
Introduction • VSI Topologies •
Modulation Methods

Multilevel Voltage Source


Converters
Introduction • Multilevel Converter
Topologies • Modulation
Techniques for Multilevel Inverters

Current Source Inverters


Introduction • PWM-CSI • PWM-
CSI Modulation Methods

119

Microcontroller for Inverter application

Voltage Source Inverters


120

60
12/17/2016

Microcontroller for Inverter application

PWM ADC

Microcontroller
121

Review on Inverter topology classification according to


type of source (voltage or current) and power range

Inverter operating principle.

122

61
12/17/2016

Review on H-Bridge VSI

Single-Phase VSI

Three-Phase VSI
123

Setting Dead-Time
• The inverter control circuit
provides output to drive its
load by switching IGBT1
(Upper Arm) and IGBT2
(Lower Arm) alternately on
and off .
• If the dead-time is
insufficient, IGBT1 and
IGBT2 could both switch on,
causing a short-circuit Normal Operation of the Short Circuit of the Inverter
current and breakdown Inverter Control Circuit Control Circuit
of the IGBTs

124

62
12/17/2016

Setting Dead-Time

• Dead-time, TDEAD, should be Driver


set so that IGBT1 and IGBT2
are not on at the same time.
• A value greater than the Driver
difference between the
maximum total turn-off
time (tOFF Total max) and the
minimum total turn-on time
(tON Total min)

125

Conventional technique of sinusoidal generation

126

63
12/17/2016

Conventional technique of sinusoidal generation

127

Mathematical model of sinusoidal generation

To generate sinusoidal wave as modulating signal using mathematical


model Vref=A sin (2πft +ɸ) + offset, where A is reference of desired
amplitude signal, f is desiredsignal frequency and ɸ is phase shift angle.
The rule for single phase and three phase signal is described on table

128

64
12/17/2016

Review on Modulation Methods


(Square-Wave Operation)

129

Modulation Methods (Square-Wave Operation)


Reference signal generation
//#define phi 3.141592653589
const float phi= 3.141592653589;
float Va, Vb, Vc, f, t, dt;
Va = A * sin (2*phi*f*t)
Vb = A * sin ((2*phi*f*t) + (2*phi/3))
Vc = A * sin ((2*phi*f*t) + (4*phi/3)))

PWM signal generation


if(Va > 0) PWM_a =1;
else PWM_a =0;
if(Vb > 0) PWM_b =1;
else PWM_b =0;
if(Vc > 0) PWM_c =1;
else PWM_c =0; 130

65
12/17/2016

Review on Modulation Methods


Sinusoidal PWM: Bipolar PWM (single Phase)
PWM signal generation

131

Modulation Methods (Sinusoidal PWM: Bipolar PWM (single Phase))


Reference signal generation
//#define phi 3.141592653589
const float phi= 3.141592653589;
float Vr,f, t, dt;
Vr = A * sin (2*phi*f*t)

PWM signal generation

PWM signal generation


if(Vr > Vc)
{ PWM_S11 =1; PWM_S12 =0;}
else
{ PWM_S11 =0; PWM_S12 =1;}

132

66
12/17/2016

Review on Modulation Methods


Sinusoidal PWM: Unipolar PWM (single Phase) (1)

PWM signal generation

133

Modulation Methods (Sinusoidal PWM: Unipolar PWM (single Phase))


Reference signal generation PWM signal generation
const float phi= 3.141592653589;
float Va,Vb,f, t, dt; if(Va > Vc)
Va = A * sin (2*phi*f*t) { PWM_S11 =1; PWM_S22 =0;}
Vb = Va * -1; else
{ PWM_S11 =0; PWM_S22 =1;}

if(Vb > Vc)


PWM signal generation { PWM_S12 =1; PWM_S21 =0;}
else
{ PWM_S12 =0; PWM_S21 =1;}

134

67
12/17/2016

Review on Modulation Methods


Sinusoidal PWM: Unipolar PWM (single Phase) (2)
PWM signal generation

135

Review on Modulation Methods


Sinusoidal PWM(single Phase)

Bipolar PWM Unipolar PWM

136

68
12/17/2016

Review on Modulation Methods


Sinusoidal PWM: Bipolar PWM (Three Phase)

Vc

137

Modulation Methods (Sinusoidal PWM: Bipolar PWM (Three Phase))


Reference signal generation
const float phi= 3.141592653589;
float Vr, Vs, Vt, f, t, dt;
Vr = A * sin (2*phi*f*t)
Vs = A * sin ((2*phi*f*t) + (2*phi/3))
Vt = A * sin ((2*phi*f*t) + (4*phi/3)))
PWM signal generation
if(Vr > Vc) PWM_a =1;
else PWM_a =0;
if(Vs > Vc) PWM_b =1;
else PWM_b =0;
if(Vt > Vc) PWM_c =1;
Vc else PWM_c =0; 138

69
12/17/2016

Implementation block diagram for PWM

(a) half-bridge bipolar PWM, (b) H-bridge unipolar PWM, and (c) three-phase VSI bipolar PWM.
139

Influence of the carrier signal over synchronous current sampling

(a) triangular carrier PWM and (b) sawtooth carrier PWM (right weighted). 140

70
12/17/2016

Over-modulation concept in a VSI.


Over modulation occur when
Va (reference) signal peak
value greater than maximum
Vcr (carrier).

modulation index (Ma) can be


calculated as Va/Vcr

modulation ratio (Mf) can be


calculated as fc/ fr where fc is
carrier frequency and fr is
reference frequency
141
SPWM Waveform on Oscilloscope

142

71
12/17/2016

TIMER Configuration For Driving Inverter

143

TIMER Configuration For Driving Inverter

144

72
12/17/2016

Minggu Ke - 7

145

Controlling DC–AC Converters (Inverter) with Microcontroller


(Scalar Control)

146

73
12/17/2016

Classification of IM control methods

147
NFO is the natural field orientation

Review on modulation concept in a VSI.


Over modulation occur when
Va (reference) signal peak
value greater than maximum
Vcr (carrier).

modulation index (Ma) can be


calculated as Va/Vcr

modulation ratio (Mf) can be


calculated as fc/ fr where fc is
carrier frequency and fr is
reference frequency
148

74
12/17/2016

Scalar Control with V/f constant


• The scalar based controller with V/f constant are the way to maintain
voltage reference and frequency at constant ratio. when frequency
going slower the voltage reference should be in lower value, if
frequency going faster the voltage reference should be in higher value

= t è = ∗ t

Example
10
= 0.2
50

= 0.2
149

Speed
Scalar Control with V/f constant

2000

1500

1000

500

-500

Isa Isb Isc

300

200

100

-100

-200

-300

Vfset Vr

50

40

30

20

10

0 2 4 6 8 10 12 14
Time (s)
150

75
12/17/2016

Speed

2000
added with acceleration and deceleration time

1500

1000

500
Scalar Control with V/f constant

-500

Isa Isb Isc

150

100

50

-50

-100

-150

Vfset Vr

50

40
30

20

10
0

-10

0 2 4 6 8 10 12 14
Time (s) 151

Speed

2000

1500
added with acceleration and deceleration time

1000

500

-500
Scalar Control with V/f constant

Without Speed Isb


Isa Isc
ACC & 2000
300
DEC 1500
200

100
1000
0
500
-100
0
-200
-500
-300
With
Isa Isb Isc
ACC & 150
DEC 100

50

-50

-100

Significant -150

reduce Vfset Vr

starting 50

current 40

30

20

10

-10
152
0 2 4 6 8 10 12 14
Time (s)

76
12/17/2016

arm-fast-math for fast computation

Digitally, to generate SPWM signal,


triangle wave as a carrier signal is
compared with the sinusoidal wave in
specific time period. This technique is
called regular sampling. The result of
implementation proposed method on
STM32F407 ARM Cortex-M
microcontroller at168MHz operating
speed for method A (standard math
library) and method B (arm-fast-math
library) can be seen on table 2 below.

153
arm-fast-math for fast computation

154

77
12/17/2016

arm-fast-math for fast computation

155
arm-fast-math for fast computation

standard math library è #include “math.h”

vr=a*sin((float)2*phi*f * t )+ ofset;
vs=a*sin(((float)2*phi*f * t) +(2*phi/3)) + ofset;
vt=a*sin(((float)2*phi*f * t) -(2*phi/3)) + ofset;

arm-fast-math library è #include "arm_math.h"


vr=a*arm_sin_f32((float)2*phi*f * t )+ ofset;
vs=a*arm_sin_f32(((float)2*phi*f * t) +(2*phi/3))+ofset;
vt=a*arm_sin_f32(((float)2*phi*f * t) -(2*phi/3))+ofset;

156

78
12/17/2016

arm-fast-math for fast computation


Sinusoidal reference

Third Harmonics Injection (THI)


Sinusoidal reference

Vr =a*arm_sin_f32((float)2*phi*f * t )+ ofset;

Vr =a*arm_sin_f32((float)2*phi*f
+(a/6)*arm_sin_f32((float)6*phi*f * t)
+ ofset; 157

158

79
12/17/2016

Minggu Ke - 8

159

Digital Firing Angle Control of Thyristor with Microcontroller

160

80
12/17/2016

Review Firing Angle Control of Thyristor

Thyristor circuits are normally preferred in


applications where controlled power is a necessity.
The three terminal thyristor has a terminal gate,
along with anode and cathode, which shall be
employed to trigger a thyristor at a particular
angle, known as firing
mechanism.
It has been established that in analog triggering
circuit, trigger circuit may consist of too many
components, which may lead to debugging issues,
as well, uneven spacing of the adjacent trigger
pulses and shifting phase in accuracies may pose
difficulties, there in. Hence digital trigger
mechanism is designed, which overcomes the
limitations of analog trigger circuit.
In this schematic, digital trigger mechanism has
been used for the control of output power.

161

Review Firing Angle Control of Thyristor

162

81
12/17/2016

Digital Firing Angle Control of Thyristor with Microcontroller

163

Digital Firing Angle Control of Thyristor with Microcontroller


Zero crossing /
Synchronizer

AC Source
Microcontroller

AC Source

164
SCR/TRIAC driver

82
12/17/2016

Digital Firing Angle Control of Thyristor with Microcontroller

Zero Crossing Detector /


Synchronizer

MCU

165

Digital Firing Angle Control of Thyristor with Microcontroller

Zero Crossing Detector /


Syncronizer

166

83
12/17/2016

Digital Firing Angle Control of Thyristor with Microcontroller

SCR / TRIAC Driver

167

Digital Firing Angle Control of Thyristor with Microcontroller

SCR / TRIAC Driver

168

84
12/17/2016

Digital Firing Angle Control of Thyristor with Microcontroller

169

Digital Firing Angle Control of Thyristor with Microcontroller

170

85
12/17/2016

Application Of Thyristor for Heater Load

171

SELECTING THE CORRECT CONTROLLER FOR


HEATING ELEMENT TYPES
Heating elements can be broadly divided into three categories:
 CLASS A
These elements have negligible resistance variation with either temperature or time. Examples include:
Nickel/Chromium or similar alloys.
 CLASS B
These elements have a low cold temperature resistance that increases greatly at operating temperature.
Examples include: Molybdenum Disilicide, Platinum and Molybdenum Tungsten Class B elements usually
require current limit on start up, as their low cold resistance results in high currents at the operating supply
voltage.These elements may also require a stepdown transformer to match the supply voltage to the rated
element voltage. Because current limit is required,and the element voltage ratings are less than line
voltage,phase angle control is the recommended firing mode.
 CLASS C
The resistance of these elements increases greatly with time in use (typically 2 to 4 times) and with
temperature.Silicon carbide is a common example .The power controller must be sized so that it can deliver
the higher currents required to maintain the desired power when the elements are new. If the elements are
sized correctly the use of a stepdown transformer may be avoided. The power limit (PW) option is
recommended for this class of element as it compensates for element ageing and limits the
maximum load power. Phase angle (F300 series controllers) is the recommended firing mode. 172

86
12/17/2016

CONTROLLER SELECTION AND ELEMENT TYPE

173

VOLTAGE WAVEFORMS FOR ON/ OFF AND


PHASE ANGLE CONTROL

174

87
12/17/2016

Minggu Ke - 9

175

UART Serial Communication (Pooling method)

176

88
12/17/2016

Simple UART communication


• Objective
• Learn how to setup UART in Cube MX
• How to generate project in Cube MX and use HAL functions
• Work in pairs, one will create transmitter and second receiver
• Goal
• Configure UART in Cube MX and generate project
• Learn how to send and receive data over UART without
interrupts
• Verify the correct functionality

177

Simple UART communication


• Create project in Cube MX
• Menu > File > New Project
• Select STM32F4 > STM32F429/439 > LQFP144 > STM32F439ZITx

• Pin selection
• We are looking for free pins where is possible to create wire loopback connection

178

89
12/17/2016

Simple UART communication


• Pin selection
• We are looking for free pins
where is possible to create
wire loopback connection

Image from STM32F429-


Discovery user manual

179

Simple UART communication


• Pin selection
• We are looking for free pins where is possible to create wire loopback connection

Image from
STM32F429
datasheet

180

90
12/17/2016

Simple UART communication


• Hardware preparation
• We connect selected pins together by jumper, this help us to create loopback on UART

Hardware
connection
RX <-TX
TX->RX

181

Simple UART communication


• Create project in Cube MX
• Menu > File > New Project
• Select STM32F4 > STM32F429/439 > LQFP144 > STM32F439ZITx

• CubeMX UART selection


• Select USART1 in asynchronous mode
• Select PA9 and PA10 for USART1 if weren't selected

182

91
12/17/2016

Simple UART communication


• In order to make HAL_Delay and UART to work correctly we need to setup clock
system
• Details in lab 0

183

Simple UART communication


• CubeMX UART configuration
• Tab->Configuration->Connectivity->USART1

184

92
12/17/2016

Simple UART communication


• CubeMX USART configuration check:
• BaudRate
• World length
• Parity
• Stop bits
• Data direction
• Oversampling

185

Simple UART communication


• Now we set the project details for generation
• Menu > Project > Project Settings
• Set the project name
• Project location
• Type of toolchain

• Now we can generate project


• Menu > Project > Generate Project

186

93
12/17/2016

Simple UART communication


HAL Library init flow

Peripheral Initializations
Cube MX UART init start in
main.c file
MX_USART1_UART_Init();

Init UART1 structure

HAL_UART_Init(&huart1);

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

187

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

MX_USART1_UART_Init();

Init UART1 structure

HAL_UART_Init(&huart1);

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

188

94
12/17/2016

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

MX_USART1_UART_Init();
Cube MX create for us
function which handle UART
Init UART1 structure initialization

HAL_UART_Init(&huart1);

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

189

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure

HAL_UART_Init(&huart1);

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

190

95
12/17/2016

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure Cube MX fill the UART


structure with parameters
which we choose in
HAL_UART_Init(&huart1);
Configuration window

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

191

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1);

HAL_UART_MspInit callback

Init GPIO and NVIC for UART

192

96
12/17/2016

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1);
Function wrote parameters
from structure into UART1
HAL_UART_MspInit callback registers

Init GPIO and NVIC for UART

193

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1); 4. Write to UART1 registers

HAL_UART_MspInit callback Optional callback from


HAL_UART_Init function, be
default empty weak
Init GPIO and NVIC for UART
function

194

97
12/17/2016

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1); 4. Write to UART1 registers

HAL_UART_MspInit callback CubeMX configure here


UART1 GPIOs and enable
Init GPIO and NVIC for UART UART1 clock system

195

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1); 4. Write to UART1 registers

HAL_UART_MspInit callback 5. UART1 init callback

Init GPIO and NVIC for UART CubeMX configure here


UART1 GPIOs and enable
UART1 clock system and
NVIC
196

98
12/17/2016

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1); 4. Write to UART1 registers

HAL_UART_MspInit callback 5. UART1 init callback

Init GPIO and NVIC for UART 6. UART1 GPIOS, NVIC and RCC init

197

Simple UART communication


HAL Library init flow
1. We need init
Peripheral Initializations UART1

2. Call UART1 init


MX_USART1_UART_Init(); function

Init UART1 structure 3. Store UART1 configuration into


structure

HAL_UART_Init(&huart1); 4. Write to UART1 registers

HAL_UART_MspInit callback 5. UART1 init callback

Init GPIO and NVIC for UART 6. UART1 GPIOS, NVIC and RCC init

7. Next periph init or user code


198

99
12/17/2016

Simple UART communication


HAL Library transmit flow

Peripheral Initializations Generated by


CubeMX
Polling process Function blocks
HAL_UART_Transmit Polling with timeout

HAL_TIMEOUT HAL_OK HAL_ERROR HAL_BUSY

199

Simple UART communication


HAL Library transmit flow

Created by user
Peripheral Initializations

Polling process Function blocks


HAL_UART_Transmit Polling with timeout

HAL_TIMEOUT HAL_OK HAL_ERROR HAL_BUSY

200

100
12/17/2016

Simple UART communication


HAL Library receive flow

Peripheral Initializations Generated by


CubeMX
Polling process Function blocks
HAL_UART_Receive Polling with timeout

HAL_TIMEOUT HAL_OK HAL_ERROR HAL_BUSY

201

Simple UART communication


HAL Library receive flow

Created by user
Peripheral Initializations

Polling process Function blocks


HAL_UART_Receive Polling with timeout

HAL_TIMEOUT HAL_OK HAL_ERROR HAL_BUSY

202

101
12/17/2016

Simple UART communication


• Open the project in our IDE
• The functions we want to put into main.c
• Between /* USER CODE BEGIN 3 */ and /* USER CODE END 3 */ tags
• Into infinite while function
• For transmit use function
• HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)

• For receive use function


• HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout);

203

Simple UART communication


• Transmit solution
• Create data structure for data
/* USER CODE BEGIN 0 */
uint8_t
data[]={0,1,2,3,4,5,6,7,8,9};
/* USER CODE END 0 */

/* USERfunction
• Call transmit CODE BEGIN
from3 while
*/ loop
/* Infinite loop */
while (1)
{

HAL_UART_Transmit(&huart1,data,10,
1000);
}
/* USER CODE END 3 */
204

102
12/17/2016

Simple UART communication


• Receive solution
• Create data structure for data
/* USER CODE BEGIN 0 */
uint8_t data[10];
/* USER CODE END 0 */

/* USER CODE BEGIN 3 */


• Call/*transmit
Infinitefunction
loop */from while loop
while (1)
{
HAL_UART_Receive(&huart1,data,10,1000);
}
/* USER CODE END 3 */

205

206

103
12/17/2016

Minggu Ke - 10

207

UART Interrupt

208

104
12/17/2016

Use UART with interrupt


• Objective
• Learn how to setup UART with interrupts in Cube MX
• How to generate project in Cube MX and use HAL functions
• Create simple loopback example with interrupts
• Goal
• Configure UART in Cube MX and generate project
• Learn how to send and receive data over UART with interrupts
• Verify the correct functionality

209

Use UART with interrupt


• Create project in Cube MX
• Menu > File > New Project
• Select STM32F4 > STM32F429/439 > LQFP144 > STM32F439ZITx

• Pin selection
• It will be same as previous lab we use again PA9 and PA10

210

105
12/17/2016

Use UART with interrupt


• Hardware preparation
• We connect selected pins together by jumper, this help us to create loopback on UART

Hardware
loopback

211

Use UART with interrupt


• In order to make HAL_Delay and UART to work correctly we need to setup clock
system
• Details in lab 0

212

106
12/17/2016

Use UART with interrupt


• CubeMX UART configuration
• Tab->Configuration->Connectivity->USART1

213

Use UART with interrupt


• CubeMX UART configuration check:
• BaudRate
• World length
• Parity
• Stop bits
• Data direction
• Oversampling

214

107
12/17/2016

Use UART with interrupt


• CubeMX USART configuration NVIC settings
• TAB->NVIC Settings
• Enable interrupts
• OK

215

Use UART with interrupt


• Now we set the project details for generation
• Menu > Project > Project Settings
• Set the project name
• Project location
• Type of toolchain

• Now we can generate project


• Menu > Project > Generate Project

216

108
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Receive_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

217

Use UART with interrupt


HAL Library UART with IT transmit flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

218

109
12/17/2016

Use UART with interrupt


HAL Library UART with IT transmit flow
Peripheral Initializations
including peripheral interrupt NVIC initializations
Generated by Cube MX

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

219

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback Defined by user


HAL_UART_ErrorCallback

220

110
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations Generated in main.c and
stm32f4xx_hal_msp.c
Start process with interrupt generation at end of
process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

221

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback
We recommend to use it in
main.c
process Error callback
HAL_UART_ErrorCallback

222

111
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

Defined as __weak you can find


process Error callback name of this functions in
HAL_UART_ErrorCallback stm32f4xx_hal_uart.c

223

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

Generated in stm32f4xx_it.c

process Error callback


HAL_UART_ErrorCallback

224

112
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback
Defined in
stm32f4xx_hal_uart.c
process Error callback
HAL_UART_ErrorCallback

225

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations Send buffer over UART
Not blocking function
Start process with interrupt generation at end of
program can continue
process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

226

113
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Interrupt indicate the data
Peripheral Initializations register is empty we can
including peripheral interrupt NVIC initializations send more data or error was
detected
Start process with interrupt generation at end of
process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

227

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Process interrupt
Start process with interrupt generation at end of information
process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

228

114
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations
Send more data if is buffer
Start process with interrupt generation at end of
not empty
process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback

process Error callback


HAL_UART_ErrorCallback

229

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback If data buffer is empty use
Complete callback function

process Error callback


HAL_UART_ErrorCallback

230

115
12/17/2016

Use UART with interrupt


HAL Library UART with IT receive flow
Peripheral Initializations
including peripheral interrupt NVIC initializations

Start process with interrupt generation at end of


process
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

end of process callback


HAL_UART_TxCpltCallback Or if error was detected use
Error callback function

process Error callback


HAL_UART_ErrorCallback

231

Use UART with interrupt


HAL Library UART with IT receive flow
1. UART1 init
Peripheral Initializations
including peripheral interrupt NVIC initializations

2. UART1 send
Start process with interrupt generation at end of
process
buffer
HAL_UART_Transmit_IT

HAL_OK HAL_ERROR HAL_BUSY HAL_UART_IRQHandler USART1_IRQHandler

3. UART1 Tx
4. Send more data
register empty
end of process callback 5. Buffer sent or manage error
HAL_UART_TxCpltCallback

process Error callback 5. Transmit error


HAL_UART_ErrorCallback

232

116
12/17/2016

Use UART with interrupt


• Open the project in our IDE
• The functions we want to put into main.c
• Between /* USER CODE BEGIN 2 */ and /* USER CODE END 2 */ tags
• For transmit use function
• HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size);

• For receive use function


• HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size);

233

Use UART with interrupt


• Buffer definition
/* USER CODE BEGIN 0 */
uint8_t tx_buff[]={0,1,2,3,4,5,6,7,8,9};
uint8_t rx_buff[10];
/* USER CODE END 0 */

• Sending and receiving methods


/* USER CODE BEGIN 2 */
HAL_UART_Receive_IT(&huart1,rx_buff,10);
HAL_UART_Transmit_IT(&huart1,tx_buff,10);
/* USER CODE END 2 */

234

117
12/17/2016

Use UART with interrupt


• Complete callback check
• We can put brakepoints on NOPs to watch if we send or
receive complete buffer
/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
__NOP();//test if we reach this position
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)


{
__NOP();//test if we reach this position
}
/* USER CODE END 4 */

235

Use UART with interrupt


• !!!!!!!! F4 cube 1.3.0 error in TX and RX. If we use
loopback mode with interrupt will not work correctly

/* USER CODE BEGIN 4 */


void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
__NOP();//test if we reach this position
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)


{
__NOP();//test if we reach this position
}
/* USER CODE END 4 */

236

118
12/17/2016

Minggu Ke - 11

237

UART DMA

238

119
12/17/2016

Use UART with DMA transfer


• Objective
• Learn how to setup UART with DMA in Cube MX
• How to generate project in Cube MX and use HAL functions
• Create simple loopback example with DMA
• Goal
• Configure UART in Cube MX and generate project
• Learn how to send and receive data over UART with DMA
• Verify the correct functionality

239

Use UART with DMA transfer


• Create project in Cube MX
• Menu > File > New Project
• Select STM32F4 > STM32F429/439 > LQFP144 > STM32F439ZITx

• Pin selection
• It will be same as previous lab we use again PA9 and PA10

240

120
12/17/2016

Use UART with DMA transfer


• Hardware preparation
• We connect selected pins together by jumper, this help us to create loopback on UART

Hardware
loopback

241

Use UART with DMA transfer


• In order to make HAL_Delay and UART to work correctly we need to setup clock
system
• Details in lab 0

242

121
12/17/2016

Use UART with DMA transfer


• CubeMX UART configuration
• Tab->Configuration->Connectivity->USART1

243

Use UART with DMA transfer


• CubeMX USART configuration check:
• BaudRate
• World length
• Parity
• Stop bits
• Data direction
• Oversampling

244

122
12/17/2016

Use UART with DMA transfer


• CubeMX USART configuration DMA settings
• TAB->DMA Settings
• Button ADD

245

Use UART with DMA transfer


• CubeMX USART configuration DMA Tx settings
• Set USART1_TX request
• Memory to peripheral direction
• Normal mode
• Byte data width
• Increment memory address

246

123
12/17/2016

Use UART with DMA transfer


• CubeMX USART configuration DMA Rx settings
• Button ADD
• Set USART1_RX request
• Peripheral to memory direction
• Normal mode
• Byte data width
• Increment memory address

247

Use UART with DMA transfer


• CubeMX USART configuration NVIC settings
• TAB->NVIC Settings
• Enable DMA2 interrupts for
USART1
• Button OK

248

124
12/17/2016

Use UART with DMA transfer


• Now we set the project details for generation
• Menu > Project > Project Settings
• Set the project name
• Project location
• Type of toolchain

• Now we can generate project


• Menu > Project > Generate Project

249

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

250

125
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations Generated by Cube MX

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

251

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

Defined by user
process Error callback
HAL_UART_ErrorCallback

252

126
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations
Generated in main.c and
stm32f4xx_hal_msp.c
Start process with DMA end of transfer
interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

253

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback We recommend to use it in
main.c

process Error callback


HAL_UART_ErrorCallback

254

127
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

Generated in stm32f4xx_it.c

process Error callback


HAL_UART_ErrorCallback

255

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback
Defined in stm32f4xx_hal_dma.c
and then linked to
process Error callback stm32f4xx_hal_uart.c
HAL_UART_ErrorCallback

256

128
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations
Receive buffer over UART
with DMA
Not blocking function
Start process with DMA end of transfer program can continue
interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

257

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations Interrupt indicate the DMA
receive half/complete buffer
or DMA error was detected
Start process with DMA end of transfer
interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

258

129
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Process interrupt
Start process with DMA end of transfer information from DMA and
interrupt generation at end of process UART
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback

process Error callback


HAL_UART_ErrorCallback

259

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback
If data buffer is full HAL use
Complete callback function

process Error callback


HAL_UART_ErrorCallback

260

130
12/17/2016

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations
including DMA stream initializations

Start process with DMA end of transfer


interrupt generation at end of process
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

end of process callback


HAL_UART_RxCpltCallback Or if DMA error was
detected use Error callback
function
process Error callback
HAL_UART_ErrorCallback

261

Use UART with DMA transfer


HAL Library UART with DMA RX flow
Peripheral Initializations 1. UART1 and
including DMA stream initializations DMA2 init

Start process with DMA end of transfer 2. UART1 receive


interrupt generation at end of process buffer
HAL_UART_Receive_DMA

HAL_OK HAL_ERROR HAL_ERROR


DMA_Strream_IRQHa
HAL_DMA_IRQHandler
ndler

4. Process 3. DMA buffer full


end of process callback 5. Buffer received interrupt
HAL_UART_RxCpltCallback

process Error callback 5. Receive error


HAL_UART_ErrorCallback

262

131
12/17/2016

Use UART with DMA transfer


• Open the project in our IDE
• The functions we want to put into main.c
• Between /* USER CODE BEGIN 2 */ and /* USER CODE END 2 */ tags
• For transmit use function
• HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size);

• For receive use function


• HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size);

263

Use UART with DMA transfer


• Buffer definition
/* USER CODE BEGIN 0 */
uint8_t tx_buff[]={0,1,2,3,4,5,6,7,8,9};
uint8_t rx_buff[10];
/* USER CODE END 0 */

• Sending and receiving methods with DMA


/* USER CODE BEGIN 2 */
HAL_UART_Receive_DMA(&huart1,rx_buff,10);
HAL_UART_Transmit_DMA(&huart1,tx_buff,10);
/* USER CODE END 2 */

264

132
12/17/2016

Use UART with DMA transfer


• Complete callback check
• We can put breakpoints on NOPs to watch if we receive
complete buffer
/* USER CODE BEGIN 4 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
__NOP();//check if we receive all data
}
/* USER CODE END 4 */

265

266

133
12/17/2016

Minggu Ke - 12

267

Programming Microcontroller with Matlab


(Simulink & Waijung Blockset)

268

134
12/17/2016

Waijung Blockset
"Waijung" or "ไวจัง", a Thai slang for "so fast", is a Simulink Blockset that can be used to
easily and automatically generate C code from your Matlab/Simulink simulation models
for many kinds of microcontrollers (Targets).

Currently, Waijung has been designed specifically to support STM32F4 family of


microcontrollers (STM32F4 Target) which is a Hi-Performance & DSP MCU from
STMicroelectronics.

Waijung Blockset and STM32F4 Target has been completely redesigned with many new
features and improvements, based on our experiences on developing RapidSTM32
Blockset and "real-world applications with ease of use" philosophy.
.

269

270

135
12/17/2016

Waijung Execution Time Profiler


Easily measure execution time of your target in real-time with ease.
Flexibly define an unlimited number of time capture-point pairs, Waijung Profiler analyzes and
reports information such as time steps, elapse time, and histogram for you.

271

Waijung Blockset

272

136
12/17/2016

Waijung Blockset
Simple and Highly Flexible Target Setup

273

GPIO as INPUT PIN & OUPUT PIN

137
12/17/2016

GPIO for INPUT PIN And OUPUT PIN


• Objective
• Learn how to setup GPIO port in Simulink library for Digital
Input
• Learn how to setup GPIO port in Simulink library for Digital
Output
• Learn logic and bit operations

275

Configure GPIO as INPUT PIN And OUPUT


PIN

276

138
12/17/2016

Configure GPIO for INPUT PIN


Each pin of STM32F4 can be characterized as one of the three types i.e.
• Pull-Up,
• Pull-Down and
• Floating (In addition, some pins are particularly 5V Tolerance. Users need
to refer to the datasheet of specific MCU to see if it is 5V tolerance).

277

Configure GPIO for INPUT PIN (Pull-Up)


This figure shows a pull-up input which is basically is a pull-up resistor
connected to VDD or power supply.
Pull-up circuit serves the purpose of reading the status automatically in the
microcontroller. If pull-down is disconnected then the state is HIGH i.e. “1” all
time and if it is connected then the state is LOW i.e. “0” (Active Low). When the
switch is pressed then MCU pin goes LOW. Circuit pull-up is better as compared
to circuit pull-down as former is more robust to noise.

278

139
12/17/2016

Configure GPIO for INPUT PIN (Pull-Down)


This figure shows the condition when the pull-up resistor is disconnected from
VDD and pull-down resistor is connected to the ground while reading the
automatic status from MCU. For the given condition, the circuit will read LOW
i.e. “0” all the times and when the switch is pressed it will start reading HIGH
“1”.

279

Configure GPIO for INPUT PIN (Floating)


Setting pin value to floating has the same idea as pull-up / pull –
down but no internal pull-up and pull-down resisters is required.
User must connect the pull-up or pull-down externally so it is
suitable for some device that already has external Pull-Up or Pull-
Down.

280

140
12/17/2016

Configure GPIO for INPUT PIN


The output of STM32F4 are of two types i.e.
• Push-Pull or
• Open-Drain.
User can choice either of them.

281

Configure GPIO for OUTPUT PIN (Push-Pull)


STM32F4 can be set as a Push-Pull output. Internal circuit of
microcontroller has two types of MOSFET: the P-MOS that connected
between VDD and output pin for transferring current (Source Current) and
N-MOS that is connected between output and ground for receiving
current (Sink Current). The automatic connection control can described
below:
• When needing output status HIGH/“1” system will open P-MOS and close N-MOS,
then the output will have voltage = VDD/“HIGH” state.
• When needing output status LOW/“0” system will open N-MOS and close P-MOS,
then the output will have voltage = Ground/“LOW” state.
The advantage of Push-Pull output is that it can quickly change its state, so
it is suitable for such a situation which requires high frequency switching
and it can directly transfer current to device.
The disadvantage of this type is the limitation of current source/sink. User
must study pin’s maximum current and voltage values from datasheet of
each microcontroller.
282

141
12/17/2016

Configure GPIO for OUTPUT PIN (Push-Pull)

283

Configure for OUTPUT PIN ( )


• These information are very important to prevent device from damage and to improve the
system reliability. For example, each pin of STM32F4 can sink/source maximum current at 25
mA except PC13 – PC15 can sink at 3 mA [1, p.77] and can sink/source maximum of all pins
not more than 150mA as shown in Fig 2-7. Thus when bias the LED with Push-Pull I/O
(assume that VDD = 3.3 V) we can use R = 660 Ohm (from R = V/I = 3.3/5m = 660) to limit
current at 5mA that enough to make the LED bright and not exceed the 25mA maximum
value.

284

142
12/17/2016

Configure GPIO for OUTPUT PIN (Open-Drain)


When setting the output of STM32F4 to Open-Drain, internal circuit in each pin
of microcontroller will be controlled automatically as below:
• Output register will close P-MOS in any state
• If output state LOW or “0” is needed, system will open N-MOS, then output pin will has
same voltage as ground.
• If output state High or “1” is needed the system will close N-MOS then output will be High
Impedance state.

Since the Open-Drain circuit doesn’t


use power from microcontroller, it
can be advantageous because devices
are using external power which can
have a voltage might be higher than
VDD. However user must be careful
about maximum current must not
exceed 25mA.
285

286

143
12/17/2016

MCU will generate output from logic pins


based on the following logic.
if (input port == 1)
Output Logic 1
else
Output Logic 0
end

287

MCU will generate output from logic pins


based on the following logic.
if (input port == 1)
Output Logic 1
else
Output Logic 0
end

288

144
12/17/2016

Digital I/O Experiment 1


Block name Library

Target setup Waijung blockset /STM32F4 Target /


Device configuration
Digital Input Waijung blockset /STM32F4 Target /
on-chip peripheral /IO
Digital Output Waijung blockset /STM32F4 Target /
on-chip peripheral /IO

Generate simple IO for :


if (input port == 1)
Output Logic 1
else
Output Logic 0
end
289

Digital I/O Experiment 1

290

145
12/17/2016

Digital I/O Experiment 2


Bit Logic Operations

Block Library
name
Target Waijung blockset /STM32F4
setup Target / Device configuration
Digital
Input Waijung blockset /STM32F4
Target / on-chip peripheral
Digital /IO
Output
AND

OR Simulink / Logic and Bit


Operation
NOT

291

Digital I/O Experiment 3


Block name Library

Waijung blockset /STM32F4


Target setup Target / Device
configuration
Digital Input Waijung blockset /STM32F4
Digital Target / on-chip peripheral
Output /IO

AND
Simulink / Logic and Bit
OR
Operation
NOT

S-R Flip-Flop Simulink Extras / Flip-Flop

292

146
12/17/2016

Digital I/O Experiment 4


Purpose
• Enable the users to simulate the real enviornment before they actual implement.
• Enable the users to control the switching of LED by using Pulse Generator block
which determines the switching speed

293

Digital I/O Experiment 4


Block name Library In setting parameters of Pulse Generator Block there is an important
Waijung blockset
parameter called Period or the period of waveform.
Target setup /STM32F4 Target / Device Pulse width gives the information that for how long the LED will be
configuration in ON state and for how long it will be in OFF state for a given time.
Waijung blockset
Digital
/STM32F4 Target / on- For example, user wants to switch on the LED for 1 sec and switch
Output
chip peripheral /IO
off the LED for 3 sec and this process keeps on going. For the given
Pulse
Simulink / Source
case, the pulse width can be calculated by using relation below.
Generator

Simulink / Sink
% Pulse Width = (Time for which LED is ON) x 100 / Period
Scope Here Period corresponds to switch ON + switch OFF time i.e. 1 + 3 =
4 sec. So the answer is:
= (1) x 100 / 4 = 25 %

294

147
12/17/2016

Digital I/O Experiment 5

Block Library
name
Target Waijung blockset /STM32F4
setup Target / Device configuration
Digital
Input Waijung blockset /STM32F4
Target / on-chip peripheral
Digital /IO
Output
AND
Simulink / Logic and Bit
OR
Operation
NOT
Simulink / Commonly used
Delay
library

295

BOUNCING/DE-BOUNCING
• Bouncing is the non-ideal behavior of mechanical switches which creates multiple electric transitions
when a single input from the user is entered. It takes some time for the input to reach at a stable state.
• The bouncing effect is illustrated on figure below. From the figure, we can see that in the beginning the
switch is in ON state. When user enter the input to switch it OFF, then it takes around 0.01 to 100 msec
before the switch is actually switched OFF. A similar effect can be observed when the switch goes from
OFF state to ON state.

296

148
12/17/2016

BOUNCING/DE-BOUNCING
Bouncing is an undesirable effect so it must be removed when designing a
circuit. There are number of ways by which we can avoid bouncing. The process
of avioding bouncing is called de-bouncing. The most easy and commonly used
technique for debouncing is analog filtering. A resistor capacitor (RC) circuit is
used to filterout the rapid changes in the switch output. Depending on the
nature of the switch, the values of RC circuit is chosen in such a way that input
threshold is not crossed while bouncing is still occuring.

297

BOUNCING/DE-BOUNCING
In other than hardware techniques available to overcome debouncing, software programming can also
help to aviod it. This will eliminate the need to additional RC circuit. In RC block, the user can also set the
time interval in Waijung Blockset have Debounce block in Simulink Library: Waijung Blockset >> STM32F4
Target >> On-chip Peripherals >> IO by setting parameter of Debounce block.

298

149
12/17/2016

Minggu Ke - 13

299

Programming Microcontroller with Matlab


LCD Character and ADC

300

150
12/17/2016

LCD Character Experiment


• Objective
• Learn how to setup GPIO port in Simulink library for LCD
Character
• Learn how to setup displaying value of process variable on
LCD Character

301

Basic LCD Character

302

151
12/17/2016

Basic LCD Character


1."Target Setup" block, this block is needed for STM32F4 target. Select the right MCU part,
compiler, automatic compile & download and more. This demo use sample time is 1ms.
2."Character LCD Setup" block. This block located in LCD Setup subsystem, for configure
MCU pin to control LCD display.
3."Volatile Data Storage" and "Volatile Data Storage1" blocks are configured as string buffer,
storing string/ message for LCD line2 and line1 respectively.
4."Character LCD Write" block use for write LCD line with string/ message from buffer
(Volatile Data storage1).
5. "Character LCD Write1" block use for write LCD line with string/ message from "Volatile Data
Storage" block.
6. "printf2" block, generate formatted string: Index: %u and store into "Volatile Data Storage1"
block. %u will be replaced with unsigned int32 value from counter free running block.
7."printf" block, generate formatted string: Value: %1.3f V and store into "Volatile Data
Storage" block. %1.3f will replaced with your desired data. 303

In this experiment LCD Character is


installed on GPIOD, D0-D7

304

152
12/17/2016

Basic LCD Character

305

Basic LCD Character

306

153
12/17/2016

Basic LCD Character

307

Multi Channel ADC

154
12/17/2016

GPIO for Multi channel ADC


• Objective
• Learn how to setup GPIO pin in Simulink Model for Analog input
• Learn how to Analog value from ADC to process variable
• Learn how to displaying analog value from ADC on LCD Character

309
Regular ADC in a Simulink

Configuration item Selectable option/ Value Description


ADC Module 1 There are 3 modules available.
2
3
Output Data Type Double Select output data type for each
Single ADC output port.
Raw (uint16)
ADC Prescaler Auto Select ADC clock prescaler to
2 optimize the conversion speed.
4
6
8
Read ANx; x=0 to 15 Checked/ Un-checked Check: Enable ADC channel
Un-checked: Disable ADC channel.
Read Temperature Sensor Checked/ Un-checked Check: Enable reading internal
temperature sensor.
Un-checked: Disable.
Read VREFINT Checked/ Un-checked Check: Enable reading internal
voltage reference.
Un-checked: Disable.
Read VBAT Checked/ Un-checked Check: Enable reading VBAT level.
Un-checked: Disable.
Sample Time (Sec) Sample time value in unit of Configuration block sample time
second, default -1. value.
Enable custom port labels Checked/ Un-checked Checked: enable custom port
labels.
Custom output port labels Port label with comma separate Put the desired string to appear on
value. port labels. 310

155
12/17/2016

Regular ADC in a Simulink model

311

ADC Experiment 1

312

156
12/17/2016

ADC Experiment 2

313

ADC Experiment 3

314

157
12/17/2016

ADC Experiment 3

315

316

158
12/17/2016

Minggu Ke - 14

317

Programming Microcontroller with Matlab


Regular DAC and Arbitrary Waveform Generator

318

159
12/17/2016

Regular DAC

319

GPIO for Regular DAC


• Objective
• Learn how to setup GPIO pin in Simulink Model for Analog Output
• Learn how to transfer Analog value of process variable on DAC

320

160
12/17/2016

Use the Digital to Analog Convertor (DAC) Block to


Regular DAC in a Simulink
generate analog signals. For all STM32F4xx, a maximum of
2 analog channels can be generated simultaneously.
1. Channel 1 = Pin A4
2. Channel 2 = Pin A5
The DAC module of STM32F4xx has the following
specifications.
2 x 12-bits 1MHz Sample per second DAC converters: one
for each output channel Better resolution can be
controlled with input voltage reference VREF

The DAC block takes inputs as either voltage (between 0 -


3.3V) or raw data (between 0 - 4095) and generated
output analog signals according to the following equation.
Analog output voltage = VREF x DOR / 4095, where DOR is
the required DAC register value. For voltage input, DOR is
computer as follow: DOR = (INPUT_VOLTS x 4095) / VREF
For raw data (both 8 and 12 bits) input, DOR is computer
as follow: DOR = INPUT_RAW
The DAC Module is based on software simultaneous
trigger configuration.

321
Regular DAC in a Simulink

This example demonstrates how to use the Regular DAC Block to output 2 analog signals
1. Triangular Waveform frequency 1kHz, Amplitude 0 - 2V
2. Sinusoidal Waveform frequency 1kHz, Ampliture 0.5 - 2.5V
Note that:
The values used to drive DAC Module in this example are derived from native Simulink block from Simulink
Source block library. This approach is not suitable for generating high-frequency signals. This is because the
Source blocks compute each value by solving relevant equation analytically, hence there is computation
time lost. 322

161
Regular DAC in a Simulink Regular DAC in a Simulink

324
323
12/17/2016

162
12/17/2016

DAC Experiment 1

325

DAC Experiment 1

326

163
12/17/2016

DAC Experiment 1

327

DAC Experiment 1

328

164
12/17/2016

DAC Experiment 2

329

DAC Experiment 2

330

165
12/17/2016

DAC
Arbitrary Waveform Generator

331
DAC Arbitrary Waveform Generator

332

166
12/17/2016

DAC Arbitrary Waveform Generator

• Use this block to output pre-determined sequence of voltage values to


Digital to Analog Converter modules of the MCU.
• STM32F4 has a maximum number of 2 DAC channels, meaning STM32F4
can be used as a 2 channels arbitrary function generator (by default
between 0 - 3.3V).
• Users give an array of voltage values to be output to the DAC modules.
• This block uses DMA to automatically control the output of DAC,
minimizing MCU load.
• Select "Loop Data" to enable output values to loop back continuously.
• Check "Enable Simulation" to enable output ports for output DAC values
during simulation.

333
DAC Arbitrary Waveform Generator

This example demonstrates how to use Arbitrary Waveform


Generator Block to output analog voltage sequences at 100kHz
rate.
a) [0 0.5 1 1.5 2] on DAC channel 1
b) [2.5 2 1.5 1 0] on DAC channel 2

334

167
12/17/2016

DAC Arbitrary Waveform Generator Two analog signals should be output from pins A4 and A5 as shown below

335

336

168
12/17/2016

Minggu Ke - 15

337

Programming Microcontroller with Matlab


Basic PWM and Advanced PWM

338

169
12/17/2016

Use this block to generate edge-aligned Pulse


Width Modulation (PWM) signals. The following
Basic PWM

conditions applies.
1. Up to a maximum number of 4 edge-aligned
PWM signals (channels) can be generated per
timer.
2. Each timer has 16-bit counter that
determines the PWM period.
3. PWM period can not be changed during run-
time.

How does this block work?


This block accepts Input Duty Cycle (%) between
0-100 as double values for each generated PWM
signal.

This block supports "Enable custom port labels". 339

Clock Computation
PWM signal frequency is determined by the value TIMx_ARR and a duty cycle is determined
by the value TIMx_CCRx. The timer's clock is computed as follows:
TIMx_CLK = HCLK/APBxPrescaler
where TIM2,3,4,5,6,7,12,13,14 uses APB1 and TIM1,8,9,10,11 uses APB2.
The timer's auto reload value (TIMx_ARR) that determines the PWM period for each timer is
Basic PWM

computed from:
TIMx_ARR = (TIMx_CounterClock * PWM_period) - 1
where TIMx_CounterClock = TIMx_CLK / (TIMx_Prescaler + 1).

STM32F4 Target searches for the optimal TIMx_ARR automatically using the following
constraints
1. TIMx_Prescaler <= 65535
2. TIMx_ARR is as near a whole number as possible, i.e. min(TIMx_ARR -
floor(TIMx_ARR))
The duty cycle is computed from:
TIMx_CCRx = TIMx_ARR * (Duty Cycle / 100)

340

170
12/17/2016

Basic PWM PWM Experiment 1

341

PWM Experiment 1
This example demonstrates how to use the Basic
PWM Block to configure Timer 4 generate Active
High PWM signals with 0.02 seconds period.

4 PWM signals are generated as follows.


Channel 1 = D12 (100% Duty Cycle)
Channel 2 = D13 (75% Duty Cycle)
Channel 3 = D14 (25% Duty Cycle)
Channel 4 = D15 (0% Duty Cycle)

342

171
12/17/2016

PWM Experiment 2

This example demonstrates how to use the Basic


PWM Block to configure Timer 4 generate Active High
PWM signals with 0.02 seconds period.

4 PWM signals are generated as follows.


Channel 1 = D12 (100% Duty Cycle)
Channel 2 = D13 (75% Duty Cycle)
Channel 3 = D14 (25% Duty Cycle)
Channel 4 = D15 (0% Duty Cycle)

343

PWM Experiment 2

This example demonstrates how to use the Basic


PWM Block to configure Timer 4 generate Active High
PWM signals with 0.02 seconds period.

4 PWM signals are generated as follows.


Channel 1 = D12 (100% Duty Cycle)
Channel 2 = D13 (75% Duty Cycle)
Channel 3 = D14 (25% Duty Cycle)
Channel 4 = D15 (0% Duty Cycle)

344

172
12/17/2016

Controlling
Basic PWM PWM Duty Cycle With ADC

345

Controlling
Basic PWM PWM Duty Cycle With ADC

346

173
12/17/2016

Basic PWM Sinusoidal PWM

347

Basic PWM Sinusoidal PWM

348

174
12/17/2016

Example DC motor control

349

This block implement PWM generation upto 7 output with variable of


duty cycle, complementary outputs and dead-time which required in
power electronics control, motor control and other advance control
application.
Advanced PWM

350

175
12/17/2016

Description

This demo implements


Advance PWM blocks,
using timer1 (TIM1) and
Advanced PWM

timer8 (TIM8) together


with frequency 100KHz
and insert 1uS for dead-
time.

All input into block are


enabled and apply
constant duty cycle value
20% to channel 1, 30% to
channel 2, 50% to channel
3 and 70% to channel 4
(Ref).

351

An example of waveform capture PWM output CH1, CH1N, CH2 and CH2N. Due to Dead-time 1uS (equal to
10% of period 10uS), so the duty cycle measurement of CH1 will be 10% instead of 20%.
Advanced PWM

352

176
12/17/2016

Minggu Ke - 16

353

Programming Microcontroller with Matlab


Timer Encoder And Timer Capture

354

177
12/17/2016

Encoder Read

The encoder read function uses built-in


STM32F4 timer to interpret encoder data.

Available pins for encoder channel A and B


depends on selected MCU (via Target Setup
Block) and Timer.

The encoder position count always count up:


From 0 to (PPR x 4)-1 when channel A and B
are used.
From 0 to (PPR x 2)-1 when only a single
channel (either A or B) is used.

If Reset counter after every counter read is


checked, the counter is reset to zero after
the count is read. 355
PWM Capture

Use this block when input signal is PWM, to


analyze its frequency and duty cycle.
Maximum input frequency should lower than
10kHz, and minimum is 0.33Hz.

Output port
1. READY , Return status of PWM capture
operation, value is non-zero when data is
ready.
2. +Width (sec), Positive pulse width value, in
unit of seconds.
3. +Duty (%), Positive duty cycle value, in
percentage.
4. Frequency (Hz), PWM frequency, in unit of
Hz.
356

178
12/17/2016

Use this block when input signal is PWM,


to analyze its frequency and duty cycle.
Maximum input frequency should lower
than 10kHz, and minimum is 0.33Hz.
PWM Capture

Output port
1. READY , Return status of PWM capture
operation, value is non-zero when data
is ready.
2. +Width (sec), Positive pulse width
value, in unit of seconds.
3. +Duty (%), Positive duty cycle value, in
percentage.
4. Frequency (Hz), PWM frequency, in
unit of Hz.

357

358

179
12/17/2016

eka@pens.ac.id, epyk@pens.ac.id
Politeknik Elektronika Negeri Surabaya
©2016
359

Terima kasih

360

180

S-ar putea să vă placă și