Advance Innovation Centre
  • AIC Knowledge @ EEC for All
  • 😎Logical Thinking
    • Karel Robot
    • Code to Flowchart
    • Play with Docker
    • CNX Software
  • MCU & Interfacing with Infineon PSOC™
    • Basic MCU Interfacing
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
      • PSoC™ 6S2 Peripherals Interfacing (GPIO)
        • Hello World and LED Blinking
        • GPIO Principles
        • PSoC™ 6S2 GPIO-HAL LED Blink Lab
        • PSoC™ 6S2 GPIO-PDL LED Blink Lab
        • Button "Bounce" Principles
          • Push/Pull Button to Turn ON/OFF LED via HAL
          • Push/Pull Button to Turn ON/OFF LED via PDL
          • GPIO Button Interrupt via HAL
          • GPIO Button Interrupt via PDL
        • GPIO variables & functions
      • PSoC™ 6S2 Peripherals Interfacing (ADC, PWM)
        • PSoC™ 6S2 SAR ADC
          • ADC Principles
          • PSoC™ 6S2 with ADC Labs
            • Reading potentiometer sensor value via an ADC HAL
            • Reading potentiometer sensor value via an ADC PDL
        • PSoC™ 6S2 PWM & TCPWM
          • PWM Principles
          • PSoC™ 6S2 for PMW Function Labs
            • LED Brightness using PWM via HAL
            • LED Brightness using PWM via PDL
    • Sensor Interfacing and HMI
      • OLED Display
        • OLED Display Principles
        • Calling BDH’s OLED functions
        • Display ADC via Potentiometer on OLED
      • BDH Shell
        • Shell Principles
        • LED Blinking and CAPSENSE via BDH Shell
        • Adding "History" command
        • Adding "Reboot" command
        • CAPSENSE Button and Slider
          • CAPSENSE Button and Slider with Capsense Tuner
          • CAPSENSE Button and Slider using FreeRTOS
    • Serial Communication & Visualization
      • UART, I2C, SPI Communication via Infineon PSoC™6
      • BMX160 Sensor Communication via Infineon PSoC™6
        • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
        • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
        • Motion Sensors GUI Integration via Serial Studio
    • IoT Connectivity & Data Analytics via Node-Red
      • Node-Red Installation
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • Edge AI on PSoC™
      • Machine Learning on PSoC™6 via Edge-Impulse
    • Infineon PSoC™ Troubleshooting
  • IoT Development with Infineon PSOC™ & BDH Platform
    • PSoC™ IoT Development Kit
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
        • Hello World and LED Blinking
    • IoT Connectivity
      • Node-Red Installation
      • Controlling PSoC™ LED using MQTT
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • BDH IoT Connectivity
    • WireLinX™ IoT PLC
    • BDH X-Brain Data Analytics
      • PSoC6 Data Collection to CSV log file
    • Data Visualization
      • สร้าง Dashboard ด้วย Looker Studio
  • 🖥️Operation Systems
    • Prerequisites
      • Guideline from Ubuntu
        • Ubuntu and VSCode on WSL2
      • ติดตั้ง WSL 2
      • Run Ubuntu on VirtualBox7
    • Zero to Linux Hero
      • Computer OS Architecture
      • Anatomy of Linux System
        • UNIX/Linux History
        • UNIX/Linux Evolution
        • GNU Project
        • Linux OS Architecture
        • Command Line Interface (CLI)
          • Basic Commands
          • 😎Level up your Linux Shell
          • File & Dir. Commands
          • Searching Commands
          • 😎ChatGPT-based Terminal
          • SysAdmin Commands
          • Network Commands
          • Hacker Commands
        • Busybox
        • Shell Script
          • Awk Script
          • Bash Shell Script
            • Bash Snippets
            • Bash Useful Examples
      • Anatomy of Linux Kernel
        • Linux Kernel Principles
        • Linux Environment for Developer
      • Anatomy of Embedded Linux
        • Embedded Linux
        • Host & Target
        • Cross Toolchains
        • Bootloader
        • Building Embedded Linux
    • Linux OS Dev. Engineer
      • Process Management
        • Process Basic
        • Process State
        • Basic Process Mgmt. Commands
        • Advance Process Mgmt. Commands
        • Process API Programming
      • IPC
        • IPC Anatomy
        • Signal Programming
        • Pipe Programming
        • FIFO Programming
        • Msg. Queue Programming
          • System V
        • Share Memory Programming
          • System V
        • Socket Programming
      • POSIX Threads
        • Multi-tasking Basic
        • POSIX Thread Anatomy
        • Threading Programming
      • Applied IPC
        • Remote Commander
        • Multi-Remote Commanders
      • Process Synchronization
        • Mutex Programming
        • Semaphore Programming
      • Applied IPC with Semaphore
  • ⌚Embedded Systems Development
    • Introduction to ESD
      • Why's ESD?
      • What it use for?
      • How it works?
    • Enbedded System Development via PSoC6
      • Basic MCU Interfacing
        • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
        • Development Environment Preparation
        • PSoC™ 6S2 Peripherals Interfacing (GPIO)
          • Hello World and LED Blinking
          • GPIO Principles
          • PSoC™ 6S2 GPIO-HAL LED Blink Lab
          • PSoC™ 6S2 GPIO-PDL LED Blink Lab
          • Button "Bounce" Principles
            • Push/Pull Button to Turn ON/OFF LED via HAL
            • Push/Pull Button to Turn ON/OFF LED via PDL
            • GPIO Button Interrupt via HAL
            • GPIO Button Interrupt via PDL
          • GPIO variables & functions
        • PSoC™ 6S2 Peripherals Interfacing (ADC, PWM)
          • PSoC™ 6S2 SAR ADC
            • ADC Principles
            • PSoC™ 6S2 with ADC Labs
              • Reading potentiometer sensor value via an ADC HAL
              • Reading potentiometer sensor value via an ADC PDL
          • PSoC™ 6S2 PWM & TCPWM
            • PWM Principles
            • PSoC™ 6S2 for PMW Function Labs
              • LED Brightness using PWM via HAL
              • LED Brightness using PWM via PDL
      • Sensor Interfacing and HMI
        • OLED Display
          • OLED Display Principles
          • Calling BDH’s OLED functions
          • Display ADC via Potentiometer on OLED
        • BDH Shell
          • Shell Principles
          • LED Blinking and CAPSENSE via BDH Shell
          • Adding "History" command
          • Adding "Reboot" command
          • CAPSENSE Button and Slider
            • CAPSENSE Button and Slider with Capsense Tuner
            • CAPSENSE Button and Slider using FreeRTOS
      • Serial Communication & Visualization
        • UART, I2C, SPI Communication via Infineon PSoC™6
        • BMX160 Sensor Communication via Infineon PSoC™6
          • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
          • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
          • Motion Sensors GUI Integration via Serial Studio
    • Edge Computing and IoT Connectivity
    • Cloud-Based Data Analytics and Digital Twin
    • Edge Vision AI
    • Resources
      • Basic Hardware and Firmware
        • Environment Preparation
          • การติดตั้งโปรแกรม Arduino IDE
            • ตัวอย่างการเริ่มต้นใช้งาน Arduino IDE
          • การติดตั้งโปรแกรมสำหรับใช้งานเครื่องมือวัด NI MyDAQ
            • ตัวอย่างการตั้งค่าใช้ Digital Multimeter -NI ELVISmx
            • ตัวอย่างการตั้งค่าใช้ Oscilloscope-NI ELVISmx
          • ติดตั้งโปรแกรม KingstVIS
        • Basic measurement
          • Basic Digital and Analog I/O
            • LAB: Basic Digital Input/Output
            • LAB: Basic Analog Input/Output
          • Waveform
            • LAB: Oscilloscope
            • LAB: Oscilloscope and Function Generator
            • LAB: Pulse Width Modulation (PWM)
              • Homework
        • Interfacing and Communication
          • LAB: UART, RS485, RS232 Protocol
          • LAB: I2C Protocol
            • HOMEWORK
          • LAB: SPI Protocol
      • IoT Connectivity
        • Example: IoT with MQTT on Node-red
        • Data logger
        • LAB: Data Visualization
  • 🛠️C/C++ for Embedded Programming
    • Development Environment Preparation
      • ติดตั้ง WSL 2
      • ติดตั้ง Ubuntu environment
      • ติดตั้งโปรแกรม Visual Studio Code
      • การเชื่อมต่อ Virtual studio code เข้ากับ WSL
      • ติดตั้ง docker on WSL
    • Principle C/C++ Programming
      • Get started with C++
      • Makefile
        • Makefile Examples
      • Compiling and running
        • How to create a program that you can enter inputs.
          • Lab 1 Exercise
      • Arguments
        • Command line arguments in C and C++
      • signed and unsigned data types
      • Variable and Operator
      • If and If else
      • Loop, Infinite loop, and flag
        • Loop and Flag exercise
      • Array
        • Get to know with arrays
        • Implement example
      • Vector
    • Object Oriented Programming (OOP) in C++
      • Class and Object
      • Encapsulation and Abstraction
      • Polymorphism and Inheritance
    • C/C++ Preprocessing
      • Macro
        • Quiz Macro
      • File Inclusion
      • Conditional Compilation
      • Pragma directive
        • Quiz Pragma
    • String in C++
      • Concatenation
      • Split
    • Type conversions for C/C++
      • Conversion using Cast operator
    • Error handling
    • Data logger
      • การสร้างไฟล์และเขียนไฟล์
      • การอ่านไฟล์
      • การเก็บข้อมูลกับTime stamp
    • High performance programing
      • Multi-task and Multi-thread
        • Multi-threading example
      • Mutex
      • Queue
      • OpenCV
    • C/C++ Techniques
      • Makefile in action
      • Object Oriented Programming (OOP) in C++
        • Class and Object
        • Encapsulation and Abstraction
        • Polymorphism and Inheritance
      • C/C++ Preprocessing
        • Macro
          • Quiz Macro
        • File Inclusion
        • Conditional Compilation
        • Pragma directive
          • Quiz Pragma
      • Binary, Octal and Hexadecimal Numbers
      • Array and properties of an array
        • Get to know with arrays
        • Implement example
      • What's next?
  • 🤖Artificial Intelligence (AI)
    • VAMStack Design House, BUU
    • Data Analytics
      • Data cleansing
      • Data analytics
      • Data analytic exercise
    • Machine Learning
      • Neural Network Layers
      • Machine learning type
      • Dataset
      • Using Edge Impulse for AI Model
    • Basic Image Processing
      • Computer Vision using Python Language
        • Installation
        • Computer Vision Basics
          • Pixel and Color
          • Draw image
          • Basic Image processing
          • Morphology Transformations
          • Gaussian blur
          • Simple Thresholding
          • Contour
          • Canny edge detection
        • Case Study
          • Coin counting
          • Color detection & tracking
        • VAM_CV SDK
  • ⚙️FPGA Design and Development
    • Verilog HDL via Vivado IDE
      • LAB1: Setting Environment and Create Project
        • Create Vivado Project
      • LAB2: Hardware Description Language Work Flow
        • Simulation code
      • LAB3: Design HDL Project
        • Top Level Design
        • Top-level Simulation
      • LAB4: Asynchronous VS Synchronous Circuit
        • Simulation Synchronous counter
    • C/C++ Programming on Ultra96v2 FPGA Board
      • Application C/C++ on Ultra96v2 Part 1
        • Design Overview
        • Step 1 - Burn the image to SD card
        • Step 2 - Bring up Ultra96v2
        • Step 3 - Installing the Vitis-AI runtime packages
      • Application C/C++ on Ultra96v2 Part 2
        • STEP 1 : Setting auto boot Wifi
        • STEP 2 : How to working on Embedded
        • STEP 3 : How to run the test code
  • 🤖Robotics
    • Dobot Magician
      • Instruction of Dobot
      • Software Download
      • Basically of Program
        • Teaching and Playback
        • Write and Draw
        • LaserEngraving
        • 3D Printer
    • Robotino
      • Software Download
        • Robotino View
        • Robotino SIM
      • Charging
      • Connecting
      • Follow Line example
        • Basic block in Follow Line
    • RaspBlock
      • Get Started with Raspblock
  • 🚩Special Topics
    • Node-Red
      • Set up Raspberry Pi
      • Install node red in Raspberry Pi
      • Get started with Node Red
        • Open node-red
        • Turn off node red
        • Install Dashboard on Node-red
        • Use node red to show message
        • Using Ultrasonic sensor with node-red
    • IoT Cloud
      • Overview
        • How do they work?
          • Basic Knowlege
      • Installations
        • Install Docker
        • Install Mosquitto Broker
        • Install InfluxDB
        • Install Telegraf
        • Install Grafana
      • Get Sensor Value and Send to MQTT
        • Connect ESP3266 to sensor
        • Connect ESP3266 to MQTT
      • Integration
    • Senses IoT
      • SENSES IoT Platform
      • LAB8: MCU send data to IoT platform
    • CrowPi Dev Kit
      • Raspberry Pi with CrowPi
      • Remote to Raspberry Pi
      • Cross-Compile
        • Lab 1: Programming and cross complier
      • Hardware and Interfaces Usage CLI
        • LAB: Usage GPIO via CLI
        • LAB: Scan I2C bus via CLI
      • Python library for Crow Pi
      • wiringPi library (C) for CrowPi
        • Lab2: Crowpi and sensors
    • LVGL Development
      • LVGL - Light and Versatile Embedded Graphics Library
        • Setting program for LVGL Simulator
        • Get started with LVGL simulator
        • Example Library of LVGL
        • Create your own screen
          • Exercise
        • Style
          • Exercise
        • Event
    • Docker OS
      • Docker OS Part 1
        • Part 1 : Installation
        • Part 2 : Basic Docker OS and Linux CLI
      • Docker OS Part 2
        • Part 1 : Docker communication
        • Part 2 : Docker compose
      • Application Gstreamer on devcontainer
        • STEP 1 : Setting gstreamer environment
        • STEP 2 : Create the Gstreamer element on template
        • STEP 3 : Testing and application on your gst element
  • 🤟Recommended by AIC
    • Skill Roadmap
      • Embedded Engineer
      • Developer
    • Hardware Programming
    • Embedded Programming
    • General-propose Programming
    • Algorithmica
    • Thai Expert Knowledge
    • RT-Thread University Program
      • Infineon PSoC6
      • Kernel
        • Kernel Basics
        • Thread Management
        • Clock Management
        • Inter-thread synchronization
        • Inter-thread communication
        • Memory Management
        • Interrupt Management
        • Kernel porting
        • Atomic Operations
        • RT-Thread SMP
        • Kernel API Changelog
      • Tools
      • Devices & Drivers
        • SENSOR Devices
        • Touch Equipment
        • CRYPTO Devices
        • AUDIO Devices
        • Pulse Encoder Devices
      • Components
        • C Library (libc)
        • ISO/ANSI C Standard
        • POSIX Standard
          • FILE (File IO)
          • Pthread
          • Timer
          • IPC Semaphore
          • IPC Message Queues
          • Dynamic Modules
        • Network Components
          • FinSH Console
          • FAL: Flash Abstraction Layer
          • Virtual File System
          • tmpfs: temporary file system
          • ulog log
          • utest testing framework
          • Power Management
          • RT-Link
        • Software Packages
          • Internet of Things
            • MQTT-umqtt
            • Telnet
          • Tools
            • SystemView
            • SEGGER_RTT
          • LVGL Manual
            • Touch Screen Driver
      • Demo
        • Infineon Gateway
        • Handwriting Recognition (MNIST)
        • Object Detection (Darknet)
        • ROS using RT-Thread
        • Control the car using RT-Thread
        • LiDAR via RT-Thread
        • Detection via RT-Thread and ROS
        • Sensor Driver Development Guide
