2a57eb4ac3f09d3928cb4113b43ce6595a9f7bee
[clinton/Smoothieware.git] / src / modules / tools / zprobe / ZProbe.cpp
1 /*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 #include "ZProbe.h"
9
10 #include "Kernel.h"
11 #include "BaseSolution.h"
12 #include "Config.h"
13 #include "Robot.h"
14 #include "StepperMotor.h"
15 #include "StreamOutputPool.h"
16 #include "Gcode.h"
17 #include "Conveyor.h"
18 #include "Stepper.h"
19 #include "checksumm.h"
20 #include "ConfigValue.h"
21 #include "SlowTicker.h"
22 #include "Planner.h"
23 #include "SerialMessage.h"
24 #include "PublicDataRequest.h"
25 #include "EndstopsPublicAccess.h"
26 #include "PublicData.h"
27 #include "LevelingStrategy.h"
28
29 // strategies we know about
30 #include "DeltaCalibrationStrategy.h"
31 #include "ThreePointStrategy.h"
32
33 #define enable_checksum CHECKSUM("enable")
34 #define probe_pin_checksum CHECKSUM("probe_pin")
35 #define debounce_count_checksum CHECKSUM("debounce_count")
36 #define slow_feedrate_checksum CHECKSUM("slow_feedrate")
37 #define fast_feedrate_checksum CHECKSUM("fast_feedrate")
38 #define probe_height_checksum CHECKSUM("probe_height")
39 #define gamma_max_checksum CHECKSUM("gamma_max")
40
41 // from endstop section
42 #define delta_homing_checksum CHECKSUM("delta_homing")
43
44 #define X_AXIS 0
45 #define Y_AXIS 1
46 #define Z_AXIS 2
47
48 #define STEPPER THEKERNEL->robot->actuators
49 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
50 #define Z_STEPS_PER_MM STEPS_PER_MM(Z_AXIS)
51
52 #define abs(a) ((a<0) ? -a : a)
53
54 void ZProbe::on_module_loaded()
55 {
56 // if the module is disabled -> do nothing
57 if(!THEKERNEL->config->value( zprobe_checksum, enable_checksum )->by_default(false)->as_bool()) {
58 // as this module is not needed free up the resource
59 delete this;
60 return;
61 }
62 this->running = false;
63
64 // load settings
65 this->on_config_reload(this);
66 // register event-handlers
67 register_for_event(ON_GCODE_RECEIVED);
68
69 THEKERNEL->slow_ticker->attach( THEKERNEL->stepper->get_acceleration_ticks_per_second() , this, &ZProbe::acceleration_tick );
70 }
71
72 void ZProbe::on_config_reload(void *argument)
73 {
74 this->pin.from_string( THEKERNEL->config->value(zprobe_checksum, probe_pin_checksum)->by_default("nc" )->as_string())->as_input();
75 this->debounce_count = THEKERNEL->config->value(zprobe_checksum, debounce_count_checksum)->by_default(0 )->as_number();
76
77 // get strategies to load
78 vector<uint16_t> modules;
79 THEKERNEL->config->get_module_list( &modules, leveling_strategy_checksum);
80 for( auto cs : modules ){
81 if( THEKERNEL->config->value(leveling_strategy_checksum, cs, enable_checksum )->as_bool() ){
82 bool found= false;
83 // check with each known strategy and load it if it matches
84 switch(cs) {
85 case delta_calibration_strategy_checksum:
86 this->strategies.push_back(new DeltaCalibrationStrategy(this));
87 found= true;
88 break;
89
90 case three_point_leveling_strategy_checksum:
91 // NOTE this strategy is mutually exclusive with the delta calibration strategy
92 this->strategies.push_back(new ThreePointStrategy(this));
93 found= true;
94 break;
95
96 // add other strategies here
97 //case zheight_map_strategy:
98 // this->strategies.push_back(new ZHeightMapStrategy(this));
99 // found= true;
100 // break;
101 }
102 if(found) this->strategies.back()->handleConfig();
103 }
104 }
105
106 // need to know if we need to use delta kinematics for homing
107 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
108
109 // default for backwards compatibility add DeltaCalibrationStrategy if a delta
110 // will be deprecated
111 if(this->strategies.empty()) {
112 if(this->is_delta) {
113 this->strategies.push_back(new DeltaCalibrationStrategy(this));
114 this->strategies.back()->handleConfig();
115 }
116 }
117
118 this->probe_height = THEKERNEL->config->value(zprobe_checksum, probe_height_checksum)->by_default(5.0F)->as_number();
119 this->slow_feedrate = THEKERNEL->config->value(zprobe_checksum, slow_feedrate_checksum)->by_default(5)->as_number(); // feedrate in mm/sec
120 this->fast_feedrate = THEKERNEL->config->value(zprobe_checksum, fast_feedrate_checksum)->by_default(100)->as_number(); // feedrate in mm/sec
121 this->max_z = THEKERNEL->config->value(gamma_max_checksum)->by_default(500)->as_number(); // maximum zprobe distance
122 }
123
124 bool ZProbe::wait_for_probe(int& steps)
125 {
126 unsigned int debounce = 0;
127 while(true) {
128 THEKERNEL->call_event(ON_IDLE);
129 // if no stepper is moving, moves are finished and there was no touch
130 if( !STEPPER[Z_AXIS]->is_moving() && (!is_delta || (!STEPPER[Y_AXIS]->is_moving() && !STEPPER[Z_AXIS]->is_moving())) ) {
131 return false;
132 }
133
134 // if the touchprobe is active...
135 if( this->pin.get() ) {
136 //...increase debounce counter...
137 if( debounce < debounce_count) {
138 // ...but only if the counter hasn't reached the max. value
139 debounce++;
140 } else {
141 // ...otherwise stop the steppers, return its remaining steps
142 if(STEPPER[Z_AXIS]->is_moving()){
143 steps= STEPPER[Z_AXIS]->get_stepped();
144 STEPPER[Z_AXIS]->move(0, 0);
145 }
146 if(is_delta) {
147 for( int i = X_AXIS; i <= Y_AXIS; i++ ) {
148 if ( STEPPER[i]->is_moving() ) {
149 STEPPER[i]->move(0, 0);
150 }
151 }
152 }
153 return true;
154 }
155 } else {
156 // The probe was not hit yet, reset debounce counter
157 debounce = 0;
158 }
159 }
160 }
161
162 // single probe and report amount moved
163 bool ZProbe::run_probe(int& steps, bool fast)
164 {
165 // Enable the motors
166 THEKERNEL->stepper->turn_enable_pins_on();
167 this->current_feedrate = (fast ? this->fast_feedrate : this->slow_feedrate) * Z_STEPS_PER_MM; // steps/sec
168 float maxz= this->max_z*2;
169
170 // move Z down
171 STEPPER[Z_AXIS]->move(true, maxz * Z_STEPS_PER_MM, 0); // always probes down, no more than 2*maxz
172 if(this->is_delta) {
173 // for delta need to move all three actuators
174 STEPPER[X_AXIS]->move(true, maxz * STEPS_PER_MM(X_AXIS), 0);
175 STEPPER[Y_AXIS]->move(true, maxz * STEPS_PER_MM(Y_AXIS), 0);
176 }
177
178 // start acceration hrprocessing
179 this->running = true;
180
181 bool r = wait_for_probe(steps);
182 this->running = false;
183 return r;
184 }
185
186 bool ZProbe::return_probe(int steps)
187 {
188 // move probe back to where it was
189 float fr= this->slow_feedrate*2; // nominally twice slow feedrate
190 if(fr > this->fast_feedrate) fr= this->fast_feedrate; // unless that is greater than fast feedrate
191 this->current_feedrate = fr * Z_STEPS_PER_MM; // feedrate in steps/sec
192 bool dir= steps < 0;
193 steps= abs(steps);
194
195 STEPPER[Z_AXIS]->move(dir, steps, 0);
196 if(this->is_delta) {
197 STEPPER[X_AXIS]->move(dir, steps, 0);
198 STEPPER[Y_AXIS]->move(dir, steps, 0);
199 }
200
201 this->running = true;
202 while(STEPPER[Z_AXIS]->is_moving() || (is_delta && (STEPPER[X_AXIS]->is_moving() || STEPPER[Y_AXIS]->is_moving())) ) {
203 // wait for it to complete
204 THEKERNEL->call_event(ON_IDLE);
205 }
206
207 this->running = false;
208
209 return true;
210 }
211
212 bool ZProbe::doProbeAt(int &steps, float x, float y)
213 {
214 int s;
215 // move to xy
216 coordinated_move(x, y, NAN, getFastFeedrate());
217 if(!run_probe(s)) return false;
218
219 // return to original Z
220 return_probe(s);
221 steps = s;
222
223 return true;
224 }
225
226 float ZProbe::probeDistance(float x, float y)
227 {
228 int s;
229 if(!doProbeAt(s, x, y)) return NAN;
230 return zsteps_to_mm(s);
231 }
232
233 void ZProbe::on_gcode_received(void *argument)
234 {
235 Gcode *gcode = static_cast<Gcode *>(argument);
236
237 if( gcode->has_g && gcode->g >= 29 && gcode->g <= 32) {
238 // make sure the probe is defined and not already triggered before moving motors
239 if(!this->pin.connected()) {
240 gcode->stream->printf("ZProbe not connected.\n");
241 return;
242 }
243 if(this->pin.get()) {
244 gcode->stream->printf("ZProbe triggered before move, aborting command.\n");
245 return;
246 }
247
248 if( gcode->g == 30 ) { // simple Z probe
249 gcode->mark_as_taken();
250 // first wait for an empty queue i.e. no moves left
251 THEKERNEL->conveyor->wait_for_empty_queue();
252
253 int steps;
254 if(run_probe(steps)) {
255 gcode->stream->printf("Z:%1.4f C:%d\n", steps / Z_STEPS_PER_MM, steps);
256 // move back to where it started, unless a Z is specified
257 if(gcode->has_letter('Z')) {
258 // set Z to the specified value, and leave probe where it is
259 THEKERNEL->robot->reset_axis_position(gcode->get_value('Z'), Z_AXIS);
260 } else {
261 return_probe(steps);
262 }
263 } else {
264 gcode->stream->printf("ZProbe not triggered\n");
265 }
266
267 } else {
268 // find a strategy to handle the gcode
269 for(auto s : strategies){
270 if(s->handleGcode(gcode)) {
271 gcode->mark_as_taken();
272 return;
273 }
274 }
275 gcode->stream->printf("No strategy found to handle G%d\n", gcode->g);
276 }
277
278 } else if(gcode->has_m) {
279 // M code processing here
280 if(gcode->m == 119) {
281 int c = this->pin.get();
282 gcode->stream->printf(" Probe: %d", c);
283 gcode->add_nl = true;
284 gcode->mark_as_taken();
285
286 }else {
287 for(auto s : strategies){
288 if(s->handleGcode(gcode)) {
289 gcode->mark_as_taken();
290 return;
291 }
292 }
293 }
294 }
295 }
296
297 #define max(a,b) (((a) > (b)) ? (a) : (b))
298 // Called periodically to change the speed to match acceleration
299 uint32_t ZProbe::acceleration_tick(uint32_t dummy)
300 {
301 if(!this->running) return(0); // nothing to do
302 if(STEPPER[Z_AXIS]->is_moving()) accelerate(Z_AXIS);
303
304 if(is_delta) {
305 // deltas needs to move all actuators
306 for ( int c = X_AXIS; c <= Y_AXIS; c++ ) {
307 if( !STEPPER[c]->is_moving() ) continue;
308 accelerate(c);
309 }
310 }
311
312 return 0;
313 }
314
315 void ZProbe::accelerate(int c)
316 { uint32_t current_rate = STEPPER[c]->get_steps_per_second();
317 uint32_t target_rate = int(floor(this->current_feedrate));
318
319 // Z may have a different acceleration to X and Y
320 float acc= (c==Z_AXIS) ? THEKERNEL->planner->get_z_acceleration() : THEKERNEL->planner->get_acceleration();
321 if( current_rate < target_rate ) {
322 uint32_t rate_increase = floor((acc / THEKERNEL->stepper->get_acceleration_ticks_per_second()) * STEPS_PER_MM(c));
323 current_rate = min( target_rate, current_rate + rate_increase );
324 }
325 if( current_rate > target_rate ) {
326 current_rate = target_rate;
327 }
328
329 // steps per second
330 STEPPER[c]->set_speed(current_rate);
331 }
332
333 // issue a coordinated move directly to robot, and return when done
334 // Only move the coordinates that are passed in as not nan
335 void ZProbe::coordinated_move(float x, float y, float z, float feedrate, bool relative)
336 {
337 char buf[32];
338 char cmd[64];
339
340 if(relative) strcpy(cmd, "G91 G0 ");
341 else strcpy(cmd, "G0 ");
342
343 if(!isnan(x)) {
344 int n = snprintf(buf, sizeof(buf), " X%1.3f", x);
345 strncat(cmd, buf, n);
346 }
347 if(!isnan(y)) {
348 int n = snprintf(buf, sizeof(buf), " Y%1.3f", y);
349 strncat(cmd, buf, n);
350 }
351 if(!isnan(z)) {
352 int n = snprintf(buf, sizeof(buf), " Z%1.3f", z);
353 strncat(cmd, buf, n);
354 }
355
356 // use specified feedrate (mm/sec)
357 int n = snprintf(buf, sizeof(buf), " F%1.1f", feedrate * 60); // feed rate is converted to mm/min
358 strncat(cmd, buf, n);
359 if(relative) strcat(cmd, " G90");
360
361 //THEKERNEL->streams->printf("DEBUG: move: %s\n", cmd);
362
363 // send as a command line as may have multiple G codes in it
364 struct SerialMessage message;
365 message.message = cmd;
366 message.stream = &(StreamOutput::NullStream);
367 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
368 THEKERNEL->conveyor->wait_for_empty_queue();
369 }
370
371 // issue home command
372 void ZProbe::home()
373 {
374 Gcode gc("G28", &(StreamOutput::NullStream));
375 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
376 }
377
378 float ZProbe::zsteps_to_mm(float steps)
379 {
380 return steps / Z_STEPS_PER_MM;
381 }