ROS arduino read examples 2-5
ROS arduino read examples 2-5
Digital read:
Below is a simple example of an Arduino code that reads a digital input using ROS (Robot
Operating System) integration through rosserial_arduino. The code will read a digital pin and
publish the state to a ROS topic.
void setup() {
pinMode(inputPin, INPUT); // Set the input pin mode
nh.initNode(); // Initialize ROS node
nh.advertise(inputPublisher); // Advertise the topic
}
void loop() {
bool pinState = digitalRead(inputPin); // Read the digital pin
inputStateMsg.data = pinState; // Assign the state to the message
inputPublisher.publish(&inputStateMsg); // Publish the message
nh.spinOnce(); // Handle ROS communication
delay(100); // Adjust the delay as needed
}
### *Explanation*
1. ros.h and std_msgs/Bool.h: ROS libraries included for communication and message types.
2. inputPin: Defines which digital pin to read from.
3. std_msgs::Bool inputStateMsg: Stores the pin state.
4. ros::Publisher inputPublisher: Publishes the input state to the digital_input topic.
5. setup(): Initializes the pin mode and sets up the ROS node.
6. loop(): Reads the pin, updates the message, and publishes it to ROS.
Analog read:
### *Arduino Code Example for Analog Read with ROS*
cpp
#include <ros.h>
#include <std_msgs/Float32.h>
ros::NodeHandle nh;
void setup() {
nh.initNode(); // Initialize the ROS node
nh.advertise(analogPublisher); // Advertise the topic
}
void loop() {
int rawValue = analogRead(analogPin); // Read the analog input
float voltage = (rawValue / 1023.0) * 5.0; // Convert to voltage (assuming 5V reference)
### *Explanation*
1. *Library Imports*: ros.h and std_msgs/Float32.h for ROS communication and message type.
2. *analogPin*: Defines the analog input pin to read from (e.g., A0).
3. *analogValueMsg*: Stores the voltage reading as a float.
4. *analogPublisher*: Publishes to the analog_input topic.
5. *loop()*: Reads the analog input, converts it to voltage, updates the message, and publishes it
to ROS.