(Jetson Project Final) Jetson Nano Hector SLAM 로봇 최종 코드

mseokq23·2026년 11월 9일

이 시리즈에서 만든 모든 파일을 최종 버전으로 한 글에 모아둠.
결과물은 Hector SLAM 로봇. RPLIDAR A1, MPU6050, ESP32 모터, 장애물 회피, 탐색, 맵 자동 저장, Flutter 앱용 API까지 들어 있음.
환경: Jetson Nano B01, Ubuntu 20.04, ROS Noetic, Python 3.8, ESP32-WROOM-32D (Arduino IDE)

시리즈 글들은 실패한 것과 고친 것까지 순서대로 다 보여주는데, 그러다 보니 최종 코드가 30편 정도에 흩어져 있고 파일마다 버전도 여러 개임.
그래서 이 글에 모든 파일의 최종 버전을 한곳에 모았고, 중간에 찾은 버그도 고쳐둠.

0. 바로 실행

roslaunch robot_bringup bringup.launch                 # drive + obstacle avoidance (+ RViz)
roslaunch robot_bringup mapping.launch                 # Hector SLAM mapping
roslaunch robot_bringup mapping.launch explore:=true   # ... while the robot explores by itself
python3 server/map_api_server.py                       # API for the Flutter app (+ ngrok)

1. 프로젝트 진행 과정

단계글내용결과
0Ros2 foxy 설치, Cartographer Setup(1)부터 (3)까지ROS2 Foxy, rplidar_ros, 시리얼 노드, Cartographer실패. ROS1에서 포팅할 게 너무 많아서 ROS1 Noetic으로 바꿈
1#0부터 #4까지ROS Noetic, Jetson Nano 세팅, RPLIDAR A1완료
1#5부터 #8까지, #12IMU (MPU9250에서 MPU6050으로 변경), publisher, RViz, TF완료
1#9부터 #11까지, #13, #14ESP32 모터, 장애물 회피, master launch 파일완료
1#15Cartographer (ROS1, 소스 빌드)실패. 빌드 에러
1#16, #17Hector SLAM, 탐색일부만 동작. 이 글에서 고침
1#18move_base 자율주행접음 (바퀴 odometry 없음)
2Project2#1부터 #4까지새로 설치, Hector 매핑, 맵 서버와 Flutter 앱완료

2. 시스템 구성

  • RPLIDAR A1M8: USB(/dev/ttyUSB0)로 Jetson Nano에 연결
  • MPU6050(GY-521): I2C 버스 1(주소 0x68)로 Jetson Nano에 연결
  • Jetson Nano B01(Ubuntu 20.04, ROS Noetic): rplidarNode, mpu6050_publisher, hector_mapping, map_autosaver, obstacle_avoidance나 exploration, motor_control_node가 돎
  • Flutter 앱: Wi-Fi랑 ngrok을 거쳐서 Jetson의 map_api_server.py(5000 포트)에 접속
  • ESP32: Jetson에서 USB 시리얼(/dev/ttyACM0, 115200 baud)로 한 글자 명령(F, B, L, R, S)을 받아서 L298N으로 DC 모터 2개를 돌림

토픽이랑 TF 흐름

  • /scan(sensor_msgs/LaserScan, frame laser)은 hector_mapping, obstacle_avoidance_node, exploration_node가 받음
  • hector_mapping은 /map, /slam_out_pose, 그리고 map에서 base_link로 가는 TF를 보냄
  • obstacle_avoidance_node, exploration_node, map_api_server(POST /command), rostopic pub이 /motor_command(std_msgs/String)로 명령을 보내면 motor_control_node가 ESP32로 넘김
  • mpu6050_publisher는 /imu/data_raw(sensor_msgs/Imu, frame imu_link)를 보냄
  • map_autosaver는 /map을 받아서 30초마다 ~/my_map.pgm/.yaml에 저장하고, 끝날 때 ~/maps/map_<time>.*에 사본을 남김
  • TF tree: map에서 base_link(hector), base_link에서 laser(lidar.launch), base_link에서 imu_link(mpu6050.launch)

3. 폴더 구조

jetson_nano_self_driving/
├── src/                                  # copy into ~/catkin_ws/src
│   ├── mpu6050_driver/                   # IMU                       (#5-1, #6, #7, #8, #12)
│   ├── motor_control/                    # ESP32 motors + avoidance  (#9, #10, #11)
│   ├── exploration/                      # random-walk exploration   (#17)
│   └── robot_bringup/                    # launch files + autosaver  (#14, #16, Project2 #4)
├── firmware/esp32_motor_control/         # Arduino IDE sketch        (#9)
└── server/                               # Flask API for the app     (Project2 #4)

rplidar_ros(Slamtec)랑 hector_slam은 clone하거나 apt로 설치해서 수정 없이 그대로 씀.
예전에 그 안에서 고쳤던 내용(tutorial.launch, mapping_default.launch)은 이제 robot_bringup/launch/에 있음.

4. 하드웨어 배선

부품연결
RPLIDAR A1M8USB, /dev/ttyUSB0 (115200)
ESP32-WROOM-32DUSB, /dev/ttyACM0 (115200, USB CDC)
MPU6050 VCC, GNDJetson 1번 핀(3.3V), 6번 핀(GND)
MPU6050 SCL, SDAJetson 5번 핀(SCL1), 3번 핀(SDA1). /dev/i2c-1, 주소 0x68
L298N IN1, IN2, IN3, IN4ESP32 GPIO 5, 18, 19, 21
L298N ENA, ENB (PWM)ESP32 GPIO 22, 23

로봇 지름이 400 mm라서 장애물 거리 기준은 0.5 m로 잡음 (반지름 0.2 m에 여유 0.3 m).

5. 설치와 빌드

# permissions for serial (LiDAR, ESP32) and I2C (IMU), then reboot
sudo usermod -aG dialout,i2c $USER
sudo reboot

# system packages
sudo apt update
sudo apt install -y i2c-tools python3-smbus python3-serial python3-numpy \
                    python3-flask python3-pil ros-noetic-map-server
sudo apt install -y ros-noetic-rviz-imu-plugin   # optional: Imu display in RViz

# catkin workspace
cd ~/catkin_ws/src
git clone https://github.com/Slamtec/rplidar_ros.git
git clone https://github.com/tu-darmstadt-ros-pkg/hector_slam.git
#   (or instead: sudo apt install ros-noetic-rplidar-ros ros-noetic-hector-slam)
#   + the 4 packages of this post: mpu6050_driver, motor_control, exploration, robot_bringup

cd ~/catkin_ws
rosdep install --from-paths src --ignore-src -r -y
catkin_make
source devel/setup.bash

# check the hardware
ls /dev/ttyUSB* /dev/ttyACM*        # LiDAR = ttyUSB0, ESP32 = ttyACM0
sudo i2cdetect -y -r 1              # MPU6050 shows up as 68
python3 ~/catkin_ws/src/mpu6050_driver/scripts/mpu6050_test.py

ESP32는 Arduino IDE에서 7.5의 스케치를 열고 보드를 ESP32 Dev Module로 고른 다음 업로드.
업로드하고 나면 시리얼 모니터는 닫아야 함 (열려 있으면 포트를 계속 잡고 있음).

6. 실행

