Robotics StackExchange | Archived questions

How to open a serial port using a ROS node?

I have setup a serial connection between my laptop and a PC. I run a Python script in order to send some data (strings, integers etc) to PC's serial terminal (the goal is to connect the laptop to a PIC microcontroller. The PC is just for testing). I want to to do the same thing using a ROS node, instead of just running the python script in an IDE. I spent days searching the internet for a solution and I tried several things I found, without finding the right way to do it.

If I understand correctly:

I use Ubuntu 16.04, ROS kinetic, Python 2.7.

Any possible solution, advise or example will be appreciated. Thanks in advance.

#!/opt/bin/python
#!/usr/bin/env python
import rospy
import serial
import time
from std_msgs.msg import String
def serial_connection():
    rospy.init_node('serial_connection', anonymous = True)
    rate = rospy.Rate(10)
    syxnotita = 0
    euros = 0
    mesi_gwnia = 0
    while not rospy.is_shutdown():
        data = [syxnotita, euros, mesi_gwnia]
        ser = serial.Serial('/dev/ttyUSB0', 9600)
        print (ser.name)
        time.sleep(2)
        while ser.isOpen():
            print ("Port Open")
            for i in range(5):
                print ('Hola!')
                ser.write("Hola!\n")
                time.sleep(1)
                rate.sleep()
        ser.close()
if __name__ == '__main__':
    try:
        serial_connection()
    except rospy.ROSInterruptException:
        pass

Asked by Spyros on 2018-10-22 06:46:42 UTC

Comments

Answers

Using serial port is not really a ROS question, but I feel your pain so I'll help out.

First: your code runs just fine on 14.04.4 with Jade using just "rosrun serial serial.py". Confirmed serialport output as well as print statements working. No changes required at all. I suspect it runs fine on 16 as well but something wrong with your config. maybe

Second: I created the package with "catkin_create_pkg serial std_msgs rospy roscpp" as described in the tutorials. You didn't mention anything about creating a package so maybe that is where you missed out.

You'll need to explain what you mean by "and didn't work" because that kind of description isn't useful at all.

Asked by billy on 2018-10-23 22:53:06 UTC

Comments