ros-drivers / rosserial

A ROS client library for small, embedded devices, such as Arduino. See: http://wiki.ros.org/rosserial
508 stars 527 forks source link

How to modify the rosserial code if I want to use arduino mega 2560 serial2 to communicate with PC. #582

Open BronWang opened 2 years ago

BronWang commented 2 years ago

class ArduinoHardware { public: ArduinoHardware(SERIALCLASS* io , long baud= 57600){ iostream = io; baud = baud; } ArduinoHardware() {

if defined(USBCON) and !(defined(USE_USBCON))

  /* Leonardo support */
  iostream = &Serial1;

elif defined(USE_TEENSY_HW_SERIAL) or defined(USE_STM32_HW_SERIAL)

  iostream = &Serial1;

else

  iostream = &Serial;

endif

  baud_ = 57600;
}
ArduinoHardware(ArduinoHardware& h){
  this->iostream = h.iostream;
  this->baud_ = h.baud_;
}

void setPort(SERIAL_CLASS* io){
  this->iostream = io;
}

void setBaud(long baud){
  this->baud_= baud;
}

int getBaud(){return baud_;}

void init(){

if defined(USE_USBCON)

  // Startup delay as a fail-safe to upload a new sketch
  delay(3000); 

endif

  iostream->begin(baud_);
}

int read(){return iostream->read();};
void write(uint8_t* data, int length){
  iostream->write(data, length);
}

unsigned long time(){return millis();}

protected: SERIALCLASS* iostream; long baud; };

BronWang commented 2 years ago

In 15th line, ''iostream = &Serial'' is revised to ''iostream = &Serial2'', which is right or not?

romainreignier commented 2 years ago

Hi @BronWang

The ros::NodeHandle class has a getHardware() method here: https://github.com/ros-drivers/rosserial/blob/c169ae2173dcfda7cee567d64beae45198459400/rosserial_client/src/ros_lib/ros/node_handle.h#L130-L133

And the ArduinoHardware class has a setPort() method here: https://github.com/ros-drivers/rosserial/blob/c169ae2173dcfda7cee567d64beae45198459400/rosserial_arduino/src/ros_lib/ArduinoHardware.h#L88-L90

So you should be able to change the port used by rosserial by adding this line as the first line of your setup() function:

nh.getHardware()->setPort(&Serial2);