Powered by GitBook

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University

On this page
  • 1 Introduction
  • 2 ROS Smooth Motion
  • 3 ROS Camera
  • 4 Conclusion
  • References

Was this helpful?

  1. Recommended by AIC
  2. RT-Thread University Program
  3. Demo

Control the car using RT-Thread

RT-Thread connects to ROS to control the car

PreviousROS using RT-ThreadNextLiDAR via RT-Thread

Last updated 7 months ago

Was this helpful?

This document will introduce how to use RT-Thread and ROS to connect to realize a remote control car with a camera.

img

Here is a diagram of the entire system, so that if you want to make a car like this yourself, you can try it out:

This is what the actual picture looks like:

The following codes are all operated on a computer with ROS installed

The installation of ROS has been introduced before, so I won’t repeat it here. Let’s create a new workspace first:

$ mkdir  telebot_ws  && cd telebot_ws
$ catkin_init_workspacecopymistakeCopy Success

Let's create a new ROS package:

$ cd src
$ catkin_create_pkg telebot rospycopymistakeCopy Success

Now we can start ROS development, in the telebot_ws directory:

$ catkin_make
$ source devel/setup.bashcopymistakeCopy Success

We first create a node to monitor keyboard keys and publish the received keys to the topic /keys (communication between ROS nodes is achieved by publishing and subscribing to topics). We create a new file key_publisher.py in the telebot_ws/src/telebot/src directory

