Giter VIP home page Giter VIP logo

adafruit-motor-hat-python-library's Introduction

THIS LIBRARY IS DEPRECATED. SEE NEW LIBRARY HERE:

https://github.com/adafruit/Adafruit_CircuitPython_MotorKit

Adafruit Python Library for DC + Stepper Motor HAT

Python library for interfacing with the Adafruit Motor HAT for Raspberry Pi to control DC motors with speed control and Stepper motors with single, double, interleave and microstepping.

Designed specifically to work with the Adafruit Motor Hat

----> https://www.adafruit.com/product/2348

Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!

Written by Limor Fried for Adafruit Industries. MIT license, all text above must be included in any redistribution

adafruit-motor-hat-python-library's People

Contributors

caternuson avatar ladyada avatar tdicola avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit-motor-hat-python-library's Issues

performance + other improvements

Hello,

I started to use the Adafruit motor hat with this library.
I discovered several issues:

  1. When a new motorhat is initialised, a new steppermotor instance is also initialized in line 230:
    self.steppers = [ Adafruit_StepperMotor(self, 1), Adafruit_StepperMotor(self, 2) ]

In this way. The steps per revolution is not changeable during initialization and remains 200.

  1. The timing is of by using time.sleep(s_per_s) in line 159. This can be greatly Improved by:
    time.sleep(time.time() - time_before_start - s_per_s)
  2. The speed of execution can be improved by only sending the commands needed with this snippet starting from line 130:
           if (dir == Adafruit_MotorHAT.FORWARD):
                   prev_coil = step2coils[(self.currentstep/(self.MICROSTEPS/2) - 1) % len(step2coils)]
           else:
                   prev_coil = step2coils[(self.currentstep/(self.MICROSTEPS/2) + 1) % len(step2coils)]
           coils = step2coils[self.currentstep/(self.MICROSTEPS/2)]


#print "coils state = " + str(coils)
pin_to_set = [self.AIN2, self.BIN1, self.AIN1, self.BIN2]
for pin in range (0, 4):
           if prev_coil[pin] != coils[pin]:
                      self.MC.setPin(pin_to_set[pin], coils[pin])
  1. Is it possible that at line 239, the logic bits are reversed?
if (value == 0):
       self._pwm.setPWM(pin, 0, 4096)
if (value == 1):
       self._pwm.setPWM(pin, 4096, 0)

Shouldn’t it be like this:

if (value == 1):
       self._pwm.setPWM(pin, 0, 4096)