6.1 장애물 회피하면서 주행 (#14)

roslaunch robot_bringup bringup.launch               # LiDAR + IMU + motors + avoidance + RViz
roslaunch robot_bringup bringup.launch rviz:=false   # headless (SSH)

roscore는 따로 안 띄워도 됨. roslaunch가 master가 없으면 알아서 띄움.

6.2 Hector SLAM으로 매핑 (Project2#4)

roslaunch robot_bringup mapping.launch                # drive by hand / from the app
roslaunch robot_bringup mapping.launch explore:=true  # the robot explores by itself
rosrun map_server map_saver -f ~/my_map               # save right now (optional)

맵은 30초마다 ~/my_map.pgm/.yaml로 저장되고, Ctrl+C로 끝내면 ~/maps/map_YYYYmmdd_HHMMSS.*에 사본이 남음.

6.3 앱 서버 (Flutter 앱에서 ngrok 거쳐서 Jetson으로)

export ROBOT_API_KEY='<long random string, same value as in the app>'
python3 ~/jetson_nano_self_driving/server/map_api_server.py    # no sudo
ngrok http --url=<your-name>.ngrok.io 5000                     # second terminal

6.4 직접 확인

rostopic pub -1 /motor_command std_msgs/String "F"   # F B L R S
rostopic echo /imu/data_raw
rostopic hz /scan
rosrun rqt_graph rqt_graph                           # nodes and topics
rosrun rqt_tf_tree rqt_tf_tree                       # TF tree

6.5 launch argument 정리

launch 파일argument기본값의미
bringup.launchlidar_port, esp32_port/dev/ttyUSB0, /dev/ttyACM0시리얼 포트
use_imutrueMPU6050 노드 실행
obstacle_avoidancetrueobstacle_avoidance_node 실행
rviztrue화면 없이 돌릴 때는 false
mapping.launchlidar_port, esp32_port, use_imu, rviz위와 같음
motorstruemotor_control_node (탐색, 앱에서 조종할 때 필요)
explorefalseexploration_node 실행
autosavetruemap_autosaver 실행

7. 전체 코드

7.1 mpu6050_driver: IMU 드라이버 (#5-1, #6, #7, #8, #12)

src/mpu6050_driver/package.xml

<?xml version="1.0"?>
<package format="2">
  <name>mpu6050_driver</name>
  <version>1.0.0</version>
  <description>
    MPU6050 (GY-521) 6-axis IMU driver for Jetson Nano (I2C bus 1, address 0x68).
    Publishes sensor_msgs/Imu on /imu/data_raw and the static TF base_link -> imu_link.
  </description>
  <maintainer email="minseok1270@gmail.com">mseokq23</maintainer>
  <license>Apache-2.0</license>

  <buildtool_depend>catkin</buildtool_depend>

  <depend>rospy</depend>
  <depend>std_msgs</depend>
  <depend>sensor_msgs</depend>
  <depend>geometry_msgs</depend>
  <depend>tf</depend>
  <depend>tf2_ros</depend>

  <exec_depend>python3-smbus</exec_depend>
</package>

src/mpu6050_driver/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(mpu6050_driver)

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  sensor_msgs
  geometry_msgs
  tf
  tf2_ros
)

catkin_package()

catkin_install_python(PROGRAMS
  scripts/mpu6050_test.py
  scripts/mpu6050_publisher.py
  scripts/tf_broadcaster.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

install(DIRECTORY launch
  DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)

src/mpu6050_driver/scripts/mpu6050_test.py

#!/usr/bin/env python3
"""
Stand-alone MPU6050 I2C test (no ROS needed).          [Jetson Project #6]

    python3 mpu6050_test.py          # bus 1, address 0x68
    python3 mpu6050_test.py 1 0x69   # other bus / address

Prints raw accelerometer / gyroscope values once per second.
If this works, wiring + I2C are OK and the ROS node will work too.
"""
import sys
import time

import smbus

# MPU6050 registers
PWR_MGMT_1   = 0x6B
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
GYRO_XOUT_H  = 0x43
GYRO_YOUT_H  = 0x45
GYRO_ZOUT_H  = 0x47


def read_word(bus, address, reg):
    high = bus.read_byte_data(address, reg)
    low = bus.read_byte_data(address, reg + 1)
    val = (high << 8) + low
    if val >= 0x8000:
        return -((65535 - val) + 1)
    return val


def main():
    bus_num = int(sys.argv[1]) if len(sys.argv) > 1 else 1
    address = int(sys.argv[2], 0) if len(sys.argv) > 2 else 0x68

    bus = smbus.SMBus(bus_num)
    bus.write_byte_data(address, PWR_MGMT_1, 0)  # wake up the MPU6050

    try:
        while True:
            accel_x = read_word(bus, address, ACCEL_XOUT_H)
            accel_y = read_word(bus, address, ACCEL_YOUT_H)
            accel_z = read_word(bus, address, ACCEL_ZOUT_H)
            gyro_x = read_word(bus, address, GYRO_XOUT_H)
            gyro_y = read_word(bus, address, GYRO_YOUT_H)
            gyro_z = read_word(bus, address, GYRO_ZOUT_H)

            print(f"Accel: X={accel_x} Y={accel_y} Z={accel_z} | "
                  f"Gyro: X={gyro_x} Y={gyro_y} Z={gyro_z}")
            time.sleep(1)
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()

src/mpu6050_driver/scripts/mpu6050_publisher.py

#!/usr/bin/env python3
"""
MPU6050 (GY-521) IMU publisher                [Jetson Project #6 -> #7(2) -> final]

Reads the accelerometer + gyroscope over I2C and publishes
sensor_msgs/Imu on /imu/data_raw (frame: imu_link).

Changes from the blog version
  * SI units as sensor_msgs/Imu requires: m/s^2 (was g) and rad/s (was deg/s)
  * one 14-byte burst read per sample, so accel/gyro come from the same sample
  * gyro bias calibration at start-up (keep the robot still for ~1 s)
  * orientation_covariance[0] = -1 -> "this IMU gives no orientation"
  * log is throttled (it used to flood the terminal every sample)
  * parameters instead of hard-coded values

Parameters
  ~i2c_bus             (int,   1)          /dev/i2c-1
  ~i2c_address         (int,   0x68)       0x69 if AD0 is tied to 3.3V
  ~frame_id            (str,   imu_link)
  ~rate                (float, 50.0)       Hz
  ~calibration_samples (int,   200)        0 = skip gyro calibration
"""
import math
import struct

import rospy
import smbus
from sensor_msgs.msg import Imu

# MPU6050 registers
PWR_MGMT_1   = 0x6B
SMPLRT_DIV   = 0x19
CONFIG       = 0x1A
GYRO_CONFIG  = 0x1B
ACCEL_CONFIG = 0x1C
ACCEL_XOUT_H = 0x3B  # ACCEL(6) + TEMP(2) + GYRO(6) = 14 bytes from here

ACCEL_LSB_PER_G   = 16384.0  # +-2 g
GYRO_LSB_PER_DPS  = 131.0    # +-250 deg/s
GRAVITY           = 9.80665  # m/s^2
DEG_TO_RAD        = math.pi / 180.0


class MPU6050:
    def __init__(self, bus_num=1, address=0x68):
        self.bus = smbus.SMBus(bus_num)
        self.address = address

    def initialize(self):
        self.bus.write_byte_data(self.address, PWR_MGMT_1, 0x00)    # wake up
        rospy.sleep(0.1)
        self.bus.write_byte_data(self.address, SMPLRT_DIV, 0x00)
        self.bus.write_byte_data(self.address, CONFIG, 0x03)        # DLPF ~44 Hz (less noise)
        self.bus.write_byte_data(self.address, ACCEL_CONFIG, 0x00)  # +-2 g
        self.bus.write_byte_data(self.address, GYRO_CONFIG, 0x00)   # +-250 deg/s

    def read(self):
        """Return (ax, ay, az) in m/s^2 and (gx, gy, gz) in rad/s."""
        raw = self.bus.read_i2c_block_data(self.address, ACCEL_XOUT_H, 14)
        ax, ay, az, _temp, gx, gy, gz = struct.unpack('>7h', bytes(raw))
        accel = tuple(v / ACCEL_LSB_PER_G * GRAVITY for v in (ax, ay, az))
        gyro = tuple(v / GYRO_LSB_PER_DPS * DEG_TO_RAD for v in (gx, gy, gz))
        return accel, gyro


def calibrate_gyro(sensor, samples):
    """Average the gyro while the robot is standing still -> bias (rad/s)."""
    rospy.loginfo(f"Calibrating gyro with {samples} samples - keep the robot still...")
    sums = [0.0, 0.0, 0.0]
    good = 0
    for _ in range(samples):
        try:
            _, gyro = sensor.read()
        except OSError:
            continue
        sums = [s + g for s, g in zip(sums, gyro)]
        good += 1
        rospy.sleep(0.005)
    if good == 0:
        rospy.logwarn("Gyro calibration failed (no samples). Using zero bias.")
        return (0.0, 0.0, 0.0)
    bias = tuple(s / good for s in sums)
    rospy.loginfo("Gyro bias [rad/s]: X=%.4f Y=%.4f Z=%.4f" % bias)
    return bias


def main():
    rospy.init_node('mpu6050_publisher')

    bus_num = int(rospy.get_param('~i2c_bus', 1))
    address = int(str(rospy.get_param('~i2c_address', '0x68')), 0)  # "0x68" or 104
    frame_id = rospy.get_param('~frame_id', 'imu_link')
    rate_hz = float(rospy.get_param('~rate', 50.0))
    calib_samples = int(rospy.get_param('~calibration_samples', 200))

    imu_pub = rospy.Publisher('/imu/data_raw', Imu, queue_size=10)

    try:
        sensor = MPU6050(bus_num, address)
        sensor.initialize()
    except Exception as e:  # wiring / permission / wrong address
        rospy.logerr(f"Failed to initialize MPU6050 on i2c-{bus_num} @ {hex(address)}: {e}")
        rospy.logerr("Check wiring, 'sudo i2cdetect -y -r 1' and that your user is in the 'i2c' group.")
        return

    gyro_bias = calibrate_gyro(sensor, calib_samples) if calib_samples > 0 else (0.0, 0.0, 0.0)

    imu_msg = Imu()
    imu_msg.header.frame_id = frame_id
    # No orientation estimate from a raw 6-axis IMU -> covariance[0] = -1 (sensor_msgs/Imu convention)
    imu_msg.orientation.w = 1.0
    imu_msg.orientation_covariance = [-1.0, 0, 0, 0, 0, 0, 0, 0, 0]
    imu_msg.angular_velocity_covariance = [0.1, 0, 0, 0, 0.1, 0, 0, 0, 0.1]
    imu_msg.linear_acceleration_covariance = [0.1, 0, 0, 0, 0.1, 0, 0, 0, 0.1]

    rospy.loginfo(f"MPU6050 ready: publishing /imu/data_raw at {rate_hz:.0f} Hz (frame: {frame_id})")
    rate = rospy.Rate(rate_hz)
    errors = 0

    while not rospy.is_shutdown():
        try:
            (ax, ay, az), (gx, gy, gz) = sensor.read()
            errors = 0
        except OSError as e:
            errors += 1
            rospy.logwarn_throttle(2.0, f"Error reading MPU6050 data: {e}")
            if errors % 50 == 0:  # sensor reset / loose wire -> try to wake it up again
                try:
                    sensor.initialize()
                except OSError:
                    pass
            rate.sleep()
            continue

        imu_msg.header.stamp = rospy.Time.now()
        imu_msg.linear_acceleration.x = ax
        imu_msg.linear_acceleration.y = ay
        imu_msg.linear_acceleration.z = az
        imu_msg.angular_velocity.x = gx - gyro_bias[0]
        imu_msg.angular_velocity.y = gy - gyro_bias[1]
        imu_msg.angular_velocity.z = gz - gyro_bias[2]
        imu_pub.publish(imu_msg)

        rospy.loginfo_throttle(
            2.0,
            f"Accel[m/s^2]: X={ax:.2f} Y={ay:.2f} Z={az:.2f} | "
            f"Gyro[rad/s]: X={imu_msg.angular_velocity.x:.3f} "
            f"Y={imu_msg.angular_velocity.y:.3f} Z={imu_msg.angular_velocity.z:.3f}")
        rate.sleep()


if __name__ == "__main__":
    try:
        main()
    except rospy.ROSInterruptException:
        pass

src/mpu6050_driver/scripts/tf_broadcaster.py

#!/usr/bin/env python3
"""
IMU TF broadcaster: base_link -> imu_link          [Jetson Project #8 -> #12 -> final]

The MPU6050 is screwed to the robot, so the transform never changes.
Final version publishes it once as a *static* transform (/tf_static)
instead of re-sending it at 10 Hz, and the mounting offset is a parameter.

Parameters
  ~parent_frame (str, base_link)
  ~child_frame  (str, imu_link)
  ~x ~y ~z           mounting position of the IMU on the robot [m]
  ~roll ~pitch ~yaw  mounting rotation [rad]
"""
import rospy
import tf2_ros
from geometry_msgs.msg import TransformStamped
from tf.transformations import quaternion_from_euler


class TFBroadcasterNode:
    def __init__(self):
        rospy.init_node('imu_tf_broadcaster')
        self.parent_frame = rospy.get_param('~parent_frame', 'base_link')
        self.child_frame = rospy.get_param('~child_frame', 'imu_link')

        # Adjust based on how the MPU6050 is mounted on the robot
        self.translation = tuple(float(rospy.get_param('~' + k, 0.0)) for k in ('x', 'y', 'z'))
        self.rpy = tuple(float(rospy.get_param('~' + k, 0.0)) for k in ('roll', 'pitch', 'yaw'))

        self.br = tf2_ros.StaticTransformBroadcaster()

    def broadcast(self):
        t = TransformStamped()
        t.header.stamp = rospy.Time.now()
        t.header.frame_id = self.parent_frame
        t.child_frame_id = self.child_frame
        t.transform.translation.x, t.transform.translation.y, t.transform.translation.z = self.translation
        qx, qy, qz, qw = quaternion_from_euler(*self.rpy)
        t.transform.rotation.x = qx
        t.transform.rotation.y = qy
        t.transform.rotation.z = qz
        t.transform.rotation.w = qw

        self.br.sendTransform(t)  # latched on /tf_static -> sending once is enough
        rospy.loginfo(f"Static TF {self.parent_frame} -> {self.child_frame}: "
                      f"xyz={self.translation} rpy={self.rpy}")
        rospy.spin()


if __name__ == '__main__':
    try:
        node = TFBroadcasterNode()
        node.broadcast()
    except rospy.ROSInterruptException:
        pass

src/mpu6050_driver/launch/mpu6050.launch

<launch>
  <!-- MPU6050 IMU publisher -> /imu/data_raw (sensor_msgs/Imu, frame: imu_link) -->
  <node name="mpu6050_publisher" pkg="mpu6050_driver" type="mpu6050_publisher.py" output="screen">
    <param name="i2c_bus" value="1"/>                <!-- /dev/i2c-1 : pin 3 (SDA), pin 5 (SCL) -->
    <param name="i2c_address" value="0x68"/>         <!-- 0x69 if AD0 is tied to 3.3V -->
    <param name="frame_id" value="imu_link"/>
    <param name="rate" value="50"/>                  <!-- Hz -->
    <param name="calibration_samples" value="200"/>  <!-- gyro bias at start-up, 0 = off -->
  </node>

  <!-- Static TF base_link -> imu_link (mpu6050.launch already includes it:
       do NOT include tf_broadcaster.launch again in another launch file) -->
  <include file="$(find mpu6050_driver)/launch/tf_broadcaster.launch"/>
</launch>

src/mpu6050_driver/launch/tf_broadcaster.launch

<launch>
  <!-- Static TF base_link -> imu_link
       Set x/y/z [m] and roll/pitch/yaw [rad] to where the MPU6050 is mounted on the robot. -->
  <node name="imu_tf_broadcaster" pkg="mpu6050_driver" type="tf_broadcaster.py" output="screen">
    <param name="parent_frame" value="base_link"/>
    <param name="child_frame" value="imu_link"/>
    <param name="x" value="0.0"/>
    <param name="y" value="0.0"/>
    <param name="z" value="0.0"/>
    <param name="roll" value="0.0"/>
    <param name="pitch" value="0.0"/>
    <param name="yaw" value="0.0"/>
  </node>
</launch>

7.2 motor_control: ESP32 모터, 장애물 회피 (#9, #10, #11)

src/motor_control/package.xml

<?xml version="1.0"?>
<package format="2">
  <name>motor_control</name>
  <version>1.0.0</version>
  <description>
    Motor control over USB serial to an ESP32 (F/B/L/R/S commands on /motor_command)
    and LiDAR-based obstacle avoidance (stop / go forward).
  </description>
  <maintainer email="minseok1270@gmail.com">mseokq23</maintainer>
  <license>Apache-2.0</license>

  <buildtool_depend>catkin</buildtool_depend>

  <depend>rospy</depend>
  <depend>std_msgs</depend>
  <depend>sensor_msgs</depend>

  <exec_depend>python3-serial</exec_depend>
</package>

src/motor_control/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(motor_control)

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  sensor_msgs
)

catkin_package()

catkin_install_python(PROGRAMS
  scripts/motor_control_node.py
  scripts/obstacle_avoidance_node.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

install(DIRECTORY launch
  DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)

src/motor_control/scripts/motor_control_node.py

#!/usr/bin/env python3
"""
Motor control node: /motor_command -> USB serial -> ESP32     [Jetson Project #9 -> final]

Subscribes  /motor_command (std_msgs/String)
            "F" forward, "B" backward, "L" left, "R" right, "S" stop
            (words also work: forward / backward / left / right / stop)
Writes the single character to the ESP32 (115200 baud, see firmware/).

Changes from the blog version
  * keeps re-sending the last command (~resend_rate). The ESP32 firmware stops the
    motors if nothing arrives for 1 s, so the robot stops when this node dies or the
    USB cable comes off (before: it kept driving with the last command forever).
  * sends "S" when the node shuts down (Ctrl+C)
  * re-opens the serial port if the ESP32 is unplugged / reset
  * no crash when the port is missing at start-up (it keeps retrying)

Parameters
  ~serial_port (str,   /dev/ttyACM0)   ESP32 (USB CDC). The RPLIDAR is on /dev/ttyUSB0
  ~baud_rate   (int,   115200)
  ~resend_rate (float, 5.0)            Hz, 0 = only send when a command arrives
"""
import threading

import rospy
import serial
from std_msgs.msg import String

VALID_COMMANDS = ('F', 'B', 'L', 'R', 'S')
ALIASES = {'FORWARD': 'F', 'BACKWARD': 'B', 'BACK': 'B',
           'LEFT': 'L', 'RIGHT': 'R', 'STOP': 'S'}


class MotorControlNode:
    def __init__(self):
        rospy.init_node('motor_control_node')

        self.serial_port = rospy.get_param('~serial_port', '/dev/ttyACM0')  # Update as needed
        self.baud_rate = int(rospy.get_param('~baud_rate', 115200))
        resend_rate = float(rospy.get_param('~resend_rate', 5.0))

        self.ser = None
        self.lock = threading.Lock()
        self.last_command = 'S'
        self.closed = False  # set on shutdown: no more writes / reconnects

        self.connect()

        rospy.Subscriber('motor_command', String, self.command_callback, queue_size=10)
        rospy.on_shutdown(self.shutdown)
        if resend_rate > 0:
            rospy.Timer(rospy.Duration(1.0 / resend_rate), self.resend_callback)

    # ---------------------------------------------------------------- serial
    def connect(self):
        try:
            self.ser = serial.Serial(self.serial_port, self.baud_rate, timeout=1, write_timeout=1)
            rospy.loginfo(f"Connected to ESP32 on {self.serial_port} at {self.baud_rate} baud.")
            return True
        except serial.SerialException as e:
            self.ser = None
            rospy.logerr_throttle(5.0, f"Failed to connect to ESP32 on {self.serial_port}: {e}")
            return False

    def send(self, command):
        with self.lock:
            if self.closed:
                return False
            if self.ser is None and not self.connect():
                return False
            try:
                self.ser.write(command.encode())
                return True
            except (serial.SerialException, OSError) as e:
                rospy.logerr_throttle(5.0, f"Failed to send command: {e} (reconnecting)")
                try:
                    self.ser.close()
                except Exception:
                    pass
                self.ser = None
                return False

    # ------------------------------------------------------------- callbacks
    def command_callback(self, msg):
        raw = msg.data.strip().upper()
        command = ALIASES.get(raw, raw)
        if command not in VALID_COMMANDS:
            rospy.logwarn(f"Received unknown command: {msg.data}")
            return
        self.last_command = command
        rospy.loginfo(f"Sending command to ESP32: {command}")
        self.send(command)

    def resend_callback(self, _event):
        # keep-alive for the ESP32 watchdog
        self.send(self.last_command)

    def shutdown(self):
        rospy.loginfo("motor_control_node shutting down -> stop motors")
        self.last_command = 'S'
        self.send('S')
        with self.lock:
            self.closed = True  # the resend timer may still fire during shutdown
            if self.ser is not None:
                self.ser.close()
                self.ser = None

    def run(self):
        rospy.spin()


if __name__ == '__main__':
    try:
        node = MotorControlNode()
        node.run()
    except rospy.ROSInterruptException:
        pass

src/motor_control/scripts/obstacle_avoidance_node.py

#!/usr/bin/env python3
"""
Obstacle avoidance node: /scan -> /motor_command     [Jetson Project #10 -> #11 (fix) -> final]

Looks at the front sector (+-30 deg) of the RPLIDAR scan
  closest obstacle <  obstacle_distance               -> "S" (stop)
  closest obstacle >= obstacle_distance + hysteresis  -> "F" (go forward)

Changes from the blog version (#11 is the base; #10 crashed on rospy.is_num)
  * the first command is sent right away (before: nothing was sent until the first
    obstacle appeared, so the robot never started by itself)
  * latched publisher -> the command is not lost if motor_control_node starts later
  * hysteresis -> no S/F/S/F chattering when an obstacle sits right at the threshold
  * no scan for ~scan_timeout seconds (LiDAR unplugged) -> "S"
  * readings outside [range_min, range_max] are ignored, angles are normalized
  * distance log throttled to 1 Hz

Parameters
  ~obstacle_distance (float, 0.5)  m   robot diameter 0.4 m -> 0.2 m radius + 0.3 m margin
  ~hysteresis        (float, 0.1)  m
  ~front_angle_deg   (float, 30.0)     half width of the front sector
  ~scan_timeout      (float, 1.0)  s
  ~scan_topic        (str, /scan)
  ~command_topic     (str, /motor_command)
"""
import math

import rospy
from sensor_msgs.msg import LaserScan
from std_msgs.msg import String


def front_min_distance(scan, half_angle):
    """Closest valid range within +-half_angle [rad] around the laser x-axis (front)."""
    min_distance = float('inf')
    for i, r in enumerate(scan.ranges):
        if not (math.isfinite(r) and scan.range_min <= r <= scan.range_max):
            continue  # NaN / inf / too close / too far
        angle = scan.angle_min + i * scan.angle_increment
        angle = math.atan2(math.sin(angle), math.cos(angle))  # normalize to [-pi, pi]
        if -half_angle <= angle <= half_angle and r < min_distance:
            min_distance = r
    return min_distance


class ObstacleAvoidanceNode:
    def __init__(self):
        rospy.init_node('obstacle_avoidance_node')

        # Parameters
        self.obstacle_distance = float(rospy.get_param('~obstacle_distance', 0.5))  # meters
        self.hysteresis = float(rospy.get_param('~hysteresis', 0.1))
        self.front_angle = math.radians(float(rospy.get_param('~front_angle_deg', 30.0)))
        self.scan_timeout = float(rospy.get_param('~scan_timeout', 1.0))
        self.scan_topic = rospy.get_param('~scan_topic', '/scan')
        self.command_topic = rospy.get_param('~command_topic', '/motor_command')

        # Publisher to motor_command (latched: a late subscriber still gets the last command)
        self.motor_pub = rospy.Publisher(self.command_topic, String, queue_size=10, latch=True)

        # State: None = unknown (first scan), True = stopped by obstacle, False = moving
        self.obstacle_detected = None
        self.last_scan_time = None

        rospy.Subscriber(self.scan_topic, LaserScan, self.scan_callback, queue_size=1)
        rospy.Timer(rospy.Duration(0.2), self.watchdog_callback)

    def scan_callback(self, scan_data):
        self.last_scan_time = rospy.Time.now()
        min_distance = front_min_distance(scan_data, self.front_angle)
        rospy.loginfo_throttle(1.0, f"Minimum distance in front: {min_distance:.2f} meters")

        if self.obstacle_detected:  # currently stopped -> need a bit more room to go again
            blocked = min_distance < self.obstacle_distance + self.hysteresis
        else:                       # moving / first scan
            blocked = min_distance < self.obstacle_distance

        if blocked and self.obstacle_detected is not True:
            rospy.logwarn("Obstacle detected! Stopping.")
            self.motor_pub.publish('S')
        elif not blocked and self.obstacle_detected is not False:
            rospy.loginfo("Path clear. Moving forward.")
            self.motor_pub.publish('F')
        self.obstacle_detected = blocked

    def watchdog_callback(self, _event):
        if self.last_scan_time is None:
            return
        if (rospy.Time.now() - self.last_scan_time).to_sec() > self.scan_timeout:
            if self.obstacle_detected is not True:
                rospy.logerr(f"No LiDAR data on {self.scan_topic} for {self.scan_timeout:.1f}s -> stop")
                self.motor_pub.publish('S')
            self.obstacle_detected = True

    def run(self):
        rospy.spin()


if __name__ == '__main__':
    try:
        node = ObstacleAvoidanceNode()
        node.run()
    except rospy.ROSInterruptException:
        pass

src/motor_control/launch/motor_control.launch

<launch>
  <!-- ESP32 serial port: ESP32 shows up as USB CDC (/dev/ttyACM0), RPLIDAR is /dev/ttyUSB0 -->
  <arg name="serial_port" default="/dev/ttyACM0"/>
  <arg name="baud_rate" default="115200"/>

  <node name="motor_control_node" pkg="motor_control" type="motor_control_node.py" output="screen">
    <param name="serial_port" value="$(arg serial_port)"/>
    <param name="baud_rate" value="$(arg baud_rate)"/>
    <param name="resend_rate" value="5.0"/>  <!-- keep-alive for the ESP32 watchdog (Hz) -->
  </node>
</launch>

src/motor_control/launch/obstacle_avoidance.launch

<launch>
  <node name="obstacle_avoidance_node" pkg="motor_control" type="obstacle_avoidance_node.py" output="screen">
    <!-- Parameters -->
    <param name="obstacle_distance" value="0.5"/>  <!-- meters -->
    <param name="hysteresis" value="0.1"/>         <!-- meters -->
    <param name="front_angle_deg" value="30.0"/>   <!-- +-30 deg front sector -->
    <param name="scan_timeout" value="1.0"/>       <!-- seconds without /scan -> stop -->
    <param name="scan_topic" value="/scan"/>
    <param name="command_topic" value="/motor_command"/>
  </node>
</launch>

7.3 exploration: 매핑용 random walk (#17)

src/exploration/package.xml

<?xml version="1.0"?>
<package format="2">
  <name>exploration</name>
  <version>1.0.0</version>
  <description>
    Simple random-walk exploration for autonomous mapping: drive forward,
    stop and turn left/right at random when the LiDAR sees an obstacle.
  </description>
  <maintainer email="minseok1270@gmail.com">mseokq23</maintainer>
  <license>Apache-2.0</license>

  <buildtool_depend>catkin</buildtool_depend>

  <depend>rospy</depend>
  <depend>std_msgs</depend>
  <depend>sensor_msgs</depend>
</package>

src/exploration/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(exploration)

find_package(catkin REQUIRED COMPONENTS
  rospy
  std_msgs
  sensor_msgs
)

catkin_package()

catkin_install_python(PROGRAMS
  scripts/exploration_node.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

install(DIRECTORY launch
  DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)

src/exploration/scripts/exploration_node.py

#!/usr/bin/env python3
"""
Exploration node (random walk) for autonomous mapping    [Jetson Project #17 -> final]

  drive forward
  obstacle within obstacle_distance in front -> stop (stop_time)
  -> turn left or right at random (at least turn_time, until the front is clear)
  -> drive forward again

Changes from the blog version
  * the front is found from the scan angles. data.ranges[0:10] / [-10:] was the
    *rear* of the RPLIDAR (its scan runs from -pi to +pi, 0 rad = front = middle index)
  * inf / NaN / 0 readings are ignored (before, min() could pick 0.0 or crash)
  * non-blocking state machine on a timer. rospy.sleep() inside the scan callback
    blocked it and piled up old scans
  * keeps turning until the front is clear instead of driving into the obstacle again
  * no scan for ~scan_timeout -> stop; "S" on shutdown
  * run it INSTEAD of obstacle_avoidance_node (both write /motor_command)

Parameters
  ~obstacle_distance (float, 0.5) m    ~front_angle_deg (float, 30.0)
  ~stop_time         (float, 1.0) s    ~turn_time       (float, 1.0) s
  ~scan_timeout      (float, 1.0) s
  ~scan_topic (str, /scan)             ~command_topic   (str, /motor_command)
"""
import math
import random

import rospy
from sensor_msgs.msg import LaserScan
from std_msgs.msg import String


def front_min_distance(scan, half_angle):
    """Closest valid range within +-half_angle [rad] around the laser x-axis (front)."""
    min_distance = float('inf')
    for i, r in enumerate(scan.ranges):
        if not (math.isfinite(r) and scan.range_min <= r <= scan.range_max):
            continue
        angle = scan.angle_min + i * scan.angle_increment
        angle = math.atan2(math.sin(angle), math.cos(angle))  # normalize to [-pi, pi]
        if -half_angle <= angle <= half_angle and r < min_distance:
            min_distance = r
    return min_distance


class ExplorationNode:
    FORWARD = 'FORWARD'
    STOPPING = 'STOPPING'
    TURNING = 'TURNING'

    def __init__(self):
        rospy.init_node('exploration_node')

        self.obstacle_distance = float(rospy.get_param('~obstacle_distance', 0.5))  # meters
        self.front_angle = math.radians(float(rospy.get_param('~front_angle_deg', 30.0)))
        self.stop_time = float(rospy.get_param('~stop_time', 1.0))
        self.turn_time = float(rospy.get_param('~turn_time', 1.0))
        self.scan_timeout = float(rospy.get_param('~scan_timeout', 1.0))
        scan_topic = rospy.get_param('~scan_topic', '/scan')
        command_topic = rospy.get_param('~command_topic', '/motor_command')

        self.cmd_pub = rospy.Publisher(command_topic, String, queue_size=10, latch=True)

        self.min_distance = float('inf')
        self.last_scan_time = None
        self.state = None
        self.state_start = rospy.Time.now()
        self.turn_direction = 'L'
        self.current_command = None

        rospy.Subscriber(scan_topic, LaserScan, self.scan_callback, queue_size=1)
        rospy.Timer(rospy.Duration(0.1), self.control_loop)  # 10 Hz
        rospy.on_shutdown(self.shutdown)

    # ------------------------------------------------------------------ helpers
    def publish(self, command):
        if command != self.current_command:
            self.cmd_pub.publish(command)
            self.current_command = command

    def set_state(self, state):
        if state != self.state:
            rospy.loginfo(f"[exploration] {self.state} -> {state} (front: {self.min_distance:.2f} m)")
        self.state = state
        self.state_start = rospy.Time.now()

    # ---------------------------------------------------------------- callbacks
    def scan_callback(self, data):
        self.min_distance = front_min_distance(data, self.front_angle)
        self.last_scan_time = rospy.Time.now()

    def control_loop(self, _event):
        now = rospy.Time.now()

        # Safety: no LiDAR data -> stop
        if self.last_scan_time is None or (now - self.last_scan_time).to_sec() > self.scan_timeout:
            rospy.logwarn_throttle(2.0, "[exploration] waiting for /scan ... (stopped)")
            self.publish('S')
            self.state = None
            return

        elapsed = (now - self.state_start).to_sec()
        blocked = self.min_distance < self.obstacle_distance

        if self.state in (None, self.FORWARD):
            if blocked:
                self.set_state(self.STOPPING)          # 1) obstacle -> stop
                self.publish('S')
            else:
                if self.state is None:
                    self.set_state(self.FORWARD)
                self.publish('F')                      # path clear -> forward

        elif self.state == self.STOPPING:
            self.publish('S')
            if elapsed >= self.stop_time:              # 2) choose a random direction
                self.turn_direction = random.choice(['L', 'R'])
                self.set_state(self.TURNING)
                self.publish(self.turn_direction)

        elif self.state == self.TURNING:
            self.publish(self.turn_direction)          # 3) turn until the front is clear
            if elapsed >= self.turn_time and not blocked:
                self.set_state(self.FORWARD)
                self.publish('F')

    def shutdown(self):
        self.cmd_pub.publish('S')

    def run(self):
        rospy.spin()


if __name__ == '__main__':
    try:
        node = ExplorationNode()
        node.run()
    except rospy.ROSInterruptException:
        pass

src/exploration/launch/exploration.launch

<launch>
  <!-- Random-walk exploration for mapping.
       Do not run obstacle_avoidance at the same time (both publish /motor_command). -->
  <node name="exploration_node" pkg="exploration" type="exploration_node.py" output="screen">
    <param name="obstacle_distance" value="0.5"/>  <!-- meters -->
    <param name="front_angle_deg" value="30.0"/>
    <param name="stop_time" value="1.0"/>          <!-- seconds -->
    <param name="turn_time" value="1.0"/>          <!-- seconds (minimum turn) -->
    <param name="scan_timeout" value="1.0"/>
  </node>
</launch>

7.4 robot_bringup: launch 파일, 맵 자동 저장 (#14, #16, Project2#4)

src/robot_bringup/package.xml

<?xml version="1.0"?>
<package format="2">
  <name>robot_bringup</name>
  <version>1.0.0</version>
  <description>
    Launch files for the Jetson Nano robot: sensors + motors (bringup.launch),
    Hector SLAM mapping (hector_mapping.launch / mapping.launch) and the map autosaver.
  </description>
  <maintainer email="minseok1270@gmail.com">mseokq23</maintainer>
  <license>Apache-2.0</license>

  <buildtool_depend>catkin</buildtool_depend>

  <exec_depend>rospy</exec_depend>
  <exec_depend>nav_msgs</exec_depend>
  <exec_depend>tf2_ros</exec_depend>
  <exec_depend>rviz</exec_depend>
  <exec_depend>map_server</exec_depend>
  <exec_depend>python3-numpy</exec_depend>

  <!-- 3rd party (git clone into src/ or apt install ros-noetic-...) -->
  <exec_depend>rplidar_ros</exec_depend>
  <exec_depend>hector_mapping</exec_depend>
  <exec_depend>hector_geotiff_launch</exec_depend>
  <exec_depend>hector_slam_launch</exec_depend>

  <!-- this repository -->
  <exec_depend>mpu6050_driver</exec_depend>
  <exec_depend>motor_control</exec_depend>
  <exec_depend>exploration</exec_depend>
</package>

src/robot_bringup/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(robot_bringup)

find_package(catkin REQUIRED)

catkin_package()

catkin_install_python(PROGRAMS
  scripts/map_autosaver.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

install(DIRECTORY launch rviz
  DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)

src/robot_bringup/launch/lidar.launch

<launch>
  <!-- RPLIDAR A1M8: same parameters as rplidar_ros/launch/rplidar_a1.launch
       + the static TF base_link -> laser, which every launch file needs -->
  <arg name="serial_port" default="/dev/ttyUSB0"/>
  <arg name="frame_id" default="laser"/>

  <node name="rplidarNode" pkg="rplidar_ros" type="rplidarNode" output="screen">
    <param name="serial_port"      type="string" value="$(arg serial_port)"/>
    <param name="serial_baudrate"  type="int"    value="115200"/>  <!-- A1 / A2 -->
    <param name="frame_id"         type="string" value="$(arg frame_id)"/>
    <param name="inverted"         type="bool"   value="false"/>
    <param name="angle_compensate" type="bool"   value="true"/>
  </node>

  <!-- base_link -> laser: LiDAR mounted at the robot center
       (args: x y z yaw pitch roll parent child). In Project2#4 this line lived in
       hector_mapping/launch/mapping_default.launch as "map_nav_broadcaster". -->
  <node pkg="tf2_ros" type="static_transform_publisher" name="base_to_laser_broadcaster"
        args="0 0 0 0 0 0 base_link $(arg frame_id)"/>
</launch>

src/robot_bringup/launch/bringup.launch

<launch>
  <!-- Master launch file: LiDAR + IMU + motor control + obstacle avoidance + RViz
       [Jetson Project #14 -> final]
       roslaunch starts roscore by itself if it is not running yet. -->
  <arg name="lidar_port" default="/dev/ttyUSB0"/>
  <arg name="esp32_port" default="/dev/ttyACM0"/>
  <arg name="use_imu" default="true"/>
  <arg name="obstacle_avoidance" default="true"/>
  <arg name="rviz" default="true"/>  <!-- rviz:=false when running headless (SSH) -->

  <!-- Launch RPLIDAR (+ TF base_link -> laser) -->
  <include file="$(find robot_bringup)/launch/lidar.launch">
    <arg name="serial_port" value="$(arg lidar_port)"/>
  </include>

  <!-- Launch IMU. mpu6050.launch already includes tf_broadcaster.launch,
       including it here again gives "multiple nodes named [/imu_tf_broadcaster]" (#14) -->
  <include if="$(arg use_imu)" file="$(find mpu6050_driver)/launch/mpu6050.launch"/>

  <!-- Launch Motor Control -->
  <include file="$(find motor_control)/launch/motor_control.launch">
    <arg name="serial_port" value="$(arg esp32_port)"/>
  </include>

  <!-- Launch Obstacle Avoidance -->
  <include if="$(arg obstacle_avoidance)" file="$(find motor_control)/launch/obstacle_avoidance.launch"/>

  <!-- Launch RViz -->
  <node if="$(arg rviz)" name="rviz" pkg="rviz" type="rviz"
        args="-d $(find robot_bringup)/rviz/robot.rviz" required="true"/>
</launch>

src/robot_bringup/launch/hector_mapping.launch

<launch>
  <!-- Hector SLAM with the settings that produced the final map in Project2 #4.
       Before, these edits were made inside the cloned hector_slam repo:
         hector_slam_launch/launch/tutorial.launch      : /use_sim_time true -> false
         hector_mapping/launch/mapping_default.launch   : base_frame, odom_frame -> base_link
                                                          + static TF base_link -> laser
       Now hector_slam stays untouched (git clone or apt) and everything is here.
       The base_link -> laser TF is published by lidar.launch. -->
  <arg name="rviz" default="true"/>
  <arg name="geotiff" default="true"/>  <!-- /trajectory path in RViz + GeoTIFF writer -->
  <arg name="map_size" default="2048"/>
  <arg name="geotiff_map_file_path" default="$(find hector_geotiff)/maps"/>

  <!-- real robot, real clock (tutorial.launch sets true for bag files) -->
  <param name="/use_sim_time" value="false"/>

  <node pkg="hector_mapping" type="hector_mapping" name="hector_mapping" output="screen">
    <!-- Frame names: no wheel odometry -> odom_frame = base_link -->
    <param name="map_frame" value="map"/>
    <param name="base_frame" value="base_link"/>
    <param name="odom_frame" value="base_link"/>

    <!-- TF use -->
    <param name="use_tf_scan_transformation" value="true"/>
    <param name="use_tf_pose_start_estimate" value="false"/>
    <param name="pub_map_odom_transform" value="true"/>  <!-- publishes map -> base_link -->

    <!-- Map size / start point -->
    <param name="map_resolution" value="0.050"/>
    <param name="map_size" value="$(arg map_size)"/>
    <param name="map_start_x" value="0.5"/>
    <param name="map_start_y" value="0.5"/>
    <param name="map_multi_res_levels" value="2"/>

    <!-- Map update parameters -->
    <param name="update_factor_free" value="0.4"/>
    <param name="update_factor_occupied" value="0.9"/>
    <param name="map_update_distance_thresh" value="0.4"/>
    <param name="map_update_angle_thresh" value="0.06"/>
    <param name="laser_z_min_value" value="-1.0"/>
    <param name="laser_z_max_value" value="1.0"/>

    <!-- Advertising config -->
    <param name="advertise_map_service" value="true"/>
    <param name="scan_subscriber_queue_size" value="5"/>
    <param name="scan_topic" value="scan"/>
    <param name="tf_map_scanmatch_transform_frame_name" value="scanmatcher_frame"/>
  </node>

  <!-- From tutorial.launch: trajectory server (green path) + GeoTIFF map writer -->
  <include if="$(arg geotiff)" file="$(find hector_geotiff_launch)/launch/geotiff_mapper.launch">
    <arg name="trajectory_source_frame_name" value="scanmatcher_frame"/>
    <arg name="map_file_path" value="$(arg geotiff_map_file_path)"/>
  </include>

  <node if="$(arg rviz)" pkg="rviz" type="rviz" name="rviz"
        args="-d $(find hector_slam_launch)/rviz_cfg/mapping_demo.rviz"/>
</launch>

src/robot_bringup/launch/mapping.launch

<launch>
  <!-- One-command mapping: LiDAR + Hector SLAM + RViz
       (+ IMU, motor control, exploration, map autosave)
       [Jetson Project #16 / #17 + Project2 #4 -> final]

       roslaunch robot_bringup mapping.launch                 # map while driving by hand / from the app
       roslaunch robot_bringup mapping.launch explore:=true   # robot explores by itself
       rosrun map_server map_saver -f ~/my_map                # save now (autosave also does it) -->
  <arg name="lidar_port" default="/dev/ttyUSB0"/>
  <arg name="esp32_port" default="/dev/ttyACM0"/>
  <arg name="use_imu" default="true"/>    <!-- IMU for monitoring; hector_mapping uses only the LiDAR -->
  <arg name="motors" default="true"/>     <!-- motor_control_node: needed for explore / app commands -->
  <arg name="explore" default="false"/>   <!-- random-walk exploration -->
  <arg name="autosave" default="true"/>   <!-- ~/my_map every 30 s + ~/maps/map_<time> on shutdown -->
  <arg name="rviz" default="true"/>

  <!-- LiDAR (+ TF base_link -> laser) -->
  <include file="$(find robot_bringup)/launch/lidar.launch">
    <arg name="serial_port" value="$(arg lidar_port)"/>
  </include>

  <!-- IMU (+ TF base_link -> imu_link) -->
  <include if="$(arg use_imu)" file="$(find mpu6050_driver)/launch/mpu6050.launch"/>

  <!-- Hector SLAM (+ RViz mapping_demo.rviz) -->
  <include file="$(find robot_bringup)/launch/hector_mapping.launch">
    <arg name="rviz" value="$(arg rviz)"/>
  </include>

  <!-- Motors -->
  <include if="$(arg motors)" file="$(find motor_control)/launch/motor_control.launch">
    <arg name="serial_port" value="$(arg esp32_port)"/>
  </include>

  <!-- Exploration replaces obstacle_avoidance while mapping (both write /motor_command) -->
  <include if="$(arg explore)" file="$(find exploration)/launch/exploration.launch"/>

  <!-- Map autosave -->
  <node if="$(arg autosave)" name="map_autosaver" pkg="robot_bringup" type="map_autosaver.py" output="screen">
    <param name="path" value="~/my_map"/>
    <param name="archive_dir" value="~/maps"/>
    <param name="interval" value="30.0"/>
  </node>
</launch>

src/robot_bringup/scripts/map_autosaver.py

#!/usr/bin/env python3
"""
Map autosaver                                                   [NEW in the final code]

Project goal #5 (Jetson Project #1): "regularly save the SLAM map and automatically
save the final map to the home directory". The map_saver node in #16's launch file
saved the map only once, right after start-up, so this node does it properly:

  * every ~interval seconds  -> ~path.pgm / ~path.yaml   (default ~/my_map, the same
                                file the Flask API server sends to the app)
  * on shutdown (Ctrl+C)     -> the same file + a time-stamped copy in ~archive_dir
                                (default ~/maps/map_YYYYmmdd_HHMMSS.pgm/.yaml)

Output is identical to `rosrun map_server map_saver -f <path>` (trinary PGM:
free 254 / occupied 0 / unknown 205, thresholds occ 65 % / free 25 %).
It works from the last received /map, so it still saves when hector_mapping
shuts down at the same time.

Parameters
  ~map_topic   (str,   /map)
  ~path        (str,   ~/my_map)
  ~archive_dir (str,   ~/maps)      "" = no archive copy
  ~interval    (float, 30.0)        seconds, 0 = only on shutdown
  ~occupied_thresh (int, 65)  ~free_thresh (int, 25)
"""
import math
import os
import time

import numpy as np
import rospy
from nav_msgs.msg import OccupancyGrid
from rospy.numpy_msg import numpy_msg


def yaw_from_quaternion(q):
    return math.atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z))


def write_atomic(path, data, mode='wb'):
    tmp = path + '.tmp'
    with open(tmp, mode) as f:
        f.write(data)
    os.replace(tmp, path)  # readers never see a half-written file


def save_map(msg, base_path, occupied_thresh=65, free_thresh=25):
    """Write <base_path>.pgm and <base_path>.yaml like map_server/map_saver."""
    width, height = msg.info.width, msg.info.height
    grid = np.asarray(msg.data, dtype=np.int8).reshape(height, width)

    image = np.full((height, width), 205, dtype=np.uint8)            # unknown
    image[(grid >= 0) & (grid <= free_thresh)] = 254                  # free
    image[grid >= occupied_thresh] = 0                                # occupied
    image = np.flipud(image)                                          # row 0 = top of the image

    pgm_path, yaml_path = base_path + '.pgm', base_path + '.yaml'
    header = (f"P5\n# CREATOR: map_autosaver.py {msg.info.resolution:.3f} m/pix\n"
              f"{width} {height}\n255\n").encode('ascii')
    write_atomic(pgm_path, header + image.tobytes())

    origin = msg.info.origin
    yaml_text = (f"image: {os.path.basename(pgm_path)}\n"
                 f"resolution: {msg.info.resolution:f}\n"
                 f"origin: [{origin.position.x:f}, {origin.position.y:f}, "
                 f"{yaw_from_quaternion(origin.orientation):f}]\n"
                 f"negate: 0\noccupied_thresh: 0.65\nfree_thresh: 0.196\n\n")
    write_atomic(yaml_path, yaml_text, mode='w')
    return pgm_path


class MapAutosaver:
    def __init__(self):
        rospy.init_node('map_autosaver')
        self.path = os.path.expanduser(rospy.get_param('~path', '~/my_map'))
        self.archive_dir = os.path.expanduser(rospy.get_param('~archive_dir', '~/maps'))
        self.interval = float(rospy.get_param('~interval', 30.0))
        self.occupied_thresh = int(rospy.get_param('~occupied_thresh', 65))
        self.free_thresh = int(rospy.get_param('~free_thresh', 25))

        os.makedirs(os.path.dirname(self.path) or '.', exist_ok=True)
        self.latest = None
        self.saved_stamp = None

        rospy.Subscriber(rospy.get_param('~map_topic', '/map'), numpy_msg(OccupancyGrid),
                         self.map_callback, queue_size=1)
        if self.interval > 0:
            rospy.Timer(rospy.Duration(self.interval), self.timer_callback)
        rospy.on_shutdown(self.shutdown)
        rospy.loginfo(f"map_autosaver: saving to {self.path}.pgm every {self.interval:.0f}s and on shutdown")

    def map_callback(self, msg):
        self.latest = msg

    def save(self, base_path):
        msg = self.latest
        if msg is None:
            return None
        pgm = save_map(msg, base_path, self.occupied_thresh, self.free_thresh)
        self.saved_stamp = msg.header.stamp
        rospy.loginfo(f"Map saved: {pgm} ({msg.info.width}x{msg.info.height} @ {msg.info.resolution:.3f} m/pix)")
        return pgm

    def timer_callback(self, _event):
        if self.latest is not None and self.latest.header.stamp != self.saved_stamp:
            try:
                self.save(self.path)
            except Exception as e:
                rospy.logerr(f"map_autosaver: save failed: {e}")

    def shutdown(self):
        if self.latest is None:
            print("map_autosaver: no map received, nothing to save")
            return
        try:
            self.save(self.path)
            if self.archive_dir:
                os.makedirs(self.archive_dir, exist_ok=True)
                name = time.strftime('map_%Y%m%d_%H%M%S')
                self.save(os.path.join(self.archive_dir, name))
        except Exception as e:
            print(f"map_autosaver: final save failed: {e}")


if __name__ == '__main__':
    try:
        MapAutosaver()
        rospy.spin()
    except rospy.ROSInterruptException:
        pass

src/robot_bringup/rviz/robot.rviz(bringup.launch용 RViz 설정)는 맨 아래 부록에 있음.

7.5 ESP32 펌웨어 (#9)

firmware/esp32_motor_control/esp32_motor_control.ino

/*
 * ESP32 motor controller for the Jetson Nano robot        [Jetson Project #9 -> final]
 *
 * Board  : ESP32-WROOM-32D DevKit (Arduino IDE, board "ESP32 Dev Module")
 * Driver : L298N (or TB6612FNG) + 2 DC motors
 * Link   : USB serial to the Jetson Nano, 115200 baud (/dev/ttyACM0 on the Jetson)
 *
 * Protocol: one ASCII character per command (sent by motor_control_node.py)
 *   'F' forward   'B' backward   'L' turn left   'R' turn right   'S' stop
 *
 * Changes from the blog version
 *   - '\n', '\r' and ' ' are ignored. Sending "F" + Enter from the Serial Monitor
 *     used to drive forward and immediately stop again on the '\n'.
 *   - lower-case commands work too
 *   - watchdog: no command for COMMAND_TIMEOUT_MS -> stop the motors
 *     (motor_control_node re-sends the last command 5 times per second, so the robot
 *      only stops by itself when the Jetson / ROS node dies or the cable comes off)
 *   - speed constants and one setMotors() helper
 */

// Motor Control Pins (L298N)
const int motorAForward  = 5;   // IN1
const int motorABackward = 18;  // IN2
const int motorBForward  = 19;  // IN3
const int motorBBackward = 21;  // IN4
const int motorASpeed    = 22;  // ENA (PWM)
const int motorBSpeed    = 23;  // ENB (PWM)

const int DRIVE_SPEED = 255;                    // 0-255, forward / backward
const int TURN_SPEED  = 255;                    // 0-255, turning in place
const unsigned long COMMAND_TIMEOUT_MS = 1000;  // 0 = watchdog off

char currentCommand = 'S';
unsigned long lastCommandMs = 0;

// dirA / dirB: 1 = forward, -1 = backward, 0 = stop
void setMotors(int dirA, int dirB, int speed) {
  digitalWrite(motorAForward,  dirA > 0 ? HIGH : LOW);
  digitalWrite(motorABackward, dirA < 0 ? HIGH : LOW);
  digitalWrite(motorBForward,  dirB > 0 ? HIGH : LOW);
  digitalWrite(motorBBackward, dirB < 0 ? HIGH : LOW);

  analogWrite(motorASpeed, dirA == 0 ? 0 : speed);
  analogWrite(motorBSpeed, dirB == 0 ? 0 : speed);
}

void moveForward()  { setMotors( 1,  1, DRIVE_SPEED); }
void moveBackward() { setMotors(-1, -1, DRIVE_SPEED); }
void turnLeft()     { setMotors(-1,  1, TURN_SPEED);  }  // A backward, B forward
void turnRight()    { setMotors( 1, -1, TURN_SPEED);  }  // A forward, B backward
void stopMotors()   { setMotors( 0,  0, 0);           }

void applyCommand(char command) {
  switch (command) {
    case 'F': moveForward();  break;
    case 'B': moveBackward(); break;
    case 'L': turnLeft();     break;
    case 'R': turnRight();    break;
    case 'S': stopMotors();   break;
    default:                       // unknown command -> stop (same as before)
      stopMotors();
      command = 'S';
      break;
  }
  currentCommand = command;
}

void setup() {
  // Initialize serial communication (same baud rate as motor_control_node)
  Serial.begin(115200);

  // Initialize motor control pins
  pinMode(motorAForward, OUTPUT);
  pinMode(motorABackward, OUTPUT);
  pinMode(motorBForward, OUTPUT);
  pinMode(motorBBackward, OUTPUT);
  pinMode(motorASpeed, OUTPUT);
  pinMode(motorBSpeed, OUTPUT);

  // Stop motors initially
  stopMotors();
}

void loop() {
  while (Serial.available() > 0) {
    char command = (char)Serial.read();
    if (command == '\n' || command == '\r' || command == ' ') {
      continue;  // ignore line endings
    }
    if (command >= 'a' && command <= 'z') {
      command = command - 'a' + 'A';  // 'f' -> 'F'
    }
    lastCommandMs = millis();
    applyCommand(command);
  }

  // Watchdog: the Jetson stopped talking -> stop
  if (COMMAND_TIMEOUT_MS > 0 && currentCommand != 'S' &&
      millis() - lastCommandMs > COMMAND_TIMEOUT_MS) {
    stopMotors();
    currentCommand = 'S';
  }
}

7.6 앱 서버: Flask, ngrok (Project2#4)

server/map_api_server.py

#!/usr/bin/env python3
"""
Robot map API server for the Flutter app     [Jetson Project2 #4 (server_2.py) -> final]

    Flutter app --HTTPS--> ngrok (https://<name>.ngrok.io) --> this server :5000 --> ROS

Endpoints ([key] = needs the "x-api-key" header)
  POST /save_map  [key]  {"command": "save_map"}
                         rosrun map_server map_saver -f ~/my_map -> ~/my_map.pgm/.yaml -> ~/my_map.png
  GET  /image            current map (~/my_map.pgm) as PNG
  POST /picture          upload a .png (multipart field "image") into UPLOAD_FOLDER
  GET  /uploads/<name>   download an uploaded .png
  POST /command   [key]  {"command": "F"|"B"|"L"|"R"|"S"}  (or forward/backward/left/right/stop)  NEW
  POST /mapping   [key]  {"action": "start"|"stop", "explore": false}                              NEW
                         start/stop "roslaunch robot_bringup mapping.launch rviz:=false"
  GET  /status           ROS master / mapping / map file status                                  NEW

Changes from server_2.py
  * API key comes from the ROBOT_API_KEY environment variable (it was hard-coded in the post)
  * UPLOAD_FOLDER is defined (it was never set -> /picture and /uploads raised KeyError)
  * uploaded file names go through secure_filename() (no "../../" path traversal)
  * map_saver runs without a shell, with a timeout, and a stale ~/my_map.pgm from an
    earlier save no longer counts as success
  * paths use the current user's home instead of /home/jetson; run it WITHOUT sudo
    (with sudo, ~ becomes /root and the map is written to the wrong place)

Run (ROS environment sourced):
    export ROBOT_API_KEY='<long random string, same as in the app>'
    python3 map_api_server.py
    ngrok http --url=<your-domain>.ngrok.io 5000
"""
import atexit
import hmac
import io
import os
import signal
import subprocess
import sys
import threading
import time
from functools import wraps

from flask import Flask, jsonify, request, send_file, send_from_directory
from PIL import Image
from werkzeug.utils import secure_filename

# ------------------------------------------------------------------ configuration
API_KEY = os.environ.get('ROBOT_API_KEY', '')
MAP_BASE = os.path.expanduser(os.environ.get('MAP_BASE', '~/my_map'))
PGM_PATH = MAP_BASE + '.pgm'
PNG_PATH = MAP_BASE + '.png'
UPLOAD_FOLDER = os.path.expanduser(os.environ.get('UPLOAD_FOLDER', '~/uploads'))
MAP_SAVER_TIMEOUT = 60  # seconds
MAPPING_LAUNCH = ['roslaunch', 'robot_bringup', 'mapping.launch', 'rviz:=false']

VALID_COMMANDS = ('F', 'B', 'L', 'R', 'S')
ALIASES = {'FORWARD': 'F', 'BACKWARD': 'B', 'BACK': 'B',
           'LEFT': 'L', 'RIGHT': 'R', 'STOP': 'S'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16 MB upload limit
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

save_lock = threading.Lock()
mapping_lock = threading.Lock()
ros_lock = threading.Lock()
mapping_state = {'proc': None}
ros_state = {'pub': None, 'String': None}


# ------------------------------------------------------------------ API key
def require_api_key(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if 'x-api-key' not in request.headers:
            return jsonify({"error": "API 키가 필요합니다."}), 401
        if not hmac.compare_digest(request.headers['x-api-key'].encode(), API_KEY.encode()):
            return jsonify({"error": "유효하지 않은 API 키입니다."}), 403
        return f(*args, **kwargs)
    return decorated


# ------------------------------------------------------------------ map saving
def execute_ros_command():
    """Run map_saver and check that it wrote a NEW .pgm file."""
    before = os.path.getmtime(PGM_PATH) if os.path.exists(PGM_PATH) else None
    try:
        result = subprocess.run(['rosrun', 'map_server', 'map_saver', '-f', MAP_BASE],
                                capture_output=True, text=True, timeout=MAP_SAVER_TIMEOUT)
    except FileNotFoundError:
        print("rosrun 을 찾을 수 없습니다. ROS 환경을 source 했는지 확인하세요.")
        return False
    except subprocess.TimeoutExpired:
        print("맵 파일 생성 시간이 초과되었습니다. (/map 토픽이 발행 중인지 확인하세요)")
        return False

    if result.returncode != 0 or not os.path.exists(PGM_PATH):
        print(f"map_saver 실패: {result.stderr.strip()}")
        return False
    if before is not None and os.path.getmtime(PGM_PATH) <= before:
        print("맵 파일이 갱신되지 않았습니다.")
        return False
    return True


@app.route('/save_map', methods=['POST'])
@require_api_key
def save_map():
    """Executes the ROS map_saver command and converts the resulting .pgm file to .png."""
    data = request.get_json(silent=True)
    if not (data and data.get('command') == 'save_map'):
        return jsonify({"status": "error", "message": "유효하지 않은 명령입니다."}), 400

    with save_lock:  # one map_saver at a time
        if not execute_ros_command():
            return jsonify({"status": "error", "message": "맵 저장 명령을 실행하지 못했습니다."}), 500
        try:
            with Image.open(PGM_PATH) as img:
                img.convert('RGB').save(PNG_PATH, 'PNG')
        except Exception as e:
            print(f"PNG 변환 중 오류 발생: {e}")
            return jsonify({"status": "error", "message": "맵을 PNG로 변환하는 데 실패했습니다."}), 500
    return jsonify({"status": "success", "message": "Map saved and converted to PNG"}), 200


@app.route('/image')
def send_image():
    """Current map (.pgm) converted to PNG in memory (called by the Flutter app)."""
    if not os.path.exists(PGM_PATH):
        return jsonify({'error': 'Map file not found'}), 404
    try:
        with Image.open(PGM_PATH) as img:
            img_io = io.BytesIO()
            img.convert('RGB').save(img_io, 'PNG')
        img_io.seek(0)
        return send_file(img_io, mimetype='image/png')
    except Exception as e:
        print(f"Error converting map image: {e}")
        return jsonify({'error': 'Failed to process map image'}), 500


# ------------------------------------------------------------------ uploads
@app.route('/picture', methods=['POST'])
def handle_uploaded_picture():
    if 'image' not in request.files:
        return jsonify({'error': '파일이 없습니다.'}), 400
    file = request.files['image']
    if file.filename == '':
        return jsonify({'error': '파일명이 없습니다.'}), 400

    filename = secure_filename(file.filename)
    if filename and filename.lower().endswith('.png'):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return jsonify({'message': '파일 업로드 성공', 'filename': filename}), 200
    return jsonify({'error': '유효하지 않은 파일 형식입니다. .png 파일을 업로드하세요.'}), 400


@app.route('/uploads/<filename>')
def get_uploaded_picture(filename):
    filename = secure_filename(filename)
    if filename and os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename, mimetype='image/png')
    return jsonify({'error': '파일을 찾을 수 없습니다.'}), 404


# ------------------------------------------------------------------ motor commands (NEW)
def get_motor_publisher():
    """Lazily start a rospy node inside the server; None if roscore is not running."""
    with ros_lock:
        if ros_state['pub'] is None:
            import rosgraph  # ImportError -> ROS environment not sourced
            import rospy
            from std_msgs.msg import String
            if not rosgraph.is_master_online():
                return None
            rospy.init_node('robot_api_server', anonymous=True, disable_signals=True)
            pub = rospy.Publisher('/motor_command', String, queue_size=10)
            deadline = time.time() + 1.0  # give motor_control_node a moment to connect
            while pub.get_num_connections() == 0 and time.time() < deadline:
                time.sleep(0.05)
            ros_state['pub'], ros_state['String'] = pub, String
        return ros_state['pub']


@app.route('/command', methods=['POST'])
@require_api_key
def motor_command():
    data = request.get_json(silent=True) or {}
    raw = str(data.get('command', '')).strip().upper()
    command = ALIASES.get(raw, raw)
    if command not in VALID_COMMANDS:
        return jsonify({"status": "error", "message": "유효하지 않은 명령입니다. (F/B/L/R/S)"}), 400
    try:
        pub = get_motor_publisher()
    except ImportError:
        return jsonify({"status": "error", "message": "ROS 환경이 없습니다. setup.bash 를 source 하세요."}), 503
    if pub is None:
        return jsonify({"status": "error", "message": "roscore 가 실행 중이 아닙니다."}), 503
    pub.publish(ros_state['String'](data=command))
    return jsonify({"status": "success", "command": command}), 200


# ------------------------------------------------------------------ mapping start/stop (NEW)
def mapping_running():
    proc = mapping_state['proc']
    return proc is not None and proc.poll() is None


def stop_mapping(timeout=20):
    proc = mapping_state['proc']
    if proc is None:
        return
    try:
        os.killpg(proc.pid, signal.SIGINT)  # = Ctrl+C: map_autosaver writes the final map
        proc.wait(timeout=timeout)
    except subprocess.TimeoutExpired:
        os.killpg(proc.pid, signal.SIGTERM)
        proc.wait(timeout=5)
    except ProcessLookupError:
        pass
    mapping_state['proc'] = None


@app.route('/mapping', methods=['POST'])
@require_api_key
def mapping():
    data = request.get_json(silent=True) or {}
    action = str(data.get('action', '')).lower()
    with mapping_lock:
        if action == 'start':
            if mapping_running():
                return jsonify({"status": "success", "message": "이미 매핑 중입니다."}), 200
            cmd = MAPPING_LAUNCH + (['explore:=true'] if data.get('explore') else [])
            try:
                mapping_state['proc'] = subprocess.Popen(cmd, start_new_session=True)
            except FileNotFoundError:
                return jsonify({"status": "error", "message": "roslaunch 를 찾을 수 없습니다."}), 503
            return jsonify({"status": "success", "message": "매핑을 시작했습니다."}), 200
        if action == 'stop':
            if not mapping_running():
                mapping_state['proc'] = None
                return jsonify({"status": "success", "message": "매핑 중이 아닙니다."}), 200
            stop_mapping()
            return jsonify({"status": "success", "message": "매핑을 종료했습니다."}), 200
    return jsonify({"status": "error", "message": "action 은 start 또는 stop 이어야 합니다."}), 400


@app.route('/status')
def status():
    try:
        import rosgraph
        master = rosgraph.is_master_online()
    except ImportError:
        master = None
    return jsonify({"status": "ok", "ros_master": master, "mapping": mapping_running(),
                    "map_available": os.path.exists(PGM_PATH)}), 200


# ------------------------------------------------------------------ main
if __name__ == '__main__':
    if not API_KEY:
        sys.exit("ROBOT_API_KEY 환경변수를 먼저 설정하세요.\n"
                 "  export ROBOT_API_KEY=\"$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')\"")
    if os.geteuid() == 0:
        print("경고: sudo 로 실행하면 맵이 /root 에 저장됩니다. 일반 사용자로 실행하세요.")

    def on_exit():
        with mapping_lock:
            if mapping_running():
                stop_mapping()
        print("Flask 서버가 종료됩니다.")

    atexit.register(on_exit)
    # Run the app on all interfaces, port 5000
    app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), threaded=True)

server/requirements.txt

# Ubuntu 20.04 (Jetson):  sudo apt install python3-flask python3-pil
# or:                      pip3 install -r requirements.txt
flask>=1.1
pillow>=7.0

8. API

MethodPathAPI 키Body결과
POST/save_map필요{"command": "save_map"}map_saver 실행, ~/my_map.pgm/.yaml/.png 저장
GET/image현재 맵 PNG
POST/picturemultipart image (.png)~/uploads/에 저장
GET/uploads/<name>업로드한 PNG
POST/command필요{"command": "F"} (F B L R S나 forward 등)/motor_command로 publish
POST/mapping필요{"action": "start"}, {"action": "stop"}mapping.launch rviz:=false 실행, 정지
GET/statusROS master, 매핑 상태, 맵 파일

API 키는 x-api-key: <ROBOT_API_KEY> 헤더로 보냄. /command, /mapping, /status는 새로 추가한 것이고(Project2#1 계획의 5번, 앱에서 명령 보내기) 나머지 route는 server_2.py와 똑같이 동작함.

9. 이전 글과 달라진 점

파일글에서최종 코드
mpu6050_publisher.pyg, deg/s 단위, covariance 0.1에 identity orientation, 샘플마다 로그sensor_msgs/Imu에 맞게 SI 단위(m/s², rad/s), 자이로 bias 캘리브레이션, orientation_covariance[0] = -1, 14바이트 한 번에 읽기, 로그 줄임, 파라미터
tf_broadcaster.py10 Hz dynamic TFstatic TF(/tf_static), 장착 위치를 파라미터로
motor_control_node.py명령이 올 때만 보냄. ESP32가 마지막 명령을 계속 유지마지막 명령을 5 Hz로 다시 보냄(ESP32 watchdog용), 종료할 때 S, 재연결
obstacle_avoidance_node.py#10은 rospy.is_num에서 죽음. #11은 첫 F를 안 보냄#11 로직에 시작하자마자 첫 명령, 히스테리시스, /scan이 끊기면 정지, latched publisher
exploration_node.pyranges[0:10], [-10:]이 RPLIDAR 뒤쪽. callback 안에서 rospy.sleep스캔 각도로 앞쪽 범위 계산, 타이머 상태 머신, 앞이 빌 때까지 회전
esp32_motor_control.ino'\n'이 default:로 가서 정지\r, \n 무시, 소문자도 받음, 1초 watchdog
bringup.launchrobot.rviz 파일이 없었음rviz/robot.rviz 포함, argument, 화면 없을 때 rviz:=false
hector_slam_custom.launch (#16)맵 파라미터가 node 밖에 있어서 무시됨, map_saver가 시작할 때 한 번만 실행Project2#4 설정을 넣은 hector_mapping.launch와 map_autosaver.py
tutorial.launch, mapping_default.launchclone한 hector_slam 안에서 수정hector_slam은 그대로 두고 설정은 robot_bringup에
server_2.py소스에 API 키, UPLOAD_FOLDER 미정의, 파일 이름에 ../ 가능, 예전 파일로 성공 판단, /home/jetson 경로 고정환경 변수에서 키 읽기, 업로드 폴더, secure_filename, 타임아웃 있는 map_saver, $HOME 경로, /command, /mapping, /status 추가

주의) Project2#4의 server_2.py에 있던 API 키가 공개돼 있었음. ngrok authtoken이었다면 ngrok 대시보드에서 재설정하고, 어느 쪽이든 ROBOT_API_KEY는 새 값으로 쓰기.

10. 안 넣은 것 (이유)

  • ROS2 Foxy(serial_communication 노드, ROS2 세팅 글들): 프로젝트를 ROS1 Noetic으로 옮김 (#0)
  • Cartographer(ROS2, #15): Jetson Nano에서 빌드가 안 돼서 Hector SLAM으로 바꿈
  • move_base 자율주행(#18, 제목에 delete): 바퀴 odometry랑 cmd_vel이 필요한데 이 로봇은 엔코더가 없고 ESP32는 F, B, L, R, S 명령을 받음
  • MPU9250(#5): MPU6050으로 바꿈 (#5-1)

11. 트러블슈팅 모음

증상해결
RPLIDAR code: 80008004포트나 권한 문제. ls /dev/ttyUSB*, dialout 그룹, 재부팅
ESP32 Could not open serial portESP32는 /dev/ttyACM0(USB CDC)임. /dev/ttyUSB0은 LiDAR
rostopic list에 /rosout만 나옴노드가 안 돌고 있음. launch 터미널에 traceback이 있는지 확인 (#7)
multiple nodes named [/imu_tf_broadcaster]mpu6050.launch가 이미 tf_broadcaster.launch를 include함 (#14)
i2cdetect에 MPU6050 68이 안 보임배선(3.3V), sudo modprobe i2c-dev (#5-1)
화면 없는 Jetson에서 RVizrviz:=false로 띄우고 RViz는 PC에서 ROS_MASTER_URI 맞춰서 실행
/save_map이 500을 돌려줌매핑이 안 돌고 있거나(/map 없음) 서버를 sudo로 띄움

12. 코드 확인한 방법

  • ROS Noetic(Ubuntu 20.04, Python 3.8)에 ros-noetic-hector-slam, ros-noetic-rplidar-ros를 깔고 catkin_make, catkin_make install.
  • launch 파일은 전부 roslaunch --nodes로 파싱 확인 (위 argument 조합 전부).
  • 가짜 RPLIDAR(4 x 6 m 방의 /scan), 가짜 MPU6050, 가상 ESP32 시리얼 포트로 노드를 돌려봄.
    장애물 회피(첫 F, 0.4 m에서 정지, 히스테리시스, 뒤쪽 장애물 무시, LiDAR가 끊기면 S),
    탐색(정지하고 랜덤 회전 후 전진), IMU(9.81 m/s², bias 제거, 50 Hz), TF tree,
    Hector 매핑 결과로 map_autosaver가 저장한 맵이 map_saver와 똑같은지(픽셀 100 %), API 서버(키, 업로드, /command, /mapping).
  • 원래 #17 탐색 노드를 같은 가짜 LiDAR로 돌려보면 로봇 뒤에 있는 장애물을 보고 멈추고 회전함.
  • ESP32 스케치는 PC에서 컴파일하고 시뮬레이션해봄 (줄바꿈, 소문자, watchdog).
  • 실제 로봇에서 아직 확인할 것: 모터 방향, LiDAR와 IMU 장착 위치, 시리얼 포트.

부록: robot.rviz

src/robot_bringup/rviz/robot.rviz

Panels:
  - Class: rviz/Displays
    Help Height: 78
    Name: Displays
    Property Tree Widget:
      Expanded:
        - /Global Options1
        - /LaserScan1
      Splitter Ratio: 0.5
    Tree Height: 540
  - Class: rviz/Selection
    Name: Selection
  - Class: rviz/Tool Properties
    Expanded:
      - /2D Pose Estimate1
      - /2D Nav Goal1
      - /Publish Point1
    Name: Tool Properties
    Splitter Ratio: 0.588679
  - Class: rviz/Views
    Expanded:
      - /Current View1
    Name: Views
    Splitter Ratio: 0.5
  - Class: rviz/Time
    Experimental: false
    Name: Time
    SyncMode: 0
    SyncSource: LaserScan
Visualization Manager:
  Class: ""
  Displays:
    - Alpha: 0.5
      Cell Size: 1
      Class: rviz/Grid
      Color: 160; 160; 164
      Enabled: true
      Line Style:
        Line Width: 0.03
        Value: Lines
      Name: Grid
      Normal Cell Count: 0
      Offset:
        X: 0
        Y: 0
        Z: 0
      Plane: XY
      Plane Cell Count: 10
      Reference Frame: <Fixed Frame>
      Value: true
    - Class: rviz/TF
      Enabled: true
      Frame Timeout: 15
      Frames:
        All Enabled: true
      Marker Scale: 0.5
      Name: TF
      Show Arrows: true
      Show Axes: true
      Show Names: true
      Tree:
        {}
      Update Interval: 0
      Value: true
    - Alpha: 1
      Autocompute Intensity Bounds: true
      Autocompute Value Bounds:
        Max Value: 10
        Min Value: -10
        Value: true
      Axis: Z
      Channel Name: intensity
      Class: rviz/LaserScan
      Color: 255; 0; 0
      Color Transformer: FlatColor
      Decay Time: 0
      Enabled: true
      Invert Rainbow: false
      Max Color: 255; 255; 255
      Min Color: 0; 0; 0
      Name: LaserScan
      Position Transformer: XYZ
      Queue Size: 10
      Selectable: true
      Size (Pixels): 3
      Size (m): 0.03
      Style: Flat Squares
      Topic: /scan
      Unreliable: false
      Use Fixed Frame: true
      Use rainbow: true
      Value: true
    - Class: rviz_imu_plugin/Imu
      Enabled: true
      Name: Imu
      Topic: /imu/data_raw
      Unreliable: false
      Value: true
      acc. vector alpha: 1
      acc. vector color: 255; 0; 0
      acc. vector scale: 0.05
      derotate acceleration: true
      enable acceleration: true
      enable axes: true
      enable box: false
      fixed frame orientation: true
    - Alpha: 0.7
      Class: rviz/Map
      Color Scheme: map
      Draw Behind: false
      Enabled: false
      Name: Map
      Topic: /map
      Unreliable: false
      Use Timestamp: false
      Value: false
  Enabled: true
  Global Options:
    Background Color: 48; 48; 48
    Default Light: true
    Fixed Frame: base_link
    Frame Rate: 30
  Name: root
  Tools:
    - Class: rviz/Interact
      Hide Inactive Objects: true
    - Class: rviz/MoveCamera
    - Class: rviz/Select
    - Class: rviz/FocusCamera
    - Class: rviz/Measure
    - Class: rviz/SetInitialPose
      Topic: /initialpose
    - Class: rviz/SetGoal
      Topic: /move_base_simple/goal
    - Class: rviz/PublishPoint
      Single click: true
      Topic: /clicked_point
  Value: true
  Views:
    Current:
      Class: rviz/XYOrbit
      Distance: 8
      Enable Stereo Rendering:
        Stereo Eye Separation: 0.06
        Stereo Focal Distance: 1
        Swap Stereo Eyes: false
        Value: false
      Focal Point:
        X: 0
        Y: 0
        Z: 0
      Focal Shape Fixed Size: true
      Focal Shape Size: 0.05
      Invert Z Axis: false
      Name: Current View
      Near Clip Distance: 0.01
      Pitch: 1.5698
      Target Frame: <Fixed Frame>
      Value: XYOrbit (rviz)
      Yaw: 3.1416
    Saved: ~
Window Geometry:
  Displays:
    collapsed: false
  Height: 846
  Hide Left Dock: false
  Hide Right Dock: false
  Selection:
    collapsed: false
  Time:
    collapsed: false
  Tool Properties:
    collapsed: false
  Views:
    collapsed: false
  Width: 1200
  X: 60
  Y: 60

시리즈 첫 글: Ubuntu 20.04LTS 기반 Ros2 foxy 설치
마지막 단계 글: (Jetson Project2#4)hector mapping 완성

profile
mseokq23.tistory.com 으로 이사했어요~ 많이 와주세요!

0개의 댓글