patternpythonMinor
Motor degree movement function
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
`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)
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 asif 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 asdiff = target_deg - is_degCode 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_degContext
StackExchange Code Review Q#70269, answer score: 3
Revisions (0)
No revisions yet.