General about PWMPulse-width modulation PWM is a modulation process or technique used in most communication systems for encoding the amplitude of a signal right into a pulse width or dur
Trang 1HO CHI MINH CITY UNIVERSITY OF TECHNOLOGY - VIETNAM NATIONAL UNIVERSITY
-FACULTY OF ELECTRICAL AND ELECTRONICS ENGINEERING
EE4447: EMBEDDED CONTROL SYSTEM
EXERCISE REPORT #3 Using STM32F4 Generate PWM to Control DC Motor
with PID Algorithm
Instructor: PhD Nguyen Vinh Hao
Class: TT01
Group: 9
Group’s Member:
Trang 2General about PWM 2
I HARDWARE INTRODUCTION 3
1.1 STM32F407VGT 3
1.2 L298N Driver 4
1.3 Encoder DC Servo JGB37-520 333RPM 5
1.4 Synchronization Hardware 6
II SOFTWARE INTRODUCTION FOR MCU STM32 and PC 7
III SETUP FIRMWARE FOR MCU STM32F407 8
3.1 Setup Timer 1 (PWM) 8
3.2 Setup Timer 2 (Encoder) 8
3.3 Setup UART 9
3.4 PID Algorithm 10
3.5 Push PWM pules for motor 11
3.6 Function control motor from PID parameter 11
IV DESIGN GUI IN VISUAL STUDIO 12
4.1 Interface 12
4.2 Code for controlling the received data 13
4.3 GUI when received data 15
V EVALUATION PROJECT 15
1
Trang 3General about PWM
Pulse-width modulation (PWM) is a modulation process or technique used in most communication systems for encoding the amplitude of a signal right into a pulse width or duration of another signal, usually a carrier signal, for transmission Although PWM is also used in communications, its main purpose is actually to control the power that is supplied to various types of electrical devices, most especially to inertial loads such as AC/DC motors.
Duty Cycle of the PWM
When the signal is high, we call this “on time” To describe the amount of “on time”, we use the concept of the duty cycle Duty cycle is measured in percentage The percentage duty cycle specifically describes the percentage of time a digital signal is on over an interval or period of time This period is the inverse of the frequency of the waveform.
If a digital signal spends half of the time on and the other half off, we would say the digital signal has a duty cycle of 50% and resembles an ideal square wave If the percentage is higher than 50%, the digital signal spends more time in the high state than the low state and vice versa if the duty cycle is less than 50% See the figure below for full understanding:
Trang 4I HARDWARE INTRODUCTION
1.1 STM32F407VGT
The STM32F4DISCOVERY Discovery kit allows users to easily develop applications with the STM32F407VG high-performance microcontroller with the Arm® Cortex®-M4 32-bit core It includes everything required either for beginners or experienced users to get started quickly Based on STM32F407VG, it includes an ST-LINK/V2-A embedded debug tool, one STMEMS digital accelerometer, one digital microphone, one audio DAC with integrated class D speaker driver, LEDs, push-buttons and a USB OTG Micro-AB connector Specialized addon boards can
be connected by means of the extension header connectors The STM32F4DISCOVERY Discovery kit comes with the STM32 comprehensive free software libraries and examples available with the STM32CubeF4 MCU Package.
3
Trang 51.2 L298N Driver
The L298N is a dual H-Bridge motor driver which allows speed and direction control of two DC motors at the same time The module can drive DC motors that have voltages between 5 and 35V, with a peak current up to 2A.
This depends on the voltage used at the motors VCC The module have an onboard 5V regulator which is either enabled or disabled using a jumper If the motor supply voltage is up to 12V we can enable the 5V regulator and the 5V pin can be used as output, for example for powering our Arduino board But if the motor voltage is greater than 12V we must disconnect the jumper because those voltages will cause damage to the onboard 5V regulator In this case the 5V pin will be used as input as we need connect it to a 5V power supply in order the IC to work properly.
Trang 61.3 Encoder DC Servo JGB37-520 333RPM
JGB37-520 DC Geared Motor DC Servo Motor is integrated with a two-channel A, B Encoder to help read and accurately adjust the position and rotation of the motor in applications requiring high accuracy: PID control, Automatic robot action,
JGB37-520 DC Geared Motor DC Servo Motor has a metal structure for durability and high stability, used in robot models, vehicles, boats, , the motor's reducer has many The gear ratio makes it easy to choose between traction and speed (the greater the traction, the slower the speed and vice versa), the motor uses high-quality materials (pure copper wire core, 407 steel foil, strong magnets, ) for strength and durability superior to cheap ones on the market today (using wire cores, weak magnetic magnets).
Gear ratio 30:1 (motor turns 30 revolutions main shaft, reducer rotates 1 revolution).
No-load current: 120mA
Maximum withstand current under load: 1A
No-load speed: 333RPM (333 rpm)
Maximum endurance speed under load: 250RPM (250 rpm)
Traction Moment Rated: 3.5KG CM
Torque Maximum Moment: 5KG.CM
Gearbox length L: 22mm
Number of Encoder pulses per channel per spindle revolution: 11 x 30 = 330 pulses.
Pinout of JBG37-520 motor:
M1 - Red: Power cord for the motor.
GND - Black: Encoder power supply wire, 0VDC.
C1/A - Gold: A pulse return channel
C2/B - Green: Pulse return channel OFF
5
Trang 7M2 - White: Motor power cord
1.4 Synchronization Hardware
Method of triggering the PWM signal and directing
Pulse-width modulation (PWM) is used for controlling the amplitude of digital signals in order to control devices and applications requiring power or electricity This is an advanced tutorial on PWM generation We will learn how to generate a variable PWM signal with STM32F407 Series Variable PWM signal is used for controlling the speed of DC motors/Fans It is also used
in AC Light Dimmer PWM solar chargers also work on variable PWM signal Servo Motors angle and direction is also controlled with the PWM signal.
Hardware setup
Trang 8II SOFTWARE INTRODUCTION FOR MCU STM32
and PC
Software used for MCU STM32F4
No IDE + Compiler Note
1 STM2CubeMX Version 6.7.0
Package for STM32F4 Verion 1.24.0
2 MDK-ARM Professional Version 5.27.1.0
Package STM32F4xx_DFP Version 2.14.0
Software used for GUI in PC
No IDE + Compiler Note
1 Microsoft Visual Studio Enterprise Version 2022
7
Trang 9III SETUP FIRMWARE FOR MCU STM32F407
III.1 Setup Timer 1 (PWM)
//khai bao ham su dung
HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim1,TIM_CHANNEL_2);
HAL_TIM_Encoder_Start(&htim2,TIM_CHANNEL_1 | TIM_CHANNEL_2);
III.2 Setup Timer 2 (Encoder)
Trang 10encoder_cnt = HAL_TIM_GET_COUNTER(&htim2);
temp = encoder_cnt;
deg = temp * 360 /1320;
temp = (encoder_cnt - encoder_cnt_pre);
temp2 =rate;
rate = temp *333 *60 /660 ;
encoder_cnt_pre = encoder_cnt;
}
III.3 Setup UART
while (1)
{
//kiem tra du lieu nhan duoc tu giao dien
checkdata();
// dieu khien dong co
control();
// Lay mau thoi gian T
HAL_Delay(5);
// Doc thong so encoder, tinh toan vi tri va van toc
encoder();
// truyen du lieu len giao dien
HAL_UART_Transmit(&huart2,(uint8_t *)&send,sizeof(send),1000);
HAL_UART_Transmit(&huart2,(uint8_t *)"\n",2,1000);
HAL_UART_Receive_IT(&huart2,(uint8_t *)&check,1);
}
}
9
Trang 11III.4 PID Algorithm
Proportional-Integral-Derivative (PID) control is the most common control
algorithm used in industry and has been universally accepted in industrial
control The popularity of PID controllers can be attributed partly to their robust
performance in a wide range of operating conditions and partly to their
functional simplicity, which allows engineers to operate them in a simple,
straightforward manner As the name suggests, PID algorithm consists of three
basic coefficients; proportional, integral and derivative which are varied to get
optimal response
float PID( float current,float setpoint,float Kp,float Ki, float Kd)
{
float static error, pre_error, pre2_error, udk, pre_udk, Kp_part, Ki_part, Kd_part, Ts=0.005;
pre2_error = pre_error;
pre_error = error;
error = setpoint - current;
pre_udk = udk;
Kp_part = Kp * ( error - pre_error );
Ki_part = 0.5 * Ki * Ts *( error + pre_error );
Kd_part = Kd / Ts * ( error - 2*pre_error + pre2_error);
udk = pre_udk + Kp_part + Ki_part + Kd_part ;
if ( udk >100) { udk =100;
} else if ( udk <-100)
Trang 12III.5 Push PWM pules for motor
void chay(float udk)
{
udk = udk*100;
if (udk> 0)
{
HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1,0); HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_2,udk); }
else if (udk <0)
{
HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_2,0); HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1,-udk); }
return;
}
III.6 Function control motor from PID parameter
// Dieu khien dong co
void control()
{
if(motor_start ==true)
{
if (speed == true)
{
if (rate <0) { rate = temp2;
udk1 = PID(rate,value,Kp,Ki,Kd);
chay(udk1);
temp2 =0;
} else { udk1 = PID(rate,value,Kp,Ki,Kd);
chay(udk1);
snprintf(send,11,"%f",rate);
} }
if (position == true)
{ udk1 = PID(deg,value,Kp,Ki,Kd);
chay(udk1);
snprintf(send,11,"%f",deg);
}
11
Trang 13if(motor_start ==false)
{
HAL_TIM_SET_COMPARE(&htim1,TIM_CHANNEL_1,0);
rate = 0;
HAL_TIM_GET_COUNTER(&htim2) = 0;
snprintf(send,11,"%f",0.0);
udk1=0;
}
}
void encoder()
{
encoder_cnt = HAL_TIM_GET_COUNTER(&htim2);
temp = encoder_cnt;
deg = temp * 360 /1320;
temp = (encoder_cnt - encoder_cnt_pre);
temp2 =rate;
rate = temp *333 *60 /660 ;
encoder_cnt_pre = encoder_cnt;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_DMA_Init();
MX_TIM1_Init();
MX_USART2_UART_Init();
Trang 14IV DESIGN GUI IN VISUAL STUDIO
IV.1 Interface
IV.2 Code for controlling the received data
1 string[] ports = SerialPort.GetPortNames();
cboxcomport.Items.AddRange(ports);
Start.Enabled = false;
// An array of serial port names for the current computer
2 GraphPane myPane = zed.GraphPane;
myPane.Title.Text = "PID Control Chart Current Value
and PWM Pulse";
myPane.XAxis.Title.Text = "Time , Seconds";
myPane.YAxis.Title.Text = "Value ";
// Put the name for Graplh
3 RollingPointPairList list = new RollingPointPairList(100000);
RollingPointPairList list1 = new
RollingPointPairList(100000);
//Initially, a curve is added with no data points (list is empty)
4 myPane.XAxis.Scale.Min = 0;
myPane.XAxis.Scale.Max = 30;
myPane.XAxis.Scale.MinorStep = 1;
zed.AxisChange();
Tickstart = Environment.TickCount;
// Scale for x axis
5 double intcurrent; double intudk;
double.TryParse(current, out intcurrent);
// Design 1 curve
13
Trang 15(zed.GraphPane.CurveList.Count <= 0)if
return;
LineItem curve = zed.GraphPane.CurveList[0] as
LineItem;
LineItem curve1 = zed.GraphPane.CurveList[1] as
LineItem;
(curve == if null)
return;
(curve1 == if null)
return;
// Design item curve in graph
6 IPointListEdit list = curve.Points IPointListEdit; IPointListEdit list1 = curve1.Points IPointListEdit;as as
(list == if null)
return;
(list1 == if null)
return;
double time = (Environment.TickCount - Tickstart) /
1000.0;
list.Add(time, intcurrent);
list1.Add(time, intudk);
Scale xScale = zed.GraphPane.XAxis.Scale;
(time > xScale.Max - xScale.MajorStep)if
{
(intMode == 1)if
{
xScale.Max = time + xScale.MajorStep;
xScale.Min = xScale.Max - 30.0;
}
else
{
xScale.Max = time + xScale.MajorStep;
xScale.Min = 0;
}
}
zed.AxisChange();
zed.Invalidate();
}
private void timer1_Tick(object sender, EventArgs e)
{
(draw == if "Yes")
{
currentvalue.Text = check;
string udk = check;
// pointpairlist
Trang 16{
currentvalue.Text = "0";
Draw( "0" "0", );
}
}
7 timer1_Tick(object sender, EventArgs e)
{
(draw == if "Yes")
{
currentvalue.Text = check;
string udk = check;
Draw(currentvalue.Text,udk);
}
else if (draw == "No")
{
currentvalue.Text = "0";
Draw( "0" "0", );
}
}
//timer1_Tick
8 private void serialPort1_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
(serialPort1.IsOpen)if
{
check = serialPort1.ReadLine();
}
else return { ; }
// received data
9 private void SendData_Click(object sender, EventArgs e)
{
(serialPort1.IsOpen)if
{
(control.Text == if "Control Postion")
{
serialPort1.Write("vitri" "|" + );
}
Thread.Sleep(20);
(control.Text == if "Control Speed")
{
serialPort1.Write("tocdo" "|" + );
}
Thread.Sleep(20);
serialPort1.Write("value" + setpoint.Text + "|");
Thread.Sleep(20);
serialPort1.Write("gt_Kp" + Kp.Text + "|");
Thread.Sleep(20);
//button click t send data
15
Trang 17Thread.Sleep(20);
serialPort1.Write("gt_Kd" + Kd.Text + "|");
IV.3 GUI when received data
V EVALUATION PROJECT