HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Motor degree movement function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
movementdegreefunctionmotor

Problem

I want to control a motor which rotates a device over a gear.

Input values for the device are from 0 to 360 degrees. The motor should always rotate the device the shorter way around. For example, if the position is 30° and target position will be 340°, it should rotate over 0° counter clockwise.

The motor controller internally has so called qc unit system. One turnaround of the the device for example constitutes to 2938500, so there is a translation of values necessary. The internal position (in qc) could become negative or positive values like an integer.

I ended up with that code and some tests to be sure it should work. Did I catch all cases? Can I still simplify the move function?

`import unittest

qc360 = 2938500

def qc2deg(qc):
return (qc / float(qc360)) * 360.0

def deg2qc(deg):
return int(round((deg/360.0) * qc360 ))

def move(is_qc, target_deg):
is_deg = qc2deg(is_qc)
diff = is_deg - target_deg

if abs(diff)

Solution

if diff < 0:
        target_qc = is_qc + deg2qc(abs(diff))
    else:
        target_qc = is_qc + deg2qc(-diff)


If diff 180.0) also can be rewritten as

if diff < 0:
        target_qc = is_qc + deg2qc(-diff - 360)
    else:
        target_qc = is_qc + deg2qc(-diff + 360)


where the cases only differ in signs of 360, which suggests that you are looking for the remainder -diff % 360; notice that python supports the remainder of floats.

To get rid of ugly leading -, you may want to calculate diff as

diff = target_deg - is_deg

Code Snippets

if diff < 0:
        target_qc = is_qc + deg2qc(abs(diff))
    else:
        target_qc = is_qc + deg2qc(-diff)
target_qc = is_qc + deg2qc(-diff)
if diff < 0:
        target_qc = is_qc + deg2qc(-diff - 360)
    else:
        target_qc = is_qc + deg2qc(-diff + 360)
diff = target_deg - is_deg

Context

StackExchange Code Review Q#70269, answer score: 3

Revisions (0)

No revisions yet.