#!/usr/bin/python

# 导入软件包
import sys, select, tty, termios
import rospy
from std_msgs.msg import String

if __name__ == '__main__':
    # 初始化节点
    key_pub = rospy.Publisher('keys', String, queue_size=1)
    rospy.init_node("keyboard_driver")
    rate = rospy.Rate(100)

    # 设置终端输入模式
    old_attr = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    print("Publishing keystrokes. Press Ctrl-C to exit ...")

    # 循环监听键盘事件
    while not rospy.is_shutdown():
        if select.select([sys.stdin], [], [], 0)[0] == [sys.stdin]:
            # 发布监听到的按键
            key_pub.publish(sys.stdin.read(1))
        rate.sleep()

    # 恢复终端设置
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr)copymistakeCopy Success

The code above is less than 20 lines long. I have also added some comments, so I won’t go into detail. Let’s add executable permissions to this file:

$ chmod u+x key_publisher.pycopymistakeCopy Success

You can start the node:

$ rosrun telebot key_publisher.pycopymistakeCopy Success

In this way, we can see that there is a /keys topic that continuously outputs keyboard keys:

$ rostopic echo /keys
data: "w"
---
data: "a"
---
data: "s"
---copymistakeCopy Success

Now there is a node publishing our key messages. The next step is to convert the key messages into motion instructions for the robot, that is, publish them to /cmd_vel. We create a new file keys_to_twist_with_ramps.py in the telebot_ws/src/telebot/src directory:

