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:
- rosserial works only with "connected rosserial-enabled devices". But I don't want to modify the microcontroller's code.
- I searched the serial package documentation: http://wjwwood.io/serial/ and http://wjwwood.io/serial/doc/1.1.0/in... but I didn't find out how to use it.
- I found rosbridge_suite package: http://wiki.ros.org/rosbridge_suite/T... but I don't know if I can use it and how in my case.
- I tried to run serial_node.py from rosserial_python package to see what happens (I changed serial port name and baud rate) https://answers.ros.org/question/2837... I got the error: ImportError: No module named yaml Then, I searched serial_node.py to find how the nodes sends data but I didn't find any sent() function to use it in my script.
I tried to run my script as it is, using rosrun, adding only:
#!/usr/bin/env python import rospy from std_msgs.msg import string
and didn't work.
- Then I changes my code and the final version is at the end of this post (some functions may not be necessary - I am sorry about the format). When I run it with rosrun I get the error: bad interpreter: No such file or directory and I get nothing on my serial terminal.
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