serial_example_node.cpp
Go to the documentation of this file.
1 /***
2  * This example expects the serial port has a loopback on it.
3  *
4  * Alternatively, you could use an Arduino:
5  *
6  * <pre>
7  * void setup() {
8  * Serial.begin(<insert your baudrate here>);
9  * }
10  *
11  * void loop() {
12  * if (Serial.available()) {
13  * Serial.write(Serial.read());
14  * }
15  * }
16  * </pre>
17  */
18 
19 #include <ros/ros.h>
20 #include <serial/serial.h>
21 #include <std_msgs/Byte.h>
22 #include <std_msgs/UInt8.h>
23 #include <std_msgs/String.h>
24 #include <std_msgs/Empty.h>
25 
27 
28 void write_callback(const std_msgs::String::ConstPtr& msg){
29  //ROS_INFO_STREAM("Writing to serial port" << msg->data);
30  ser.write(msg->data);
31 }
32 
33 int main (int argc, char** argv){
34  ros::init(argc, argv, "serial_example_node");
35  ros::NodeHandle nh;
36 
37  ros::Subscriber write_sub = nh.subscribe("serial_write", 1000, write_callback);
38  ros::Publisher read_pub = nh.advertise<std_msgs::String>("serial_read", 1000);
39 
40  try
41  {
42  ser.setPort("/dev/ttyUSB0");
43  ser.setBaudrate(115200);
45  ser.setTimeout(to);
49  ser.open();
50  }
51  catch (serial::IOException& e)
52  {
53  ROS_ERROR_STREAM("Unable to open port ");
54  return -1;
55  }
56 
57  if(ser.isOpen()){
58  ROS_INFO_STREAM("Serial Port initialized");
59  }else{
60  return -1;
61  }
62 
63  ros::Rate loop_rate(5);
64  while(ros::ok()){
65 
66  ros::spinOnce();
67 
68  if(ser.available()){
69  ROS_INFO_STREAM("Reading from serial port");
70  std_msgs::String result;
71  ROS_INFO_STREAM("ser.available: " << ser.available());
72  result.data = ser.read(ser.available());
73 
74  const char* read_data = result.data.c_str();
75  ROS_INFO_STREAM("Read: " << atoi(read_data));
76  read_pub.publish(result);
77  }
78  loop_rate.sleep();
79 
80  }
81 }
82 
size_t available()
void write_callback(const std_msgs::String::ConstPtr &msg)
void publish(const boost::shared_ptr< M > &message) const
Subscriber subscribe(const std::string &topic, uint32_t queue_size, void(T::*fp)(M), T *obj, const TransportHints &transport_hints=TransportHints())
int main(int argc, char **argv)
void setTimeout(Timeout &timeout)
ROSCPP_DECL void init(int &argc, char **argv, const std::string &name, uint32_t options=0)
void setBaudrate(uint32_t baudrate)
serial::Serial ser
void setStopbits(stopbits_t stopbits)
void setBytesize(bytesize_t bytesize)
ROSCPP_DECL bool ok()
static Timeout simpleTimeout(uint32_t timeout)
Publisher advertise(const std::string &topic, uint32_t queue_size, bool latch=false)
bool isOpen() const
bool sleep()
void setPort(const std::string &port)
#define ROS_INFO_STREAM(args)
size_t read(uint8_t *buffer, size_t size)
#define ROS_ERROR_STREAM(args)
ROSCPP_DECL void spinOnce()
void setParity(parity_t parity)
size_t write(const uint8_t *data, size_t size)


cpp
Author(s): Kab Kyoum Kim , Jin Hyuk Gong , Jeongwoo Lee
autogenerated on Sat May 18 2019 02:32:53