2.3 Controlling LEDs & Servo with ROS 2

2.3.1 Hardware Setup for Servo Control

You'll need:

  • Servo motor (e.g., SG90 or MG90)

  • Jumper wires

  • Arduino Nano (or Uno)

  • USB cable to connect Arduino to PC

  • External 5V power supply (if required)

  • Red LED

  • Blue LED

  • 2 x 220Ω resistors

  • Breadboard

Wiring:

  • Connect the Red LED to digital pin 7 (with the resistor in series).

  • Connect the Blue LED to digital pin 8 (with the resistor in series).

  • Servo Signal (Orange/White wire) → Arduino digital pin 9

  • Servo VCC (Red wire) → Arduino 5V pin (or an external 5V power supply)

  • Servo GND (Brown/Black wire) → Arduino GND pin


2.3.2 Writing ROS Node for Serial Communication

The first step is writing a simple ROS node in Python that sends a command over serial to the Arduino.

Create a ROS package if you haven’t already:

You will now have a new folder within your workspace’s src directory called ros_arduino_com.

We will modify the Python ROS node to include options for controlling the servo motor. It will now send commands to control both the LEDs and the servo.

ser_com.py:

Make sure to modify /dev/ttyUSB0 to match the correct serial port for your Arduino.

This ROS node allows real-time control by sending commands from the terminal to the Arduino. The commands include:

  • 1: Turn on the red LED.

  • 2: Turn on the blue LED.

  • 0: Turn off both LEDs.

  • 3: Move the servo to 0 degrees.

  • 9: Move the servo to 90 degrees.


2.3.3 Uploading Arduino Code with servo control

Now, upload a simple Arduino sketch to receive data from ROS.

Arduino Sketch:

This code allows both LEDs and the servo to be controlled from the same command interface.


2.3.4 Running the Code

  1. Open a terminal on your PC and source ROS 2:

  2. Run the ROS node:

Now you can see commands being sent from ROS to Arduino. Check the Arduino Serial Monitor to see the received data.


Last updated