Class CANandcoder

java.lang.Object
com.reduxrobotics.canand.CANandDevice
com.reduxrobotics.sensors.canandcoder.CANandcoder

public class CANandcoder extends CANandDevice
Class for the CAN interface of the CANandcoder.

If you are using a CANandcoder with Spark Max or Talon with the PWM output, see our Spark Max docs or our Talon SRX docs for information on how to use the encoder with the Rev and CTRE APIs.

In general, the Java API will use SI units (seconds, meters, deg Celsius), with the exception of rotation being expressed in turns (+1 rotation == 1.0)

Operations that receive data from the device (position, velocity, faults, temperature) generally do not block. The object receives data asynchronously from the CAN packet receive thread and reads thus return the last data received.

Operations that set settings or change offsets will generally wait for up to 50ms by default as they will usually wait for a confirmation packet to be received in response -- unless the blocking timeout is set to zero, in which case the operation swill not block.

Example code:
 CANandcoder canandcoder = new CANandcoder(0); // encoder id 0 
 
 // Reading the CANandcoder
 canandcoder.getPosition(); // returns a multi-turn relative position, in rotations (turns)
 canandcoder.getAbsPosition(); // returns an absolute position bounded from [0..1) over one rotation
 canandcoder.getVelocity(); // returns measured velocity in rotations per second
 
 // Updating position
 canandcoder.setPosition(-3.5); // sets the relative position to -3.5 turns with default confirmation timeout of 50 ms (does not persist on reboot)
 canandcoder.setPosition(0.330, 0); // sets the absolute position to 0.5 turns without blocking for confirmation (persists on reboot)
 canandcoder.zeroAll(); // sets both the relative and absolute position to zero
 
 // Changing configuration
 CANandcoderSettings settings = new CANandcoderSettings();
 settings.setVelocityFilterPeriod(25); // sets the velocity filter averaging period to 25 ms
 settings.setInvertDirection(true); // make positive be clockwise instead of ccw opposite the sensor face
 settings.setPositionFramePeriod(0.010); // set the position frame period to be sent every 10 ms
 canandcoder.setSettings(settings, 0.050); // apply the new settings to the device, with maximum 50 ms timeout per settings op
 
 // Faults
 canandcoder.clearStickyFaults(); // clears all sticky faults (including the power cycle flag). This call does not block.
 
 // this flag will always be true on boot until the sticky faults have been cleared, 
 // so if this is true the encoder has rebooted sometime between clearStickyFaults and now.
 CANandcoderFaults faults = canandcoder.getStickyFaults(); // fetches faults
 System.out.printf("Encoder rebooted: %d\n", faults.powerCycle());
 
 // Timestamped data
 FrameData<Double> posFrame = canandcoder.getPositionFrame().getFrameData(); // gets current position + timestamp together
 posFrame.getValue(); // fetched position in rotations
 posFrame.GetTimestamp(); // timestamp of the previous position
 
  • Field Details

    • position

      protected Frame<Double> position
      internal Frame variable holding current relative position state
    • absPosition

      protected Frame<Double> absPosition
      internal Frame variable holding current absolute position state
    • velocity

      protected Frame<Double> velocity
      internal Frame variable holding current velocity state
    • status

      protected Frame<CANandcoderStatus> status
      internal Frame variable holding current status value state
    • CAN_MSG_POSITION_OUTPUT

      public static final int CAN_MSG_POSITION_OUTPUT
      CAN id for Position frame
      See Also:
    • CAN_MSG_VELOCITY_OUTPUT

      public static final int CAN_MSG_VELOCITY_OUTPUT
      CAN id for Velocity frame
      See Also:
    • CAN_MSG_RAW_POSITION_OUTPUT

      public static final int CAN_MSG_RAW_POSITION_OUTPUT
      CAN id for Raw position frame
      See Also:
    • SETTING_COMMAND_RESET_FACTORY_DEFAULT_KEEP_ZERO

      public static final byte SETTING_COMMAND_RESET_FACTORY_DEFAULT_KEEP_ZERO
      setting command for Factory defaults, but keep the encoder zero offset
      See Also:
    • VEL_TICK_PER_RPS

      public static final double VEL_TICK_PER_RPS
      Conversion factor from frame ticks per second to rotations per second.
      See Also:
    • COUNTS_PER_ROTATION

      public static final double COUNTS_PER_ROTATION
      Conversion factor for number of encoder ticks per rotation.
      See Also:
  • Constructor Details

    • CANandcoder

      public CANandcoder(int canID)
      Instantiates a new CANandcoder object. This object will be constant with respect to whatever CAN id assigned to it, so if a device changes id it may change which device this object reads from.
      Parameters:
      canID - the device id to use [0..63]
  • Method Details

    • getPosition

      public double getPosition()
      Gets the current integrated relative position in rotations.

      This value does not wrap around, so turning a sensed axle multiple rotations will return multiple sensed rotations of position. By default, positive is in the counter-clockwise direction from the sensor face.

      On encoder power-on, unlike the absolute value, this value will always initialize to zero.

      Returns:
      signed relative position in rotations (range [-131072.0..131071.999938396484])
    • getAbsPosition

      public double getAbsPosition()
      Gets the current absolute position of the encoder, in a scaled value from 0 inclusive to 1 exclusive. By default, higher values are in the counter-clockwise direction from the sensor face.

      This value will persist across encoder power cycles making it appropriate for swerves/arms/etc.

      Returns:
      absolute position in fraction of a rotation [0..1)
    • setPosition

      public boolean setPosition(double newPosition, double timeout)
      Sets the new relative (multi-turn) position of the encoder to the given value.

      Note that this does not update the absolute position, and this value is lost on a power cycle. To update the absolute position, use setAbsPosition(double, double)

      Parameters:
      newPosition - new relative position in rotations (acceptable range [-131072.0..131071.99993896484])
      timeout - maximum time in seconds to wait for a setting to be confirmed. Set to 0 to not check (and not block).
      Returns:
      true on success, false on timeout
    • setPosition

      public boolean setPosition(double newPosition)
      Sets the new relative (multi-turn) position of the encoder to the given value, with a confirmation timeout of 50 ms.

      Note that this does not update the absolute position, and this value is lost on a power cycle. To update the absolute position, use setAbsPosition(double, double)

      Parameters:
      newPosition - new relative position in rotations (acceptable range [-131072.0..131071.99993896484])
      Returns:
      true on success, false on timeout
    • setAbsPosition

      public boolean setAbsPosition(double newPosition, double timeout)
      Sets the new absolute position value for the encoder which will persist across reboots
      Parameters:
      newPosition - new absolute position in fraction of a rotation (acceptable range [0..1))
      timeout - maximum time in seconds to wait for the operation to be confirmed. Set to 0 to not check (and not block).
      Returns:
      true on success, false on timeout
    • setAbsPosition

      public boolean setAbsPosition(double newPosition)
      Sets the new absolute position value for the encoder which will persist across reboots with default timeout of 50 ms
      Parameters:
      newPosition - new absolute position in fraction of a rotation (acceptable range [0..1))
      Returns:
      true on success, false on timeout
    • zeroAll

      public boolean zeroAll(double timeout)
      Sets both the current absolute and relative encoder position to 0 -- generally equivalent to pressing the physical zeroing button on the encoder.
      Parameters:
      timeout - maximum time in seconds to wait for each operation (zeroing absolute and relative position) to be confirmed. Set to 0 to not check (and not block).
      Returns:
      true on success, false on timeout
    • zeroAll

      public boolean zeroAll()
      Sets both the current absolute and relative encoder position to 0 -- generally equivalent to pressing the physical zeroing button on the encoder.

      This will wait up to 50 ms to each of the absolute and relative positions, so up to 100 ms total (realistically less)

      Returns:
      true on success, false on timeout
    • getVelocity

      public double getVelocity()
      Returns the measured velocity in rotations per second.
      Returns:
      velocity, in rotations (turns) per second
    • magnetInRange

      public boolean magnetInRange()
      Returns whether the encoder magnet is in range of the sensor or not. This can be seen visually on the sensor -- a green LED is in range, whereas a red LED is out of range.
      Returns:
      whether the output shaft magnet is in range.
    • getStickyFaults

      public CANandcoderFaults getStickyFaults()
      Returns sticky faults. Sticky faults are the active faults, except once set they do not become unset until clearStickyFaults() is called.
      Returns:
      CANandcoderFaults of the sticky faults.
      See Also:
    • getActiveFaults

      public CANandcoderFaults getActiveFaults()
      Returns an object representing currently active faults. Active faults are only active for as long as the error state exists.
      Returns:
      CANandcoderFaults of the active faults
      See Also:
    • getTemperature

      public double getTemperature()
      Get onboard encoder temperature readings in degrees Celsius.
      Returns:
      temperature in degrees Celsius
    • clearStickyFaults

      public void clearStickyFaults()
      Clears sticky faults.

      It is recommended to clear this during initialization, so one can check if the encoder loses power during operation later.

      This call does not block, so it may take up to the next status frame (default every 1000 ms) for the sticky faults to be updated. To check for validity, use CANandcoderFaults.faultsValid() for faults returned by getStickyFaults()

    • setPartyMode

      public void setPartyMode(int level)
      Controls "party mode" -- an encoder identification tool that blinks the onboard LED various colors at a user-specified strobe period. The strobe period of the LED will be (50 milliseconds * level). Setting this to 0 disables party mode. This function does not block.
      Parameters:
      level - the party level value to set.
    • getSettings

      public CANandcoderSettings getSettings(double timeout)
      Fetches the CANandcoder's current configuration in a blocking manner. This function will block for at least about 0.2-0.3 seconds waiting for the encoder to reply, so it is best to put this in a teleop or autonomous init function, rather than the main loop.
      Parameters:
      timeout - maximum number of seconds to wait for settings before giving up
      Returns:
      CANandcoderSettings representing the device's configuration, or null on timeout.
    • getSettings

      public CANandcoderSettings getSettings()
      Fetches the CANandcoder's current configuration in a blocking manner. This function will block for up to 0.350 seconds waiting for the encoder to reply, so it is best to put this in a teleop or autonomous init function, rather than the main loop.
      Returns:
      CANandcoderSettings representing the device's configuration, or null on timeout.
    • startFetchSettings

      public void startFetchSettings()
      Tells the CANandcoder to begin transmitting its settings; once they are all transmitted (after ~200-300ms), the values can be retrieved from getSettingsAsync()
    • getSettingsAsync

      public CANandcoderSettings getSettingsAsync()
      Non-blockingly returns a CANandcoderSettings object of the most recent known settings values received from the encoder.

      Most users will probably want to use getSettings(double) instead.

      One can call this after a startFetchSettings() call, and use CANandcoderSettings.allSettingsReceived() to check if/when all values have been seen. As an example:
       
       // somewhere in an init function
       CANandcoder enc = new CANandcoder(0); 
       enc.startFetchSettings();
       
       // ...
       // somewhere in a loop function
       
       if (enc.getSettingsAsync().allSettingsReceived()) {
         // do something with the settings object
         System.out.printf("Encoder velocity frame period: %d\n", enc.getSettingsAsync().getVelocityFramePeriod());
       }
       
      If this is called after setSettings(CANandcoderSettings), this method will return a settings object where only the fields where the encoder has echoed the new values back will be populated. To illustrate this, consider the following:
        // somewhere in a loop 
       enc.setSettings(new CANandcoderSettings().setVelocityFramePeriod(0.100));
       enc.getSettingsAsync().getVelocityFramePeriod(); // will likely return -1, as the encoder hasn't confirmed the previous transaction
       
       // after up to 100 ms...
       enc.getSettingsAsync().getVelocityFramePeriod(); // will likely return 100
       
      Returns:
      CANandcoderSettings object of known settings
      See Also:
    • setSettings

      public boolean setSettings(CANandcoderSettings settings, double timeout)
      Applies the settings from a CANandcoderSettings object to the CANandcoder. For more information, see the CANandcoderSettings class documentation.
      Parameters:
      settings - the CANandcoderSettings to update the encoder with
      timeout - maximum time in seconds to wait for each setting to be confirmed. Set to 0 to not check (and not block).
      Returns:
      true if successful, false if a setting operation timed out
      See Also:
    • setSettings

      public boolean setSettings(CANandcoderSettings settings)
      Applies the settings from a CANandcoderSettings object to the CANandcoder. For more information, see the CANandcoderSettings class documentation.
      Parameters:
      settings - the CANandcoderSettings to update the encoder with
      Returns:
      true if successful, false if a setting operation timed out
      See Also:
    • resetFactoryDefaults

      public CANandcoderSettings resetFactoryDefaults(boolean clearZero, double timeout)
      Resets the encoder to factory defaults.
      Parameters:
      clearZero - whether to clear the zero offset from the encoder's memory as well
      timeout - how long to wait for the new settings to be confirmed by the encoder in seconds (suggested at least 0.35 seconds)
      Returns:
      CANandcoderSettings object if successful, null on confirmation timeout or if timeout is 0
    • resetFactoryDefaults

      public CANandcoderSettings resetFactoryDefaults(boolean clearZero)
      Resets the encoder to factory defaults, waiting up to 500 ms to confirm the settings changes.
      Parameters:
      clearZero - whether to clear the zero offset from the encoder's memory as well
      Returns:
      CANandcoderSettings object if successful, null on confirmation timeout or if timeout is 0
    • isPresent

      public boolean isPresent(double timeout)
      Checks whether or not the CANandcoder has sent a message within the last timeout seconds.
      Parameters:
      timeout - window to check for message updates in seconds
      Returns:
      true if there has been a message within the last timeout seconds, false if not
    • isPresent

      public boolean isPresent()
      Checks whether or not the CANandcoder has sent a message within the last 2000 milliseconds.
      Returns:
      true if there has been a message within the last 2000 milliseconds, false if not
    • getPositionFrame

      public Frame<Double> getPositionFrame()
      Returns the current relative position frame.
      Returns:
      the current position frame, which will hold the current position in the same units as getPosition()
    • getAbsPositionFrame

      public Frame<Double> getAbsPositionFrame()
      Returns the current absolute position frame.
      Returns:
      the current position frame, which will hold the current position in the same units as getAbsPosition()
    • getVelocityFrame

      public Frame<Double> getVelocityFrame()
      Returns the current velocity frame, which includes CAN timestamp data.
      Returns:
      the current velocity frame, which will hold the current velocity in the same units as getVelocity()
    • getStatusFrame

      public Frame<CANandcoderStatus> getStatusFrame()
      Returns the current status frame, which includes CAN timestamp data. FrameData objects are immutable.
      Returns:
      the current status frame, as a CANandcoderStatus record.
    • handleMessage

      public void handleMessage(CANandMessage msg)
      Description copied from class: CANandDevice
      A callback called when a Redux CAN message is received and should be parsed. Subclasses of CANandDevice should override this to update their internal state accordingly.

      handleMessage will be called on all Redux CAN packets received by the vendordep that match the CANandAddress returned by CANandDevice.getAddress().

      Specified by:
      handleMessage in class CANandDevice
      Parameters:
      msg - a CANandMessage representing the received message.
    • getAddress

      public CANandAddress getAddress()
      Description copied from class: CANandDevice
      Returns the CANandAddress representing the combination of CAN bus and CAN device ID that this CANandDevice refers to.

      Implementing device subclasses should likely construct a new CANandAddress in their constructor and return it here.

      Specified by:
      getAddress in class CANandDevice
      Returns:
      the CANandAddress for the device.