Repository navigation
Expand file tree
/
Copy pathmotor_analysis.py
More file actions
456 lines (370 loc) · 16.8 KB
/
Copy pathmotor_analysis.py
File metadata and controls
456 lines (370 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
消费电子电机特性分析与可视化
本模块提供消费电子产品中常见电机的三阶段工作特性分析:
1. 启动阶段 (0-100ms) - 克服静摩擦,建立磁场
2. 运行阶段 (稳态) - 转速稳定,效率最高
3. 释放阶段 (制动) - 不同制动方式对比
支持的电机类型:
- 有刷直流电机 (Brushed DC Motor)
- 无刷直流电机 (Brushless DC Motor)
- 步进电机 (Stepper Motor)
- 舵机 (Servo Motor)
作者: AI Assistant
日期: 2024年
用途: 电机学习和教学演示
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import os
# 设置中文字体显示
def setup_chinese_fonts():
"""设置matplotlib中文字体显示"""
# 获取系统所有可用字体
available_fonts = [f.name for f in fm.fontManager.ttflist]
# 常见的中文字体列表,按优先级排序
chinese_fonts = [
'SimHei', # 黑体 (Windows)
'Microsoft YaHei', # 微软雅黑 (Windows)
'PingFang SC', # 苹方 (macOS)
'Hiragino Sans GB', # 冬青黑体 (macOS)
'Source Han Sans CN', # 思源黑体
'WenQuanYi Micro Hei', # 文泉驿微米黑 (Linux)
'WenQuanYi Zen Hei', # 文泉驿正黑 (Linux)
'Noto Sans CJK SC', # Google Noto (多平台)
'DejaVu Sans' # 备用字体
]
# 查找第一个可用的中文字体
font_found = False
for font in chinese_fonts:
if font in available_fonts:
plt.rcParams['font.sans-serif'] = [font] + plt.rcParams['font.sans-serif']
print(f"使用字体: {font}")
font_found = True
break
if not font_found:
print("警告:未找到合适的中文字体,可能无法正确显示中文")
print("可用字体示例:", available_fonts[:10])
print("\n推荐安装方法:")
print("Ubuntu/Debian: sudo apt install fonts-wqy-microhei fonts-wqy-zenhei")
print("CentOS/RHEL: sudo yum install wqy-microhei-fonts wqy-zenhei-fonts")
print("或者下载并安装 Noto Sans CJK 字体")
# 尝试使用matplotlib的默认字体,虽然可能不完美但至少能显示
plt.rcParams['font.sans-serif'] = ['DejaVu Sans'] + plt.rcParams['font.sans-serif']
# 设置负号正常显示
plt.rcParams['axes.unicode_minus'] = False
# 刷新字体缓存
plt.rcParams['font.size'] = 10
# 初始化中文字体
setup_chinese_fonts()
class MotorAnalysis:
"""电机特性分析类"""
def __init__(self, save_path='outputs'):
"""
初始化电机分析器
Args:
save_path (str): 图片保存路径,默认为outputs目录
"""
self.save_path = save_path
# 确保输出目录存在
os.makedirs(self.save_path, exist_ok=True)
def brushed_dc_startup(self):
"""
有刷直流电机启动特性分析
基于RC电路的电机启动模型:
- 电流: I(t) = (V/R) * exp(-Rt/L)
- 转速: ω(t) = (V/Ke) * (1 - exp(-t/τ))
- 转矩: T(t) = Kt * I(t)
Returns:
tuple: (时间, 电流, 转速, 转矩)
"""
t = np.linspace(0, 0.1, 1000) # 0-100ms启动时间
# 电机参数
V = 12 # 12V供电电压
R = 2 # 2Ω电枢电阻
L = 0.01 # 10mH电枢电感
Ke = 0.1 # 反电动势常数 (V⋅s/rad)
Kt = 0.05 # 转矩常数 (N⋅m/A)
# 启动特性计算
I = (V/R) * np.exp(-R*t/L) # 启动电流 (指数衰减)
omega = (V/Ke) * (1 - np.exp(-t/0.02)) # 转速上升 (指数增长)
T = Kt * I # 转矩 (正比于电流)
return t, I, omega, T
def running_characteristics(self):
"""
运行阶段特性对比分析
对比三种电机在稳态运行时的效率和转矩特性:
- 有刷直流:线性转矩下降,效率中等
- 无刷直流:恒转矩+恒功率,效率最高
- 步进电机:转矩快速下降,低速效率较高
Returns:
tuple: (转速, 效率曲线组, 转矩曲线组)
"""
speed_rpm = np.linspace(0, 5000, 1000) # 转速范围 0-5000 RPM
# 效率特性建模
brushed_eff = 0.8 * (1 - (speed_rpm/5000)**2) * np.exp(-speed_rpm/8000)
bldc_eff = 0.92 * (1 - 0.3*(speed_rpm/5000)**4)
stepper_eff = 0.7 * np.exp(-speed_rpm/1500)
# 转矩特性建模
brushed_torque = 0.5 * (1 - speed_rpm/6000) # 线性下降
bldc_torque = 0.8 * np.ones_like(speed_rpm) # 恒转矩区
bldc_torque[speed_rpm > 3000] = 0.8 * 3000 / speed_rpm[speed_rpm > 3000] # 恒功率区
stepper_torque = 0.3 * np.exp(-speed_rpm/800) # 指数下降
return (speed_rpm,
(brushed_eff, bldc_eff, stepper_eff),
(brushed_torque, bldc_torque, stepper_torque))
def braking_characteristics(self):
"""
制动阶段特性分析
对比四种制动方式的减速特性:
- 自由滑行:仅靠摩擦阻尼,减速缓慢
- 短路制动:绕组短路产生反向转矩,减速较快
- 电子制动:PWM控制制动转矩,减速线性可控
- 保持制动:步进电机立即停止并保持位置
Returns:
tuple: (时间, 各种制动方式的转速曲线)
"""
t_brake = np.linspace(0, 2, 1000) # 0-2秒制动时间
# 不同制动方式的数学模型
omega_free = 100 * np.exp(-t_brake/0.8) # 自由滑行 (τ=0.8s)
omega_short = 100 * np.exp(-t_brake/0.2) # 短路制动 (τ=0.2s)
omega_electronic = 100 * (1 - t_brake/1.5) # 电子制动 (线性)
omega_electronic[omega_electronic < 0] = 0 # 限制最小值
omega_stepper = np.zeros_like(t_brake) # 保持制动 (立即停止)
return t_brake, omega_free, omega_short, omega_electronic, omega_stepper
def plot_startup_characteristics(self):
"""绘制启动阶段特性图"""
print("正在生成启动特性分析图...")
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 8))
# 有刷直流电机启动特性
t, I, omega, T = self.brushed_dc_startup()
ax1.plot(t*1000, I, 'b-', linewidth=2, label='启动电流')
ax1.axhline(y=1, color='r', linestyle='--', alpha=0.7, label='额定电流')
ax1.set_xlabel('时间 (ms)')
ax1.set_ylabel('电流 (A)')
ax1.set_title('有刷直流电机 - 启动电流特性')
ax1.grid(True, alpha=0.3)
ax1.legend()
ax2.plot(t*1000, omega, 'g-', linewidth=2, label='转速上升')
ax2.set_xlabel('时间 (ms)')
ax2.set_ylabel('转速 (rad/s)')
ax2.set_title('有刷直流电机 - 转速响应特性')
ax2.grid(True, alpha=0.3)
ax2.legend()
# 无刷电机PWM控制特性
pwm_duty = np.linspace(0, 0.8, 100)
bldc_speed = pwm_duty * 12 / 0.1 # 线性关系 ω = (D×Vdc)/Ke
ax3.plot(pwm_duty*100, bldc_speed, 'purple', linewidth=2, label='BLDC转速')
ax3.set_xlabel('PWM占空比 (%)')
ax3.set_ylabel('转速 (rad/s)')
ax3.set_title('无刷直流电机 - PWM控制特性')
ax3.grid(True, alpha=0.3)
ax3.legend()
# 步进电机频率控制特性
step_freq = np.linspace(0, 1000, 100) # 0-1000Hz脉冲频率
stepper_speed = step_freq * 1.8 * np.pi / (180 * 200) # ω = f × θstep
ax4.plot(step_freq, stepper_speed, 'orange', linewidth=2, label='步进电机')
ax4.set_xlabel('脉冲频率 (Hz)')
ax4.set_ylabel('转速 (rad/s)')
ax4.set_title('步进电机 - 频率控制特性')
ax4.grid(True, alpha=0.3)
ax4.legend()
plt.tight_layout()
plt.savefig(os.path.join(self.save_path, 'motor_startup.png'),
dpi=300, bbox_inches='tight')
plt.show()
print(f"启动特性图已保存到: {os.path.join(self.save_path, 'motor_startup.png')}")
def plot_running_characteristics(self):
"""绘制运行阶段特性对比图"""
print("正在生成运行特性对比图...")
speed_rpm, eff_curves, torque_curves = self.running_characteristics()
brushed_eff, bldc_eff, stepper_eff = eff_curves
brushed_torque, bldc_torque, stepper_torque = torque_curves
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# 效率对比图
ax1.plot(speed_rpm, brushed_eff*100, 'b-', linewidth=2, label='有刷直流电机')
ax1.plot(speed_rpm, bldc_eff*100, 'g-', linewidth=2, label='无刷直流电机')
ax1.plot(speed_rpm, stepper_eff*100, 'orange', linewidth=2, label='步进电机')
ax1.set_xlabel('转速 (RPM)')
ax1.set_ylabel('效率 (%)')
ax1.set_title('电机效率对比')
ax1.grid(True, alpha=0.3)
ax1.legend()
ax1.set_ylim(0, 100)
# 转矩特性对比图
ax2.plot(speed_rpm, brushed_torque, 'b-', linewidth=2, label='有刷直流电机')
ax2.plot(speed_rpm, bldc_torque, 'g-', linewidth=2, label='无刷直流电机')
ax2.plot(speed_rpm, stepper_torque, 'orange', linewidth=2, label='步进电机')
ax2.set_xlabel('转速 (RPM)')
ax2.set_ylabel('转矩 (N⋅m)')
ax2.set_title('转矩-转速特性对比')
ax2.grid(True, alpha=0.3)
ax2.legend()
plt.tight_layout()
plt.savefig(os.path.join(self.save_path, 'motor_running.png'),
dpi=300, bbox_inches='tight')
plt.show()
print(f"运行特性图已保存到: {os.path.join(self.save_path, 'motor_running.png')}")
def plot_braking_characteristics(self):
"""绘制制动特性对比图"""
print("正在生成制动特性对比图...")
t_brake, omega_free, omega_short, omega_electronic, omega_stepper = self.braking_characteristics()
plt.figure(figsize=(10, 6))
plt.plot(t_brake, omega_free, 'b--', linewidth=2, label='有刷直流-自由滑行')
plt.plot(t_brake, omega_short, 'b-', linewidth=2, label='有刷直流-短路制动')
plt.plot(t_brake, omega_electronic, 'g-', linewidth=2, label='无刷直流-电子制动')
plt.plot(t_brake, omega_stepper, 'orange', linewidth=3, label='步进电机-保持制动')
plt.xlabel('时间 (s)')
plt.ylabel('转速 (rad/s)')
plt.title('电机制动特性对比')
plt.grid(True, alpha=0.3)
plt.legend()
plt.ylim(-5, 105)
# 添加制动类型说明文本框
plt.text(0.1, 80, '自由滑行:\n靠摩擦自然停止',
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightblue"))
plt.text(0.8, 60, '短路制动:\n绕组短路产生\n反向转矩',
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightgreen"))
plt.text(1.2, 30, '电子制动:\nPWM控制\n制动转矩',
bbox=dict(boxstyle="round,pad=0.3", facecolor="lightcoral"))
plt.tight_layout()
plt.savefig(os.path.join(self.save_path, 'motor_braking.png'),
dpi=300, bbox_inches='tight')
plt.show()
print(f"制动特性图已保存到: {os.path.join(self.save_path, 'motor_braking.png')}")
def generate_all_plots(self):
"""生成所有特性分析图"""
print("开始生成消费电子电机特性分析图...")
print("=" * 50)
self.plot_startup_characteristics()
print()
self.plot_running_characteristics()
print()
self.plot_braking_characteristics()
print("=" * 50)
print("所有图表生成完成!")
print(f"图片保存路径: {self.save_path}")
def main():
"""主函数 - 运行电机特性分析"""
# 创建分析器实例
analyzer = MotorAnalysis()
# 生成所有特性分析图
analyzer.generate_all_plots()
# 打印基本参数信息
print("\n电机基本特性参数:")
print("有刷直流电机: 效率75-85%, 启动转矩大, 控制简单")
print("无刷直流电机: 效率85-92%, 寿命长, 高速性能好")
print("步进电机: 效率35-70%, 精确定位, 低速转矩大")
print("舵机: 闭环控制, 角度精确, 响应快速")
class MotorEngineering:
"""
电机工程计算工具类
提供实用的电机工程计算功能,从motor_operation_demo.py整合而来。
符合"代码黄金定位"原则:自动化繁琐计算,让用户"算出"工程参数。
"""
@staticmethod
def estimate_load_torque(mass_kg, radius_m, friction_coeff=0.1):
"""
估算负载转矩
Args:
mass_kg: 负载质量 (kg)
radius_m: 作用半径 (m)
friction_coeff: 摩擦系数 (默认0.1)
Returns:
float: 负载转矩 (N⋅m)
"""
gravity = 9.81 # m/s²
return mass_kg * gravity * radius_m * friction_coeff
@staticmethod
def motor_selection_guide(required_torque):
"""
电机选型指导
Args:
required_torque: 所需转矩 (N⋅m)
Returns:
tuple: (推荐电机类型, 功率范围)
"""
safety_factor = 1.5
total_torque = required_torque * safety_factor
if total_torque < 0.1:
return "小型有刷直流电机", "10W-100W"
elif total_torque < 1.0:
return "无刷直流电机", "100W-1kW"
else:
return "伺服电机或大功率步进电机", ">1kW"
@staticmethod
def calculate_motor_requirements(load_mass_kg, radius_m, max_acceleration, friction_coeff=0.1):
"""
综合计算电机需求参数
Args:
load_mass_kg: 负载质量 (kg)
radius_m: 作用半径 (m)
max_acceleration: 最大角加速度 (rad/s²)
friction_coeff: 摩擦系数
Returns:
dict: 完整的计算结果和电机选型建议
"""
# 负载转矩计算
load_torque = MotorEngineering.estimate_load_torque(load_mass_kg, radius_m, friction_coeff)
# 负载惯量计算 (简化为点质量模型)
load_inertia = load_mass_kg * radius_m**2
# 加速转矩计算
acceleration_torque = load_inertia * max_acceleration
# 总需求转矩
total_torque = load_torque + acceleration_torque
# 电机选型建议
motor_type, power_range = MotorEngineering.motor_selection_guide(total_torque)
return {
"负载转矩": f"{load_torque:.3f} N⋅m",
"加速转矩": f"{acceleration_torque:.3f} N⋅m",
"总需求转矩": f"{total_torque:.3f} N⋅m",
"推荐电机": motor_type,
"功率范围": power_range,
"负载惯量": f"{load_inertia:.6f} kg⋅m²"
}
def demo_motor_calculations():
"""
电机工程计算演示
展示MotorEngineering类的实际使用,提供具体的工程计算案例。
"""
print("\n🔧 电机工程计算工具演示")
print("=" * 40)
# 实际工程案例
test_cases = [
{
"name": "小型齿轮减速器",
"mass": 0.1,
"radius": 0.02,
"accel": 5,
"description": "典型的小型机械臂关节"
},
{
"name": "中型传动系统",
"mass": 1.0,
"radius": 0.05,
"accel": 10,
"description": "工业输送带驱动轮"
},
{
"name": "重型负载应用",
"mass": 5.0,
"radius": 0.1,
"accel": 2,
"description": "大型升降机构"
},
]
for case in test_cases:
print(f"\n📋 {case['name']}负载分析:")
print(f" 应用场景: {case['description']}")
result = MotorEngineering.calculate_motor_requirements(
case["mass"], case["radius"], case["accel"]
)
for key, value in result.items():
print(f" {key}: {value}")
if __name__ == "__main__":
main()
# 可选:运行工程计算演示
# 取消注释下行可查看计算工具演示
# demo_motor_calculations()