How-to by @Jesse
A thread is a piece of code that can run parallel to the main program, but there are some restrictions.
You should not use threads to directly move the robot as that can lead to some conflicts with the main code, which in turn can lead to protective stops. You also should try to avoid using blocking functions as that can lead to the thread not finishing in time.
Things that a thread can be really usefull for, is reading/writing IO signals, communcation with external devices using for example sockets and simple calculations.
There are 2 ways to implement a thread on a UR: using the polyscope and using URScript. Below are an example for both options for using a socket connection to ask for some data.
Polyscope
In the following picture, you can see an example of a thread in polyscope.
To control when you want the thread to request data from the socket server, you can use a while loop that only runs when a certain variable is set to True. Now, when you change the getData variable to True, the thread will start running. It opens a socket connection to the socket server, sends a string to indicate what it is requesting from the server, it tries to receive 4 values and then it closes the socket. At the end of the loop, you can reset the getData veriable so it doesn’t run continuously.
Now we have a thread of which we can control when we want to get data.
URScript
In the following code-block, you can see an example of a URScript.
thread getSocketDataThread():
if getData:
socket_open(IP, port) # Change IP and port to the IP and port you are using
socket_send_string("x y r")
received = socket_read_ascii_float(4, timeout=0)
socket_close()
x=received[1]/1000
y=received[2]/1000
z=230/1000
rx=(cos(0.5*d2r(received[3])))*3.14%180
ry=(sin(0.5*d2r(received[3])))*3.14%180
rz=0
getData=False
end
return False # This return doesn't do anything
end
You can see that the thread contains the same commands, but you should know that threads can’t take parameters and the return is thrown out so don’t try to use these.
Below are a few commands for in the main:
thrd = run getSocketDataThread # Starts running the Thread
join thrd # Stops the main untill the Thread has finished
kill thrd # Stops the thread and deletes it (and any nested threads)
With this, you can implement a simple thread into your UR program.