#!/usr/bin/python

# 导入软件包
import rospy
import math
from std_msgs.msg import String
from geometry_msgs.msg import Twist

# 键盘和速度映设 w a s d
key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1],
                'a': [ -1, 0], 'd': [1,  0],
                's': [ 0, 0] }
g_twist_pub = None
g_target_twist = None
g_last_twist = None
g_last_send_time = None
g_vel_scales = [0.1, 0.1] # default to very slow
g_vel_ramps = [1, 1] # units: meters per second^2

# 防止速度突变
def ramped_vel(v_prev, v_target, t_prev, t_now, ramp_rate):
  # compute maximum velocity step
  step = ramp_rate * (t_now - t_prev).to_sec()
  sign = 1.0 if (v_target > v_prev) else -1.0
  error = math.fabs(v_target - v_prev)
  if error < step: # we can get there within this timestep. we're done.
    return v_target
  else:
    return v_prev + sign * step  # take a step towards the target

def ramped_twist(prev, target, t_prev, t_now, ramps):
  tw = Twist()
  tw.angular.z = ramped_vel(prev.angular.z, target.angular.z, t_prev,
                            t_now, ramps[0])
  tw.linear.x = ramped_vel(prev.linear.x, target.linear.x, t_prev,
                           t_now, ramps[1])
  return tw