if (value == 0):
       self._pwm.setPWM(pin, 0, 0)`
  1. The loop running the commands is locked and cannot be aborted. This is often needed in all sorts of situations. Is it possible to have an abort bit programmed in the loop in line 157

Different torque for a stepper motor with microstepping

Raspberry Pi3 with Raspian
python 2.7.9

In one direction of rotation, the library switches off the current at maximum. Furthermore, the coils are switched one step too early.
I solved the problem like this:

    if (style == Adafruit_MotorHAT.MICROSTEP):
        self.currentstep -= 1

        # go to next 'step' and wrap around
        self.currentstep += self.MICROSTEPS * 4
        self.currentstep %= self.MICROSTEPS * 4

        pwm_a = wm_b = 0
        if (self.currentstep >= 0) and (self.currentstep < self.MICROSTEPS):
            pwm_a = self.MICROSTEP_CURVE[self.MICROSTEPS - self.currentstep]
            pwm_b = self.MICROSTEP_CURVE[self.currentstep]
        elif (self.currentstep >= self.MICROSTEPS) and (self.currentstep < self.MICROSTEPS*2):
            pwm_a = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS]
            pwm_b = self.MICROSTEP_CURVE[self.MICROSTEPS*2 - self.currentstep]
        elif (self.currentstep >= self.MICROSTEPS*2) and (self.currentstep < self.MICROSTEPS*3):
            pwm_a = self.MICROSTEP_CURVE[self.MICROSTEPS*3 - self.currentstep]
            pwm_b = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS*2]
        elif (self.currentstep >= self.MICROSTEPS*3) and (self.currentstep < self.MICROSTEPS*4):
            pwm_a = self.MICROSTEP_CURVE[self.currentstep - self.MICROSTEPS*3]
            pwm_b = self.MICROSTEP_CURVE[self.MICROSTEPS*4 - self.currentstep]

    # only really used for microstepping, otherwise always on!
    self.MC._pwm.setPWM(self.PWMA, 0, pwm_a*16)
    self.MC._pwm.setPWM(self.PWMB, 0, pwm_b*16)

    # set up coil energizing!
    coils = [0, 0, 0, 0]

    if (style == Adafruit_MotorHAT.MICROSTEP):
        if (self.currentstep >= 0) and (self.currentstep < self.MICROSTEPS):
            if (dir == Adafruit_MotorHAT.FORWARD):
                coils = [1, 1, 0, 0]
            else:
                coils = [1, 0, 0, 1]
        elif (self.currentstep >= self.MICROSTEPS) and (self.currentstep < self.MICROSTEPS*2):
            if (dir == Adafruit_MotorHAT.FORWARD):
                coils = [0, 1, 1, 0]
            else:
                coils = [0, 0, 1, 1]
        elif (self.currentstep >= self.MICROSTEPS*2) and (self.currentstep < self.MICROSTEPS*3):
            if (dir == Adafruit_MotorHAT.FORWARD):
                coils = [0, 0, 1, 1]
            else:
                coils = [0, 1, 1, 0]
        elif (self.currentstep >= self.MICROSTEPS*3) and (self.currentstep < self.MICROSTEPS*4):
            if (dir == Adafruit_MotorHAT.FORWARD):
                coils = [1, 0, 0, 1]
            else:
                coils = [1, 1, 0, 0]
    else:
        step2coils = [     [1, 0, 0, 0],
            [1, 1, 0, 0],
            [0, 1, 0, 0],
            [0, 1, 1, 0],
            [0, 0, 1, 0],
            [0, 0, 1, 1],
            [0, 0, 0, 1],
            [1, 0, 0, 1] ]
        coils = step2coils[self.currentstep//(self.MICROSTEPS//2)]

    #print "coils state = " + str(coils)
    self.MC.setPin(self.AIN2, coils[0])
    self.MC.setPin(self.BIN1, coils[1])
    self.MC.setPin(self.AIN1, coils[2])
    self.MC.setPin(self.BIN2, coils[3])

    return self.currentstep

Turning to slow

hi

ive got a stepper with a 1:900 Transmission, which needs a Supply of 6-15V and 150mA.

When i m driving the Motor, like the example shows, the driver is pulling around 800 mA and the voltage is getting high to 18V.... Additional to that, the Stepper turns very very very slow. I tried a lot of changes, but nothing worked. Any ideas ?

Wrong indents in StepperTest.py

The last two lines the the StepperTest.py have wrong indents and do not even compile. As they belong to a while loop as the other previous lines, they should have only 1 indent instead of 2. It's clearly visible even in GitHub.

   while (True):
    print("Single coil steps")
    myStepper.step(100, Adafruit_MotorHAT.FORWARD,  Adafruit_MotorHAT.SINGLE)
    myStepper.step(100, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.SINGLE)

    print("Double coil steps")
    myStepper.step(100, Adafruit_MotorHAT.FORWARD,  Adafruit_MotorHAT.DOUBLE)
    myStepper.step(100, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.DOUBLE)

    print("Interleaved coil steps")
    myStepper.step(100, Adafruit_MotorHAT.FORWARD,  Adafruit_MotorHAT.INTERLEAVE)
    myStepper.step(100, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.INTERLEAVE)

    print("Microsteps")
        myStepper.step(100, Adafruit_MotorHAT.FORWARD,  Adafruit_MotorHAT.MICROSTEP)
        myStepper.step(100, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.MICROSTEP)

In addition to that, has anyone even tried to run this code with a stepper motor? Can't seem to get it move my stepper motor smoothly (which is powered by an external power). Motor is zig-zagging back and forth even if there's just one forward command.

Add install dependencies script

You should probably add
apt-get install -y python-smbus

which brings in as a bonus:

The following extra packages will be installed:
  i2c-tools

and something like

# Auto load i2c kernel modules
# This works for Pi2, I think the Pi1 only has i2c-dev? No idea.
 if ! grep -q "i2c-" /etc/modules; then
    echo "i2c-dev" >> /etc/modules
    echo "i2c-bcm2708" >> /etc/modules
fi

to your build script.

Here's why,

On a vanilla Pi2 running Raspbian

root@jazzy ~ # cat /etc/debian_version
7.8

after installing the Motor HAT library with
python setup.py install

You get this:

root@jazzy ~/nodedemo/Adafruit-Motor-HAT-Python-Library/examples # python DCTest.py
Traceback (most recent call last):
  File "DCTest.py", line 2, in <module>
    from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_MotorHAT-1.2.0-py2.7.egg/Adafruit_MotorHAT/__init__.py", line 1, in <module>
    from .Adafruit_MotorHAT import Adafruit_StepperMotor, Adafruit_DCMotor, Adafruit_MotorHAT
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_MotorHAT-1.2.0-py2.7.egg/Adafruit_MotorHAT/Adafruit_MotorHAT.py", line 3, in <module>
    from Adafruit_PWM_Servo_Driver import PWM
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_MotorHAT-1.2.0-py2.7.egg/Adafruit_MotorHAT/Adafruit_PWM_Servo_Driver.py", line 5, in <module>
    from Adafruit_I2C import Adafruit_I2C
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_MotorHAT-1.2.0-py2.7.egg/Adafruit_MotorHAT/Adafruit_I2C.py", line 3, in <module>
    import smbus
ImportError: No module named smbus

python-smbus is not there by default. i2c-tools isn't there either and i2c kernel modules aren't loaded.

motor port #

I think there is a discrepancy between your code and your comment.
in StepperTest.py
myStepper = mh.getStepper(200, 2) # 200 steps/rev, motor port #1

Motor state should be stored as part of the class and retrievable from calling code

Problem:

Currently there is no way of ascertaining what a motor is doing; it must be tracked manually in the users code. This may create issues when multi-threading or in complex functions where manually tracking the status of the motors is undesirable.

The Adafruit_StepperMotor and Adafruit_DCMotor classes should store this information locally and be able to return it when requested.

Solution

To implement this, I propose the following new methods:
In class Adafruit_StepperMotor:

  • getSpeed()
    • Takes no arguments
    • returns RPM

(I'm not familiar with running stepper motors, so other GET methods as necessary. This was the only one I could tell was necessary from looking at the source)

In class Adafruit_DCMotor

  • getSpeed()
    • Takes no arguments
    • Returns speed (0-255)
  • getCommand()
    • Takes no arguments
    • Returns Adafruit_MotorHAT ENUM
      • Adafruit_MotorHAT.FORWARD
      • Adafruit_MotorHAT.BACKWARD
      • Adafruit_MotorHAT.BRAKE
      • Adafruit_MotorHAT.RELEASE

Additionally, some class variables would have to be added to track this information. Class methods would have to be updated to use these variables instead of method variables they currently use.


I would do this myself and submit a pull request, but I'm new to Python and this code is still slightly over my head.

Problem Erno2

Hi,
I've receive my new Motor Hat for my raspberry pi
I've installed the library with: https://learn.adafruit.com/adafruit-dc-and-stepper-motor-hat-for-raspberry-pi/installing-software

but when I try examples i got this error:
pi@raspberrypi:~/Adafruit-Motor-HAT-Python-Library/examples $ sudo python DCTest.py Traceback (most recent call last): File "DCTest.py", line 2, in <module> from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/__init__.py", line 1, in <module> File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/Adafruit_MotorHAT.py", line 3, in <module> File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/Adafruit_PWM_Servo_Driver.py", line 11, in <module> File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/Adafruit_PWM_Servo_Driver.py", line 35, in PWM File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/Adafruit_I2C.py", line 43, in __init__ IOError: [Errno 2] No such file or directory
I don't know what it is...

Thanks by advance for your help!

Android Things support

Hey team, I've started porting this library to Android Things (Java). The code is here and, though it only supports DC motors, it's already useful for projects:

image

Feel free to close this ticket, I I just wanted to let you know about this port. Thanks for opensourcing this Python library :)

StepperTest.py

I've been trying to use the HAT and followed the instructions on Adafruit to a T, but I am still getting the same error message.

pi@raspberrypi:~/Adafruit-Motor-HAT-Python-Library/examples $ sudo python StepperTest.py
Traceback (most recent call last):
File "StepperTest.py", line 3, in
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor
File "build/bdist.linux-armv7l/egg/Adafruit_MotorHAT/init.py", line 1, in
File "/usr/local/lib/python2.7/dist-packages/Adafruit_MotorHAT-1.3.1-py2.7.egg/Adafruit_MotorHAT/Adafruit_MotorHAT.py", line 52
if (dir == Adafruit_MotorHAT.FORWARD):
^
IndentationError: expected an indented block

I have tested my i2C and everything seems to be working there.

pi@raspberrypi:~ $ sudo i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: 70 -- -- -- -- -- -- --

My stepper motor is receiving power because I cannot manually turn it.

Any solution? Thanks in advance.

I'am getting an error "No module named 'Adafruit_MotorHAT'"

Thank you for opening an issue on an Adafruit Python library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:

  • Do not use GitHub issues for troubleshooting projects and issues. Instead use
    the forums at http://forums.adafruit.com to ask questions and troubleshoot why
    something isn't working as expected. In many cases the problem is a common issue
    that you will more quickly receive help from the forum community. GitHub issues
    are meant for known defects in the code. If you don't know if there is a defect
    in the code then start with troubleshooting on the forum first.

  • If following a tutorial or guide be sure you didn't miss a step. Carefully
    check all of the steps and commands to run have been followed. Consult the
    forum if you're unsure or have questions about steps in a guide/tutorial.

  • For Python/Raspberry Pi projects check these very common issues to ensure they don't apply:

    • If you are receiving an ImportError: No module named... error then a
      library the code depends on is not installed. Check the tutorial/guide or
      README to ensure you have installed the necessary libraries. Usually the
      missing library can be installed with the pip tool, but check the tutorial/guide
      for the exact command.

    • Be sure you are supplying adequate power to the board. Check the specs of
      your board and power in an external power supply. In many cases just
      plugging a board into your computer is not enough to power it and other
      peripherals.

    • Double check all soldering joints and connections. Flakey connections
      cause many mysterious problems. See the guide to excellent soldering for examples of good solder joints.

If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:

  • Platform/operating system (i.e. Raspberry Pi with Raspbian operating system,
    Windows 32-bit, Windows 64-bit, Mac OSX 64-bit, etc.): INSERT PLATFORM/OPERATING
    SYSTEM HERE

  • Python version (run python -version or python3 -version): INSERT PYTHON
    VERSION HERE

  • Error message you are receiving, including any Python exception traces: INSERT
    ERROR MESAGE/EXCEPTION TRACES HERE
    *

  • List the steps to reproduce the problem below (if possible attach code or commands
    to run): LIST REPRO STEPS BELOW

This library doesn't work with Python 3 (and it's 2017)

This should be at least noted on the repo so people waist hours trying. This port should not be too difficult and there are several branches/pull requests that have made it working for their application.

The PMW Servo Hat has a great install flow that works for python 3. Could this install guide be made to match.

I'm using this to allow differential drive cars use the donkey to make them self driving.
2017-02-12 18 58 32

DC Motor Control can't go all on

Hi,

There's no way to turn a DC motor fully on or off because the max value should be 4095 (or 4096 special) and 255*16 isn't that. I guess I can just set the pin on so it's not a big deal.

Disable "sec per step" message

The "x sec per step" message when moving a stepper motor should be a debug message, and off by default. If using a CLI, the message clutters the display.

Adafruit_MotorHAT_Motors.py

class Adafruit_StepperMotor:

    ...

    def __init__(self, controller, num, steps=200, debug=False):

        ...

        self.debug = debug

    ...

    def step(self, steps, direction, stepstyle):

        ...

        if self.debug:

            print("{} sec per step".format(s_per_s))

...

Adafruit hat differential drive help

python diff_drive.py
Detected running on rasberrypi. Only importing select modules.
Using TensorFlow backend.
diff_vehicle
{'steering_actuator_channel': None, 'vehicle_id': 'mycar', 'throttle_actuator_channel': None, 'pilot_model_path': '/home/pi/mydonkey/models/default.h5', 'throttle_actuator_min_pulse': None, 'vehicle_loop_delay': 0.08, 'camera_loop_delay': 0.08, 'steering_actuator_min_pulse': None, 'throttle_actuator_zero_pulse': None, 'steering_actuator_max_pulse': None, 'throttle_actuator_max_pulse': None}
Traceback (most recent call last):
File "diff_drive.py", line 31, in
left_motor = dk.actuators.Adafruit_Motor_Hat_Controller(cfg['left_actuator_channel'])
KeyError: 'left_actuator_channel'

defined the key in the file,but not accessing the left_actuator_channel key... please help me.. should i include anything

Stepper Motor Voltage not specified in code?

Thank you for opening an issue on an Adafruit Python library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:

  • Do not use GitHub issues for troubleshooting projects and issues. Instead use
    the forums at http://forums.adafruit.com to ask questions and troubleshoot why
    something isn't working as expected. In many cases the problem is a common issue
    that you will more quickly receive help from the forum community. GitHub issues
    are meant for known defects in the code. If you don't know if there is a defect
    in the code then start with troubleshooting on the forum first.

  • If following a tutorial or guide be sure you didn't miss a step. Carefully
    check all of the steps and commands to run have been followed. Consult the
    forum if you're unsure or have questions about steps in a guide/tutorial.

  • For Python/Raspberry Pi projects check these very common issues to ensure they don't apply:

    • If you are receiving an ImportError: No module named... error then a
      library the code depends on is not installed. Check the tutorial/guide or
      README to ensure you have installed the necessary libraries. Usually the
      missing library can be installed with the pip tool, but check the tutorial/guide
      for the exact command.

    • Be sure you are supplying adequate power to the board. Check the specs of
      your board and power in an external power supply. In many cases just
      plugging a board into your computer is not enough to power it and other
      peripherals.

    • Double check all soldering joints and connections. Flakey connections
      cause many mysterious problems. See the guide to excellent soldering for examples of good solder joints.

If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:

  • Platform/operating system (i.e. Raspberry Pi with Raspbian operating system,
    Windows 32-bit, Windows 64-bit, Mac OSX 64-bit, etc.): INSERT PLATFORM/OPERATING
    SYSTEM HERE

  • Python version (run python -version or python3 -version): INSERT PYTHON
    VERSION HERE

  • Error message you are receiving, including any Python exception traces: INSERT
    ERROR MESAGE/EXCEPTION TRACES HERE
    *

  • List the steps to reproduce the problem below (if possible attach code or commands
    to run): LIST REPRO STEPS BELOW

I am using the stepper motor code provided in this library to drive a stepper motor using this AdaFruit HAT. Now this stepper motor requires a certain voltage i.e. 2V but I can't see in the code where this voltage or current are specified for the stepper motor? Why is this? Also can specify different voltages for 2 stepper motors connected to the same HAT? Again where is this in the Python code?

Problems with Microstepping

In Adafruit_MotorHAT module:


  if (stepstyle == Adafruit_MotorHAT.MICROSTEP):
     # this is an edge case, if we are in between full steps, lets just keep going
     # so we end on a full step
     while (lateststep != 0) and (lateststep != self.MICROSTEPS):
        lateststep = self.oneStep(dir, stepstyle)
        time.sleep(s_per_s)

dir refers to a built-in function: in this scope the correct variable name is direction. Once this change is made, the code works as it should.

Due to the bug: moving 2 steps back and 2 steps forward causes significant drift in every cycle - observable to the eye within 3-4 cycles.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.