schodet / nxt-python

NXT-Python is a python driver/interface for the Lego Mindstorms NXT robot based on NXT_python.
https://ni.srht.site/nxt-python/latest/
GNU General Public License v3.0
232 stars 72 forks source link

[NOOB QUESTION]: How to get rotation angle of motor? #198

Closed Starchaser0 closed 4 months ago

Starchaser0 commented 4 months ago

Noob Question:

Context:

I am currently working on a diy racing wheel that works by taking the angle of a servo motor and using it as joystick input.

I happen to have some old NXT and Technic parts laying around, so I decided to use those. After some looking, I finally found this amazing project, and started playing around with it.

However, I am confused by the documentation, and have not figured out how to isolate the rotation angle of a given motor. Any pointers would be appreciated!

I've tried using get_tacho(), and I couldn't figure out how to use OutputState and TachoInfo.

NOTE: The documentation isn't bad, I'm just relatively new to this kind of programming, so I'm likely the problem here lol

Thank you for helping make this a reality!

Le specs:

schodet commented 4 months ago

You can use the get_motor function to get a Motor object, then get_tacho to get the counter values. It returns a TachoInfo object which contains the tacho_count member which is an absolute counter value.

Something like this:

#!/usr/bin/env python3
"""NXT-Python example to read motor angle."""
import time

import nxt.locator
import nxt.sensor
import nxt.sensor.generic

with nxt.locator.find() as b:
    motor = b.get_motor(nxt.motor.Port.A)

    while True:
        angle = motor.get_tacho().tacho_count
        print(angle)
        time.sleep(0.5)

I did not touch the motor module yet, so it still lacks good documentation (https://ni.srht.site/nxt-python/latest/api/motor.html#nxt.motor.Motor).

Starchaser0 commented 4 months ago

Thanks for responding so quickly!

The solution you posted works very well. I did add angle = None after print(angle) to prevent high memory usage though.

Maybe once I've learned enough, I could help expand the documentation/examples. :)

Once again, thank you for making this a reality!

schodet commented 4 months ago

I did add angle = None after print(angle) to prevent high memory usage though.

No reason to do this, python will handle memory for you.

Starchaser0 commented 4 months ago

No reason to do this, python will handle memory for you.

In theory lol... My laptop froze up after a while of running it, but adding this seemed to fix the issue, so idk.