Sensors and Encoders
Overview
Sensors report position, color, distance, and heading. This lesson covers common REV and CTRE devices and how to read them in code.
REV Sensors
Common REV sensors used in FRC:
- NEO Built-in Encoder: Internal encoder on NEO motors (42 counts/rev). Useful for velocity and basic position control.
- Color Sensor V3: Detects color (RGB) and proximity. Connects via I2C (Onboard or MXP).
- 2m Distance Sensor: Time-of-Flight sensor measuring distances up to 2 meters with millimeter resolution.
- Through Bore Encoder: Rotary sensor measuring both relative and absolute positions via ABI quadrature output.
- Touch Sensor: Digital button input or mechanical limit switch.
REV Sensor Examples
package frc.robot.subsystems;
import com.revrobotics.spark.SparkMax;
import com.revrobotics.spark.SparkLowLevel.MotorType;
import com.revrobotics.spark.RelativeEncoder;
import com.revrobotics.spark.config.SparkMaxConfig;
public class Drivetrain extends SubsystemBase {
private SparkMax sparkMax = new SparkMax(1, MotorType.kBrushless);
private RelativeEncoder encoder = sparkMax.getEncoder();
public void configureEncoder() {
SparkMaxConfig config = new SparkMaxConfig();
// Set conversion factor: 0.05 meters per rotation
// Adjust based on your wheel diameter and gear ratio
config.encoder.positionConversionFactor(0.05);
config.encoder.velocityConversionFactor(0.05);
sparkMax.configure(config, ...);
}
public void readEncoder() {
// Get position in rotations (or meters if conversion factor set)
double pos = encoder.getPosition();
// Get velocity in RPM (or m/s if conversion factor set)
double vel = encoder.getVelocity();
}
}CTRE Sensors
Common CTRE sensors used in FRC:
- CANcoder: Absolute magnetic encoder. Retains position after power cycles. Essential for Swerve modules.
- Pigeon 2: IMU/Gyroscope. Provides Heading (Yaw), Pitch, and Roll. Used for Field-Centric driving.
- CANrange: Time-of-Flight distance sensor for obstacle detection and autonomous navigation.
- SRX Mag Encoder: Rotary position and velocity sensor for precise motion control.
CTRE Sensor Examples
package frc.robot.subsystems;
import com.ctre.phoenix6.hardware.CANcoder;
import com.ctre.phoenix6.configs.CANcoderConfiguration;
public class SwerveModule extends SubsystemBase {
// Create CANcoder on CAN ID 10
private CANcoder encoder = new CANcoder(10);
public SwerveModule() {
// Configure magnet offset (calibrate for your module)
CANcoderConfiguration config = new CANcoderConfiguration();
// Offset in rotations to align zero position
config.MagnetSensor.MagnetOffset = 0.25;
encoder.getConfigurator().apply(config);
}
/**
* Get absolute position from encoder
* @return Position in rotations (0.0 to 1.0)
*/
public double getPosition() {
return encoder.getAbsolutePosition().getValueAsDouble();
}
}Product Documentation
REV ION DocumentationREV Color Sensor V3REV 2m Distance SensorREV Through Bore EncoderCTRE Phoenix6 DocumentationCTRE CANcoderCTRE Pigeon 2CTRE CANrange