Mercurial > maestro-servo
changeset 4:1a7cbf6e5dfa
more commands
| author | Radomir Dopieralski <sheep-devel@sheep.art.pl> |
|---|---|
| date | Mon, 23 Jun 2014 01:31:25 +0200 |
| parents | 0b6e8a49b070 |
| children | ee14101e75a3 |
| files | maestro.py |
| diffstat | 1 files changed, 49 insertions(+), 16 deletions(-) [+] |
line wrap: on
line diff
--- a/maestro.py Sun Jun 22 22:11:51 2014 +0200 +++ b/maestro.py Mon Jun 23 01:31:25 2014 +0200 @@ -2,26 +2,59 @@ A simple library for talking to the Pololu Maestro RC servo controllers. """ -class Error(Exception): - pass - - -class InitError(Error): - """Failed to initialize Maestro.""" - - class Maestro(object): def __init__(self, serial): self.serial = serial - def init(self): - if self._write([0xAA]) != [0xAA]: - raise InitError("Failed to initialize Maestro") - def _write(self, values): self.serial.write(''.join(chr(v) for v in values)) - return [ord(c) for c in self.serial.read()] + + def _write_command(self, command): + self._write([int(command) | 128]) + + def _write_byte(self, byte): + self._write([int(byte) & 127]) + + def _write_word(self, word): + byte2, byte1 = divmod(int(word), 128) + self._write([byte1 & 127, byte2 & 127]) + + def _read(self, count): + return [ord(c) for c in self.serial.read(count)] + + def _read_byte(self): + return self._read(1)[0] + + def _read_word(self): + byte1, byte2 = self._read(2) + return byte1 + byte2 * 256 - def move(self, servo, position): - byte2, byte1 = divmod(int(position * 4), 128) - self._write([0x84, servo & 127, byte1 & 127, byte2 & 127]) + def init(self): + """Initializes the communication. Returns True on success.""" + self._write_command(0xAA) + return self._read_byte() == 0xAA + + def set_target(self, servo, target): + """Set the servo position, in 1/4 of milliseconds of pulse width.""" + self._write_command(0x84) + self._write_word(target) + + def set_speed(self, servo, speed): + """Set the servo speed limit.""" + self._write_command(0x87) + self._write_word(speed) + + def set_accel(self, servo, accel): + """Set the servo acceleration limit.""" + self._write_command(0x89) + self._write_word(accel) + + def get_target(self, servo): + """Read the current target position of a servo.""" + self._write_command(0x90) + return self._read_word() + + def get_moving_state(self): + """True if any servo is still moving, otherwise False.""" + self._write_command(0x93) + return bool(self._read_byte())
