Skip to content

Instantly share code, notes, and snippets.

@maxosprojects
Last active December 9, 2017 14:42
Show Gist options
  • Select an option

  • Save maxosprojects/7c2732c5be3e61eb6deb to your computer and use it in GitHub Desktop.

Select an option

Save maxosprojects/7c2732c5be3e61eb6deb to your computer and use it in GitHub Desktop.
Dobot XYZ absolute (not additive) control
import serial
import time
import struct
import threading
import signal
class Dobot:
def __init__(self, port, baud=230400):
self.port = serial.Serial(port, baudrate=baud)
self.running = False
def start(self):
self.running = True
thread = threading.Thread(target=self.updateStatus)
thread.daemon = True
thread.start()
def stop(self):
self.running = False
def bytesToFloat(self, byteList):
data = ''.join(chr(i) for i in byteList)
return struct.unpack('<f', data)[0]
def floatToBytes(self, value):
return (ord(c) for c in struct.pack('<f', value))
def _readFloat(self):
data = []
while len(data) < 4:
byte = self.port.read(1)
if len(byte):
val = ord(byte)
data.append(val)
return self.bytesToFloat(data)
def _writeFloat(self, value):
data = self.floatToBytes(value)
for val in data:
# print hex(val)
self.port.write(chr(val & 0xFF))
def updateStatus(self):
num = 0
commandValues = 0
headFound = False
while self.running:
while not headFound:
data = self.port.read(1)
if len(data):
val = ord(data)
if val == 0xa5:
headFound = True
headFound = False
commandValues = 0
while commandValues < 10:
val = self._readFloat()
print time.strftime("%a, %d %b %Y %H:%M:%S"), num, val
commandValues += 1
num += 1
# Read tail byte.
self.port.read(1)
self.port.close()
def xyz(self, x, y, z):
self.port.write(chr(0xa5))
self._writeFloat(3.0)
self._writeFloat(0.0)
self._writeFloat(x)
self._writeFloat(y)
self._writeFloat(z)
self._writeFloat(0.0)
self._writeFloat(0.0)
self._writeFloat(1.0)
self._writeFloat(0.0)
self._writeFloat(0.0)
self.port.write(chr(0x5a))
def signal_handler(signal, frame):
dobot.stop()
sys.exit(0)
def main():
# listen for SIGINT
signal.signal(signal.SIGINT, signal_handler)
# Arduino USB under Linux.
# dobot = Dobot('/dev/ttyUSB0')
# Dobot Bluetooth under MacOS.
# dobot = Dobot('/dev/tty.BT4-SPP-SerialPort')
# Arduino USB under MacOS.
dobot = Dobot('/dev/tty.usbmodem1421')
dobot.start()
time.sleep(1)
dobot.xyz(270, 0, -40)
time.sleep(1)
dobot.xyz(230, 0, -40)
time.sleep(1)
dobot.stop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment