第一部分:Python基础语法核心精要
1.1 Python语法快速入门
基础数据类型与操作:
python
# 变量与基本类型
robot_name = "TurtleBot3" # 字符串
battery_level = 98.5 # 浮点数
sensor_count = 8 # 整数
is_connected = True # 布尔值
# 集合类型
sensor_ids = [101, 102, 103] # 列表(可变)
motor_types = ('DC', 'Servo') # 元组(不可变)
config_params = {'max_speed': 2.0, 'timeout': 5} # 字典
# 类型转换
str(battery_level) # 浮点转字符串
int("120") # 字符串转整数
控制流结构:
python
# 条件判断
if battery_level < 20:
print("低电量警告!")
elif 20 <= battery_level < 50:
print("电量中等")
else:
print("电量充足")
# 循环结构
for sensor_id in sensor_ids:
print(f"正在初始化传感器 #{sensor_id}")
# 异常处理
try:
distance = read_sensor()
except SensorError as e:
print(f"传感器错误: {e}")
finally:
close_sensor()
1.2 Python函数与模块
函数定义与使用:
python
def calculate_velocity(distance, time, acceleration=0):
"""计算平均速度
:param distance: 移动距离(米)
:param time: 时间(秒)
:param acceleration: 加速度(可选)
:return: 速度值(米/秒)
"""
if acceleration:
return (distance / time) + 0.5 * acceleration * time
return distance / time
# 函数调用
vel = calculate_velocity(5.0, 2.0)
模块化编程:
python
# 创建robot_utils.py模块
def normalize_angle(angle):
"""将角度规范化到[-π, π]区间"""
while angle > math.pi:
angle -= 2.0 * math.pi
while angle < -math.pi:
angle += 2.0 * math.pi
return angle
# 主程序中导入
from robot_utils import normalize_angle
current_angle = normalize_angle(3.5)
1.3 面向对象编程基础
类与对象:
python
class MobileRobot:
# 类属性
robot_count = 0
def __init__(self, name, robot_type):
# 实例属性
self.name = name
self.type = robot_type
self.position = [0.0, 0.0]
MobileRobot.robot_count += 1
# 实例方法
def move(self, x, y):
self.position[0] += x
self.position[1] += y
print(f"{self.name} 移动到位置: {self.position}")
# 静态方法
@staticmethod
def calculate_distance(x1, y1, x2, y2):
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
# 创建对象
bot1 = MobileRobot("Robot1", "AGV")
bot1.move(1.5, 0.8)
第二部分:ROS2开发环境搭建

2.1 安装准备(Ubuntu 22.04)
系统要求与依赖:
bash
# 更新系统 sudo apt update && sudo apt upgrade -y # 安装基础依赖 sudo apt install curl git python3-pip python3-rosdep # 设置Python3为默认版本 sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1
2.2 ROS2安装步骤
| 步骤 | 命令 | 说明 |
|---|---|---|
| 1. 添加源 | sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg |
添加ROS2 GPG密钥 |
| 2. 设置仓库 | `echo "deb [arch= |

最低0.47元/天 解锁文章
4645

被折叠的 条评论
为什么被折叠?



