changeset 1:00778568562d

cleanup
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Sun, 22 Jun 2014 21:04:11 +0200
parents 9073470193f3
children 12958b56b98f
files maestro.py
diffstat 1 files changed, 18 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/maestro.py	Sun Jun 22 12:52:27 2014 +0000
+++ b/maestro.py	Sun Jun 22 21:04:11 2014 +0200
@@ -1,16 +1,26 @@
+"""
+A simple library for talking to the Pololu Maestro RC servo controllers.
+"""
 
-def int7bit(value):
-    byte1 = sum(2 ** i for i in range(7) if value & 2**i)
-    byte2 = sum(2 ** i for i in range(7) if value & 2**(i + 7))
-    return chr(byte1) + chr(byte2)
-        
+class Error(Exception):
+    pass
+
+
+class InitError(Error):
+    """Failed to initialize Maestro."""
+
 
 class Maestro(object):
     def __init__(self, serial):
         self.serial = serial
+        self._write(0xAA)
+        response = self.serial.read(1)
+        if response != '\xAA':
+            raise InitError("Failed to initialize Maestro")
 
-    def init(self):
-        self.serial.write('\xAA')
+    def _write(self, values):
+        self.serial.write(''.join(chr(v) for v in values))
 
     def move(self, servo, position):
-        self.serial.write('\x84' + chr(servo) + int7bit(int(position * 4)))
+        byte2, byte1 = divmod(int(position * 4), 128)
+        self._write([0x84, servo & 127, byte1 & 127, byte2 & 127])