# 发布控制指令到 /cmd_vel
def send_twist():
  global g_last_twist_send_time, g_target_twist, g_last_twist,\
         g_vel_scales, g_vel_ramps, g_twist_pub
  t_now = rospy.Time.now()
  g_last_twist = ramped_twist(g_last_twist, g_target_twist,
                              g_last_twist_send_time, t_now, g_vel_ramps)
  g_last_twist_send_time = t_now
  g_twist_pub.publish(g_last_twist)

# 订阅 /keys 的回调函数
def keys_cb(msg):
  global g_target_twist, g_last_twist, g_vel_scales
  if len(msg.data) == 0 or not key_mapping.has_key(msg.data[0]):
    return # unknown key.
  vels = key_mapping[msg.data[0]]
  g_target_twist.angular.z = vels[0] * g_vel_scales[0]
  g_target_twist.linear.x  = vels[1] * g_vel_scales[1]

# 获取传递进来的速度加速度比例
def fetch_param(name, default):
  if rospy.has_param(name):
    return rospy.get_param(name)
  else:
    print "parameter [%s] not defined. Defaulting to %.3f" % (name, default)
    return default

if __name__ == '__main__':
  rospy.init_node('keys_to_twist')
  g_last_twist_send_time = rospy.Time.now()
  g_twist_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)
  rospy.Subscriber('keys', String, keys_cb)
  g_target_twist = Twist() # initializes to zero
  g_last_twist = Twist()
  g_vel_scales[0] = fetch_param('~angular_scale', 0.1)
  g_vel_scales[1] = fetch_param('~linear_scale', 0.1)
  g_vel_ramps[0] = fetch_param('~angular_accel', 1.0)
  g_vel_ramps[1] = fetch_param('~linear_accel', 1.0)

  rate = rospy.Rate(20)
  while not rospy.is_shutdown():
    send_twist()
    rate.sleep()copymistakeCopy Success

Similarly, we add executable permissions to this file:

$ chmod u+x keys_to_twist_with_ramps.pycopymistakeCopy Success

