Skip to content

Instantly share code, notes, and snippets.

@soravux
Last active December 22, 2015 04:08
Show Gist options
  • Select an option

  • Save soravux/6414925 to your computer and use it in GitHub Desktop.

Select an option

Save soravux/6414925 to your computer and use it in GitHub Desktop.
Code for the LCES from Multigrad's blog ( http://multigrad.blogspot.ca/ )
"""
Example of how to move randomly two servos plugged in the 5th and 6th channel
(slot 4 & 5) of a Pololu Micro Maestro 6.
This script requires pyserial.
"""
from random import randrange, uniform
from time import sleep
from struct import pack
import serial
class PololuConn(object):
"""Encapsulates Pololu communications."""
def __init__(self, port, port_speed=9600):
"""Creates a connection to the Pololu.
:param port:
The serial port linked to the Pololu. Is of the form r'\\\\.\\COM3'
on Windows and '/dev/ttyUSB1' on Linux.
:type port: str
:param port_speed: The speed of the port (default 9600)
:type port_speed: int
:exception ValueError:
Will be raised when parameter are out of range, e.g. baud rate,
data bits.
:exception SerialException:
In case the device can not be found or can not be configured.
"""
self.ser = serial.Serial(port, port_speed)
def setSpeed(self, channel, speed):
"""Sets the speed of the servos plugged in channels.
The protocol for the Pololu is described in this page:
# http://www.pololu.com/docs/0J40/5.e
:param channels: channel to change speed.
:type channels: int
:param speed: Speed to set the servo.
:type speed: int
"""
self.ser.write(pack("BBBB", 0x87, channel, speed, 0x00))
def move(self, channel, destination):
"""Move the servos plugged in channels to their destinations.
Motion is done using the Mini-SSC protocol described in this page:
http://www.pololu.com/docs/0J40/5.c
:param channels: Channel to move.
:type type: int
:param destinations: Destination angle between 0 and 255.
:type destinations: int
"""
self.ser.write(pack("BBB", 0xff, channel, destination))
def close(self):
"""Close the connection to the Pololu."""
self.ser.close()
def main():
"""Connects to a Pololu and then moves randomly its channels 4 and 5."""
# These constants defines the servo range.
SERVOS_USED = (4, 5)
SERVO_RANGE = (0x40, 0xA0)
DELAY_RANGE = (0.05, 0.70)
conn = PololuConn(port=r'\\.\COM3')
# Set speed
for servo in SERVOS_USED:
conn.setSpeed(servo, 0x15)
# Main random destination loop
try:
while True:
for servo in SERVOS_USED:
destination = randrange(*SERVO_RANGE)
conn.move(servo, destination)
sleep(uniform(*DELAY_RANGE))
except KeyboardInterrupt:
conn.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment