ROS Arduino output write example
Digital write:
Here’s an example Arduino sketch that controls a digital output pin based on ROS messages:
#include <ros.h>
#include <std_msgs/Bool.h>
ros::NodeHandle nh;
// Define the digital pin
const int pin = 13;
// Callback function to set the digital output
void digitalOutputCallback(const std_msgs::Bool& msg) {
if (msg.data) {
digitalWrite(pin, HIGH); // Set pin high (ON)
} else {
digitalWrite(pin, LOW); // Set pin low (OFF)
}
}
// Define a subscriber to receive messages
ros::Subscriber<std_msgs::Bool> sub("digital_out", digitalOutputCallback);
void setup() {
pinMode(pin, OUTPUT); // Set the digital pin as output
nh.initNode();
nh.subscribe(sub); // Subscribe to the topic
}
void loop() {
nh.spinOnce(); // Process incoming ROS messages
delay(10); // Add a small delay to avoid overloading the loop
}
This code listens to the digital_out topic and sets the state of pin 13 based on the received
message (True for HIGH, False for LOW).
Run the ROS Node to Communicate with the Arduino:
In a new terminal, launch the rosserial node to establish communication with the Arduino.
roslaunch rosserial_arduino serial_node.launch
This command opens a serial connection to the Arduino and allows it to communicate with ROS.
Publish Messages from ROS:
You can now control the digital output pin from ROS by publishing messages to the
digital_out topic. For example, to turn the pin on, you can run:
rostopic pub /digital_out std_msgs/Bool "data: true"
To turn it off, run:
rostopic pub /digital_out std_msgs/Bool "data: false"