You can start the node:

$ rosrun telebot keys_to_twist_with_ramps.py _linear_scale:=1.0 _angular_scale:=0.8  _linear_accel:=1.0 _angular_accel:=0.8copymistakeCopy Success

The parameters passed in above are the ratio of the speed and acceleration of the car we want, so we can see that there is a /cmd_vel topic that will output the expected car speed:

$ rostopic echo /cmd_vel
linear:
  x: 1.0
  y: 0.0
  z: 0.0
angular:
  x: 0.0
  y: 0.0
  z: 0.0
---copymistakeCopy Success

Now the car can start, stop and turn slowly according to our instructions. The next step is to add a remote camera to it.

Before connecting to the camera of the car, there is one very important point. The previous operations were all performed on the computer. Next, we want to use our ARM development board as the ROS master node, so we need to set the environment variables and replace the following IP address with the actual IP address of the ARM board on the car :

$ export ROS_MASTER_URI=http://your.armbian_ros.ip.address:11311copymistakeCopy Success

The following codes are all operated on the ARM development board on the car with ROS installed

Let’s create a new workspace:

$ mkdir  telebot_ws  && cd telebot_ws
$ catkin_init_workspacecopymistakeCopy Success

Let's create a new ROS package:

$ cd src
$ catkin_create_pkg telebot_image roscppcopymistakeCopy Success

Now we can start ROS development, in the telebot_ws directory:

$ catkin_make
$ source devel/setup.bashcopymistakeCopy Success

In fact, the code for publishing camera messages is only about 30 lines. We create a new my_publisher.cpp in the telebot_ws/src/telebot_image/src directory.

#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "video_transp");
  ros::NodeHandle nh;
  image_transport::ImageTransport it(nh);
  image_transport::Publisher pub = it.advertise("camera/image", 1);

  cv::VideoCapture cap(0);
  cv::Mat frame;
  sensor_msgs::ImagePtr frame_msg;

  ros::Rate rate(10);

  while(ros::ok())
  {
    cap >> frame;
    if (!frame.empty())
    {
      frame_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
      pub.publish(frame_msg);
      cv::waitKey(1);
    }
    ros::spinOnce();
    rate.sleep();
  }
  return 0;
}copymistakeCopy Success

Before compiling, you need to install the OpenCV development environment first , because we use the OpenCV library function to obtain the camera data, and then publish it using the ROS library function. This is the CMakeLists.txt in the telebot_ws/src/telebot_image directory

cmake_minimum_required(VERSION 2.8.3)
project(telebot_image)

find_package(catkin REQUIRED COMPONENTS
  cv_bridge
  image_transport
)

catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES my_image_transport
#  CATKIN_DEPENDS cv_bridge image_transport
#  DEPENDS system_lib
)

include_directories(
  ${catkin_INCLUDE_DIRS}
)

find_package(OpenCV)
include_directories(include ${OpenCV_INCLUDE_DIRS})
#build my_publisher and my_subscriber
add_executable(my_publisher src/my_publisher.cpp)
target_link_libraries(my_publisher ${catkin_LIBRARIES} ${OpenCV_LIBS})copymistakeCopy Success

We compile the project in the telebot_ws directory:

$ catkin_makecopymistakeCopy Success

In this way, the camera message can be published. The image message is published in camera/image:

$rosrun telebot_image my_publishercopymistakeCopy Success

The following codes are all operated on a computer with ROS installed

Subscribing and seeing camera messages is actually very simple:

$ rosrun image_view image_view image:=/camera/imagecopymistakeCopy Success

You can then see the pictures from the car's camera on your computer.

If you already have a car that can be controlled by ROS, you only need to write about 30 lines of code in Part 3 for image publishing. You can use the OpenCV library to obtain camera information and then publish it using the ROS library.

Of course, if you just want to see the car's camera on your computer, there are actually many other ways that don't even require writing code. The advantage of using ROS to publish image data is that we can process the acquired images, such as target detection, which will be further introduced in subsequent documents.

But in fact, the RT-Thread part of the code has been introduced in this document: . On this basis, we only need to modify the ROS code.

img
img

img

🤟
RT-Thread connects to ROS to control the car
2 ROS Smooth Motion
2.1 ROS working environment
2.2 Button Trigger
2.3 Key analysis
3 ROS Camera
3.1 Release camera message
3.2 Subscribe to camera messages
4 Conclusion
References
ROS Robot Programming Practice
rosserial package
1 Introduction