Skip to content

Code explanation

Manuel Cerqueira da Silva edited this page Dec 26, 2022 · 1 revision

MotorController

The MotorController is used to control the speed of a motor using an encoder and a PID controller.

Member Variables

  • Encoder encoder_: An instance of the Encoder class that is used to measure the speed of the motor.
  • int pwm_motor_pin_: The pin number of the PWM output that is used to control the speed of the motor.
  • long last_count_: The number of encoder counts that were recorded during the last iteration of the PID control loop.
  • unsigned long last_time_: The time that the last iteration of the PID control loop was run.
  • float pulses_per_revolution_: The number of pulses that the encoder generates per revolution of the motor. This value is used to convert the number of encoder counts into RPM.
  • float kp_, float ki_, float kd_: The constants for the PID controller. These values are used to calculate the output of the PID controller based on the error between the target and current RPM.
  • float error_sum_: The sum of the errors that have occurred during previous iterations of the PID control loop. This value is used to calculate the integral term of the PID controller.
  • float last_error_: The error that occurred during the last iteration of the PID control loop. This value is used to calculate the derivative term of the PID controller.

Member Functions

  • MotorController(int enc_pin_a, int enc_pin_b, int pwm_motor_pin): The constructor for the MotorController class. This function initializes the Encoder object and sets the pin number of the PWM output.
  • void SetPIDConstants(float kp, float ki, float kd): A function that sets the constants for the PID controller.
  • void SetSpeed(int target_rpm): A function that is used to set the target RPM of the motor. This function calculates the error between the target and current RPM, and uses this error to calculate the output of the PID controller. The output of the PID controller is then used to set the speed of the motor.
  • float GetRpm(): A function that calculates the current RPM of the motor based on the number of encoder counts and the elapsed time.
  • void InterruptHandler(): A function that is called when the encoder generates an interrupt. This function updates the encoder count.

Software Hardware

Clone this wiki locally