This repository has been archived on 2025-06-01. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
compLIB/compLib/Encoder.py
2021-09-05 11:11:53 +01:00

72 lines
No EOL
2 KiB
Python

import atexit
from enum import Enum
from compLib.LogstashLogging import Logging
from compLib.Spi import Spi, Register
MOTOR_COUNT = 4
encoder_start_values = [0] * (MOTOR_COUNT + 1)
class Encoder(object):
"""Class used to read the encoders
"""
@staticmethod
def read_raw(port: int) -> int:
"""Read raw encoder from a specified port. Will not be reset to 0 at start.
:param port: Port, which the motor is connected to. 1-4 allowed
:raises: IndexError
:return: Current encoder position
"""
if port <= 0 or port > MOTOR_COUNT:
raise IndexError("Invalid encoder port specified!")
if port == 1:
return Spi.read(Register.MOTOR_1_POS_B3, 4)
elif port == 2:
return Spi.read(Register.MOTOR_2_POS_B3, 4)
elif port == 3:
return Spi.read(Register.MOTOR_3_POS_B3, 4)
elif port == 4:
return Spi.read(Register.MOTOR_4_POS_B3, 4)
@staticmethod
def read(port: int) -> int:
"""Read encoder from a specified port
:param port: Port, which the motor is connected to. 1-4 allowed
:raises: IndexError
:return: Current encoder position
"""
if port <= 0 or port > MOTOR_COUNT:
raise IndexError("Invalid encoder port specified!")
diff = Encoder.read_raw(port) - encoder_start_values[port]
if diff > 2 ** 31:
diff -= 2 ** 32
return diff
@staticmethod
def clear(port: int):
"""Reset encoder position to 0
:param port: Port, which the motor is connected to. 1-4 allowed
:raises: IndexError
"""
if port <= 0 or port > MOTOR_COUNT:
raise IndexError("Invalid encoder port specified!")
encoder_start_values[port] = Encoder.read_raw(port)
@staticmethod
def clear_all():
"""Reset all encoder positions to 0
"""
for i in range(1, MOTOR_COUNT + 1):
encoder_start_values[i] = Encoder.read_raw(i)