ClearCore Library
Loading...
Searching...
No Matches
FollowEncoder.cpp

Return to SDK Examples for Microchip Studio

1/*
2 * Title: FollowEncoder
3 *
4 * Objective:
5 * This example demonstrates the ClearCore's Encoder Input module
6 * functionality.
7 *
8 * Description:
9 * This example takes input signals from an external encoder through the
10 * CL-ENCRD-DFIN Encoder Adapter Board, and uses the encoder position
11 * or velocity to control a ClearPath-SD servo.
12 *
13 * Requirements:
14 * 1. A ClearPath-SD motor must be connected to Connector M-0.
15 * 2. The connected ClearPath motor must be configured through the MSP software
16 * for Step and Direction mode (In MSP select Mode>>Step and Direction).
17 * 3. The ClearPath motor must be set to use the HLFB mode "ASG-Position
18 * w/Measured Torque" with a PWM carrier frequency of 482 Hz through the MSP
19 * software (select Advanced>>High Level Feedback [Mode]... then choose
20 * "ASG-Position w/Measured Torque" from the dropdown, make sure that 482 Hz
21 * is selected in the "PWM Carrier Frequency" dropdown, and hit the OK
22 * button).
23 * 4. Set the Input Format in MSP for "Step + Direction".
24 * 5. An external encoder much be wired to the CL-ENCRD-DFIN Encoder Adapter Board,
25 * and the board connected to the ClearCore I/O Header. See the ClearCore User
26 * Manaual for connector pinouts.
27 *
28 * ** Reminder: When using the CL-ENCRD-DFIN Encoder Adapter Board, ClearCore
29 * connectors DI-6, DI-7, and DI-8 are unavailable and should be left Not
30 * Connected to any external device.
31 *
32 * ** Note: Homing is optional and not required in this operational mode or in
33 * this example.
34 *
35 * ** Note: Set the Input Resolution in MSP the same as your motor's Positioning
36 * Resolution spec if you'd like the pulses sent by ClearCore to command a
37 * move of the same number of Encoder Counts, a 1:1 ratio.
38 *
39 * Links:
40 * ** ClearCore Documentation: https://teknic-inc.github.io/ClearCore-library/
41 * ** ClearCore Manual: https://www.teknic.com/files/downloads/clearcore_user_manual.pdf
42 * ** ClearPath Manual (DC Power): https://www.teknic.com/files/downloads/clearpath_user_manual.pdf
43 * ** ClearPath Manual (AC Power): https://www.teknic.com/files/downloads/ac_clearpath-mc-sd_manual.pdf
44 *
45 *
46 * Copyright (c) 2020 Teknic Inc. This work is free to use, copy and distribute under the terms of
47 * the standard MIT permissive software license which can be found at https://opensource.org/licenses/MIT
48 */
49
50#include "ClearCore.h"
51
52
53// Set the operational mode of this example:
54// If true, the motor will faithfully follow the encoder's position.
55// If false, the motor will faithfully follow the encoder's velocity instead.
56bool followPosition = false;
57
58// Define the velocity and acceleration limits to be used for positional moves
59int32_t velocityLimit = 100000; // pulses per sec
60int32_t accelerationLimit = 1000000; // pulses per sec^2
61
62// Set to true if the sense of encoder direction should be inverted.
63bool swapDirection = false;
64// Set to true if index detection should occur on the falling edge,
65// rather than the rising edge.
66bool indexInverted = false;
67
68int main(void) {
69 // Set up serial communication and wait up to 5 seconds for a port to open
70 uint32_t timeout = 5000;
71 uint32_t startTime = Milliseconds();
72 ConnectorUsb.PortOpen();
73 while (!ConnectorUsb && Milliseconds() - startTime < timeout) {
74 continue;
75 }
76
77 // Enable the encoder input feature
78 EncoderIn.Enable(true);
79 // Zero the position to start
80 EncoderIn.Position(0);
81 // Set the encoder direction
82 EncoderIn.SwapDirection(swapDirection);
83 // Set the sense of index detection (true = rising edge, false = falling edge)
84 EncoderIn.IndexInverted(indexInverted);
85
86 // Motor setup:
87 MotorMgr.MotorModeSet(MotorManager::MOTOR_ALL, Connector::CPM_MODE_STEP_AND_DIR);
88
89 // Set the motor's HLFB mode to bipolar PWM
90 ConnectorM0.HlfbMode(MotorDriver::HLFB_MODE_HAS_BIPOLAR_PWM);
91 // Set the HFLB carrier frequency to 482 Hz
92 ConnectorM0.HlfbCarrier(MotorDriver::HLFB_CARRIER_482_HZ);
93
94 // Set velocity and acceleration limits for each move
95 ConnectorM0.VelMax(velocityLimit);
96 ConnectorM0.AccelMax(accelerationLimit);
97
98 // Enables the motor; homing will begin automatically if enabled
99 ConnectorM0.EnableRequest(true);
100 ConnectorUsb.SendLine("Motor Enabled");
101
102 // Waits for HLFB to assert (waits for homing to complete if applicable)
103 ConnectorUsb.SendLine("Waiting for HLFB...");
104 while (ConnectorM0.HlfbState() != MotorDriver::HLFB_ASSERTED) {
105 continue;
106 }
107 ConnectorUsb.SendLine("Motor Ready");
108
109 // Variables to store encoder state
110 int32_t position = 0;
111 int32_t velocity = 0;
112 int32_t indexPosition = 0;
113 int32_t lastIndexPosition = 0;
114 bool quadratureError = false;
115
116 // Use a timeout to print out encoder information every 500 ms.
117 char info[100];
118 timeout = 500;
119 startTime = Milliseconds();
120
121 while (!quadratureError) {
122 position = EncoderIn.Position();
123 velocity = EncoderIn.Velocity();
124 indexPosition = EncoderIn.IndexPosition();
125 quadratureError = EncoderIn.QuadratureError();
126
127 // Print out encoder info at a fixed timeout rate
128 if (Milliseconds() - startTime >= timeout) {
129 if (followPosition) {
130 snprintf(info, 100, "Encoder position: %ld counts", position);
131 }
132 else {
133 snprintf(info, 100, "Encoder velocity: %ld counts/sec", velocity);
134 }
135 ConnectorUsb.SendLine(info);
136 startTime = Milliseconds();
137 }
138
139 if (indexPosition != lastIndexPosition) {
140 snprintf(info, 100, "Detected index at position: %ld",
141 EncoderIn.IndexPosition());
142 ConnectorUsb.SendLine(info);
143 }
144
145 lastIndexPosition = indexPosition;
146
147 // Check if an alert is currently preventing motion
148 if (ConnectorM0.StatusReg().bit.AlertsPresent) {
149 ConnectorUsb.SendLine("Motor status: 'In Alert'. Move Canceled.");
150 continue;
151 }
152
153 if (followPosition) {
154 // Move the motor to the current position read by the encoder
155 ConnectorM0.Move(position, MotorDriver::MOVE_TARGET_ABSOLUTE);
156 }
157 else {
158 // Command the motor to follow the encoder's velocity
159 ConnectorM0.MoveVelocity(velocity);
160 }
161 }
162
163 // We detected a quadrature error!
164 ConnectorM0.MoveVelocity(0);
165 ConnectorM0.EnableRequest(false);
166 ConnectorUsb.SendLine("Quadrature error detected. Stopping motion...");
167}
uint32_t Milliseconds(void)
Number of milliseconds since the ClearCore was initialized.
int32_t IndexPosition()
Read the last index position of the encoder.
void SwapDirection(bool isSwapped)
Swap the sense of positive and negative encoder directions.
void Enable(bool isEnabled)
Set whether the encoder input should be active or not.
int32_t Position()
Read the current position of the encoder.
bool QuadratureError()
Query for a quadrature error.
volatile const int32_t & Velocity()
Read the velocity of the encoder input (counts per second)
Definition EncoderInput.h:173
void IndexInverted(bool invert)
Invert the edge that the index detection triggers on.
bool SendLine()
Send carriage return and newline characters.
Definition ISerial.h:162
void HlfbMode(HlfbModes newMode)
Sets operational mode of the HLFB to match up with the HLFB configuration of a ClearPathâ„¢ motor.
Definition MotorDriver.h:709
bool EnableRequest()
Accessor for the enable request state of the motor.
Definition MotorDriver.h:544
virtual bool MoveVelocity(int32_t velocity) override
Issues a velocity move at the specified velocity.
volatile const HlfbStates & HlfbState()
Return the latest HLFB state information.
Definition MotorDriver.h:672
bool HlfbCarrier(HlfbCarrierFrequency freq)
Set the HLFB carrier frequency signal.
Definition MotorDriver.h:773
volatile const StatusRegMotor & StatusReg()
Accessor for the current Motor Status Register.
Definition MotorDriver.h:835
virtual bool Move(int32_t dist, MoveTarget moveTarget=MOVE_TARGET_REL_END_POSN) override
Issues a positional move for the specified distance.
bool MotorModeSet(MotorPair motorPair, Connector::ConnectorModes newMode)
Sets the operational mode for the specified MotorDriver connectors.
void PortOpen() override
void AccelMax(uint32_t accelMax)
Sets the maximum acceleration in step pulses per second^2.
void VelMax(uint32_t velMax)
Sets the maximum velocity for position moves, in step pulses per second.
struct ClearCore::MotorDriver::StatusRegMotor::@2 bit
uint32_t AlertsPresent
Definition MotorDriver.h:301