// Directs and executes one line of formatted input from protocol_process. While mostly // incoming streaming g-code blocks, this also directs and executes Grbl internal commands, // such as settings, initiating the homing cycle, and toggling switch states. static void protocol_execute_line(char *line) { protocol_execute_realtime(); // Runtime command check point. if (sys.abort) { return; } // Bail to calling function upon system abort #ifdef REPORT_ECHO_LINE_RECEIVED report_echo_line_received(line); #endif if (line[0] == 0) { // Empty or comment line. Send status message for syncing purposes. report_status_message(STATUS_OK); } else if (line[0] == '$') { // Grbl '$' system command report_status_message(system_execute_line(line)); } else if (sys.state == STATE_ALARM) { // Everything else is gcode. Block if in alarm mode. report_status_message(STATUS_ALARM_LOCK); } else { // Parse and execute g-code block! report_status_message(gc_execute_line(line)); } }
// Block until all buffered steps are executed or in a cycle state. Works with feed hold // during a synchronize call, if it should happen. Also, waits for clean cycle end. void protocol_buffer_synchronize() { // If system is queued, ensure cycle resumes if the auto start flag is present. protocol_auto_cycle_start(); do { protocol_execute_realtime(); // Check and execute run-time commands if (sys.abort) { return; } // Check for system abort } while (plan_get_current_block() || (sys.state == STATE_CYCLE)); }
// Performs a soft limit check. Called from mc_line() only. Assumes the machine has been homed, // the workspace volume is in all negative space, and the system is in normal operation. void limits_soft_check(float *target) { uint8_t idx; uint8_t soft_limit_error = false; for (idx=0; idx<N_AXIS; idx++) { #ifdef HOMING_FORCE_SET_ORIGIN // When homing forced set origin is enabled, soft limits checks need to account for directionality. // NOTE: max_travel is stored as negative if (bit_istrue(settings.homing_dir_mask,bit(idx))) { if (target[idx] < 0 || target[idx] > -settings.max_travel[idx]) { soft_limit_error = true; } } else { if (target[idx] > 0 || target[idx] < settings.max_travel[idx]) { soft_limit_error = true; } } #else // NOTE: max_travel is stored as negative if (target[idx] > 0 || target[idx] < settings.max_travel[idx]) { soft_limit_error = true; } #endif if (soft_limit_error) { // Force feed hold if cycle is active. All buffered blocks are guaranteed to be within // workspace volume so just come to a controlled stop so position is not lost. When complete // enter alarm mode. if (sys.state == STATE_CYCLE) { system_set_exec_state_flag(EXEC_FEED_HOLD); do { protocol_execute_realtime(); if (sys.abort) { return; } } while ( sys.state != STATE_IDLE ); } mc_reset(); // Issue system reset and ensure spindle and coolant are shutdown. system_set_exec_alarm_flag((EXEC_ALARM_SOFT_LIMIT|EXEC_CRITICAL_EVENT)); // Indicate soft limit critical event protocol_execute_realtime(); // Execute to enter critical event loop and system abort return; } } }
// Execute dwell in seconds. void mc_dwell(float seconds) { if (sys.state == STATE_CHECK_MODE) { return; } uint16_t i = floor(1000/DWELL_TIME_STEP*seconds); protocol_buffer_synchronize(); delay_ms(floor(1000*seconds-i*DWELL_TIME_STEP)); // Delay millisecond remainder. while (i-- > 0) { // NOTE: Check and execute realtime commands during dwell every <= DWELL_TIME_STEP milliseconds. protocol_execute_realtime(); if (sys.abort) { return; } _delay_ms(DWELL_TIME_STEP); // Delay DWELL_TIME_STEP increment } }
// Perform homing cycle to locate and set machine zero. Only '$H' executes this command. // NOTE: There should be no motions in the buffer and Grbl must be in an idle state before // executing the homing cycle. This prevents incorrect buffered plans after homing. void mc_homing_cycle() { // Check and abort homing cycle, if hard limits are already enabled. Helps prevent problems // with machines with limits wired on both ends of travel to one limit pin. // TODO: Move the pin-specific LIMIT_PIN call to limits.c as a function. #ifdef LIMITS_TWO_SWITCHES_ON_AXES if (limits_get_state()) { mc_reset(); // Issue system reset and ensure spindle and coolant are shutdown. bit_true_atomic(sys_rt_exec_alarm, (EXEC_ALARM_HARD_LIMIT|EXEC_CRITICAL_EVENT)); return; } #endif limits_disable(); // Disable hard limits pin change register for cycle duration // ------------------------------------------------------------------------------------- // Perform homing routine. NOTE: Special motion case. Only system reset works. // Search to engage all axes limit switches at faster homing seek rate. limits_go_home(HOMING_CYCLE_0); // Homing cycle 0 #ifdef HOMING_CYCLE_1 limits_go_home(HOMING_CYCLE_1); // Homing cycle 1 #endif #ifdef HOMING_CYCLE_2 limits_go_home(HOMING_CYCLE_2); // Homing cycle 2 #endif #ifdef HOMING_CYCLE_3 limits_go_home(HOMING_CYCLE_3); // Homing cycle 3 #endif #ifdef HOMING_CYCLE_4 limits_go_home(HOMING_CYCLE_4); // Homing cycle 4 #endif #ifdef HOMING_CYCLE_5 limits_go_home(HOMING_CYCLE_5); // Homing cycle 5 #endif protocol_execute_realtime(); // Check for reset and set system abort. if (sys.abort) { return; } // Did not complete. Alarm state set by mc_alarm. // Homing cycle complete! Setup system for normal operation. // ------------------------------------------------------------------------------------- // Gcode parser position was circumvented by the limits_go_home() routine, so sync position now. gc_sync_position(); // If hard limits feature enabled, re-enable hard limits pin change register after homing cycle. limits_init(); }
// Perform homing cycle to locate and set machine zero. Only '$H' executes this command. // NOTE: There should be no motions in the buffer and Grbl must be in an idle state before // executing the homing cycle. This prevents incorrect buffered plans after homing. void mc_homing_cycle(uint8_t cycle_mask) { // Check and abort homing cycle, if hard limits are already enabled. Helps prevent problems // with machines with limits wired on both ends of travel to one limit pin. // TODO: Move the pin-specific LIMIT_PIN call to limits.c as a function. #ifdef LIMITS_TWO_SWITCHES_ON_AXES if (limits_get_state()) { mc_reset(); // Issue system reset and ensure spindle and coolant are shutdown. system_set_exec_alarm(EXEC_ALARM_HARD_LIMIT); return; } #endif limits_disable(); // Disable hard limits pin change register for cycle duration // ------------------------------------------------------------------------------------- // Perform homing routine. NOTE: Special motion case. Only system reset works. #ifdef HOMING_SINGLE_AXIS_COMMANDS if (cycle_mask) { limits_go_home(cycle_mask); } // Perform homing cycle based on mask. else #endif { // Search to engage all axes limit switches at faster homing seek rate. limits_go_home(HOMING_CYCLE_0); // Homing cycle 0 #ifdef HOMING_CYCLE_1 limits_go_home(HOMING_CYCLE_1); // Homing cycle 1 #endif #ifdef HOMING_CYCLE_2 limits_go_home(HOMING_CYCLE_2); // Homing cycle 2 #endif } protocol_execute_realtime(); // Check for reset and set system abort. if (sys.abort) { return; } // Did not complete. Alarm state set by mc_alarm. // Homing cycle complete! Setup system for normal operation. // ------------------------------------------------------------------------------------- // Sync gcode parser and planner positions to homed position. gc_sync_position(); plan_sync_position(); // If hard limits feature enabled, re-enable hard limits pin change register after homing cycle. limits_init(); }
void punch() { if (sys.state == STATE_CHECK_MODE) { return ; } punch_stop(); // wait for current awaited commands protocol_buffer_synchronize(); // wait for the end of move do { protocol_execute_realtime(); if (sys.abort) { return; } } while ( sys.state != STATE_IDLE ); punch_activate_actuator(COMMAND_PUNCH_UNACTIVATED); punch_activate_actuator(COMMAND_PUNCH_DOWN); // wait_a_bit(); punch_wait_sensor_state(PUNCH_SENSOR_DOWN_BIT); // wait_a_bit(); punch_activate_actuator(COMMAND_PUNCH_UNACTIVATED); // wait_a_bit(); // activate the punch up punch_activate_actuator(COMMAND_PUNCH_UP); // wait_a_bit(); // activate the punch up, and release the down punch_wait_sensor_state(PUNCH_SENSOR_UP_BIT); // wait_a_bit(); }
void mc_line(float *target, float feed_rate, uint8_t invert_feed_rate) #endif { // If enabled, check for soft limit violations. Placed here all line motions are picked up // from everywhere in Grbl. if (bit_istrue(settings.flags,BITFLAG_SOFT_LIMIT_ENABLE)) { limits_soft_check(target); } // If in check gcode mode, prevent motion by blocking planner. Soft limits still work. if (sys.state == STATE_CHECK_MODE) { return; } // NOTE: Backlash compensation may be installed here. It will need direction info to track when // to insert a backlash line motion(s) before the intended line motion and will require its own // plan_check_full_buffer() and check for system abort loop. Also for position reporting // backlash steps will need to be also tracked, which will need to be kept at a system level. // There are likely some other things that will need to be tracked as well. However, we feel // that backlash compensation should NOT be handled by Grbl itself, because there are a myriad // of ways to implement it and can be effective or ineffective for different CNC machines. This // would be better handled by the interface as a post-processor task, where the original g-code // is translated and inserts backlash motions that best suits the machine. // NOTE: Perhaps as a middle-ground, all that needs to be sent is a flag or special command that // indicates to Grbl what is a backlash compensation motion, so that Grbl executes the move but // doesn't update the machine position values. Since the position values used by the g-code // parser and planner are separate from the system machine positions, this is doable. // If the buffer is full: good! That means we are well ahead of the robot. // Remain in this loop until there is room in the buffer. do { protocol_execute_realtime(); // Check for any run-time commands if (sys.abort) { return; } // Bail, if system abort. if ( plan_check_full_buffer() ) { protocol_auto_cycle_start(); } // Auto-cycle start when buffer is full. else { break; } } while (1); // Plan and queue motion into planner buffer #ifdef USE_LINE_NUMBERS plan_buffer_line(target, feed_rate, invert_feed_rate, line_number); #else plan_buffer_line(target, feed_rate, invert_feed_rate); #endif }
// Directs and executes one line of formatted input from protocol_process. While mostly // incoming streaming g-code blocks, this also executes Grbl internal commands, such as // settings, initiating the homing cycle, and toggling switch states. This differs from // the realtime command module by being susceptible to when Grbl is ready to execute the // next line during a cycle, so for switches like block delete, the switch only effects // the lines that are processed afterward, not necessarily real-time during a cycle, // since there are motions already stored in the buffer. However, this 'lag' should not // be an issue, since these commands are not typically used during a cycle. uint8_t system_execute_line(char *line) { uint8_t char_counter = 1; uint8_t helper_var = 0; // Helper variable float parameter, value; switch( line[char_counter] ) { case 0 : report_grbl_help(); break; case '$': case 'G': case 'C': case 'X': if ( line[(char_counter+1)] != 0 ) { return(STATUS_INVALID_STATEMENT); } switch( line[char_counter] ) { case '$' : // Prints Grbl settings if ( sys.state & (STATE_CYCLE | STATE_HOLD) ) { return(STATUS_IDLE_ERROR); } // Block during cycle. Takes too long to print. else { report_grbl_settings(); } break; case 'G' : // Prints gcode parser state // TODO: Move this to realtime commands for GUIs to request this data during suspend-state. report_gcode_modes(); break; case 'C' : // Set check g-code mode [IDLE/CHECK] // Perform reset when toggling off. Check g-code mode should only work if Grbl // is idle and ready, regardless of alarm locks. This is mainly to keep things // simple and consistent. if ( sys.state == STATE_CHECK_MODE ) { mc_reset(); report_feedback_message(MESSAGE_DISABLED); } else { if (sys.state) { return(STATUS_IDLE_ERROR); } // Requires no alarm mode. sys.state = STATE_CHECK_MODE; report_feedback_message(MESSAGE_ENABLED); } break; case 'X' : // Disable alarm lock [ALARM] if (sys.state == STATE_ALARM) { report_feedback_message(MESSAGE_ALARM_UNLOCK); sys.state = STATE_IDLE; // Don't run startup script. Prevents stored moves in startup from causing accidents. #ifndef DEFAULTS_TRINAMIC if (system_check_safety_door_ajar()) { // Check safety door switch before returning. bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR); protocol_execute_realtime(); // Enter safety door mode. } #endif } // Otherwise, no effect. break; // case 'J' : break; // Jogging methods // TODO: Here jogging can be placed for execution as a seperate subprogram. It does not need to be // susceptible to other realtime commands except for e-stop. The jogging function is intended to // be a basic toggle on/off with controlled acceleration and deceleration to prevent skipped // steps. The user would supply the desired feedrate, axis to move, and direction. Toggle on would // start motion and toggle off would initiate a deceleration to stop. One could 'feather' the // motion by repeatedly toggling to slow the motion to the desired location. Location data would // need to be updated real-time and supplied to the user through status queries. // More controlled exact motions can be taken care of by inputting G0 or G1 commands, which are // handled by the planner. It would be possible for the jog subprogram to insert blocks into the // block buffer without having the planner plan them. It would need to manage de/ac-celerations // on its own carefully. This approach could be effective and possibly size/memory efficient. // } // break; } break; default : // Block any system command that requires the state as IDLE/ALARM. (i.e. EEPROM, homing) if ( !(sys.state == STATE_IDLE || sys.state == STATE_ALARM) ) { return(STATUS_IDLE_ERROR); } switch( line[char_counter] ) { case '#' : // Print Grbl NGC parameters if ( line[++char_counter] != 0 ) { return(STATUS_INVALID_STATEMENT); } else { report_ngc_parameters(); } break; case 'H' : // Perform homing cycle [IDLE/ALARM] if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_HOMING; // Set system state variable // Only perform homing if Grbl is idle or lost. // TODO: Likely not required. #ifndef DEFAULTS_TRINAMIC if (system_check_safety_door_ajar()) { // Check safety door switch before homing. bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR); protocol_execute_realtime(); // Enter safety door mode. } #endif mc_homing_cycle(); if (!sys.abort) { // Execute startup scripts after successful homing. sys.state = STATE_IDLE; // Set to IDLE when complete. st_go_idle(); // Set steppers to the settings idle state before returning. system_execute_startup(line); } } else { return(STATUS_SETTING_DISABLED); } break; case 'I' : // Print or store build info. [IDLE/ALARM] if ( line[++char_counter] == 0 ) { settings_read_build_info(line); report_build_info(line); } else { // Store startup line [IDLE/ALARM] if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); } helper_var = char_counter; // Set helper variable as counter to start of user info line. do { line[char_counter-helper_var] = line[char_counter]; } while (line[char_counter++] != 0); settings_store_build_info(line); } break; case 'R' : // Restore defaults [IDLE/ALARM] if (line[++char_counter] != 'S') { return(STATUS_INVALID_STATEMENT); } if (line[++char_counter] != 'T') { return(STATUS_INVALID_STATEMENT); } if (line[++char_counter] != '=') { return(STATUS_INVALID_STATEMENT); } if (line[char_counter+2] != 0) { return(STATUS_INVALID_STATEMENT); } switch (line[++char_counter]) { case '$': settings_restore(SETTINGS_RESTORE_DEFAULTS); break; case '#': settings_restore(SETTINGS_RESTORE_PARAMETERS); break; case '*': settings_restore(SETTINGS_RESTORE_ALL); break; default: return(STATUS_INVALID_STATEMENT); } report_feedback_message(MESSAGE_RESTORE_DEFAULTS); mc_reset(); // Force reset to ensure settings are initialized correctly. break; case 'N' : // Startup lines. [IDLE/ALARM] if ( line[++char_counter] == 0 ) { // Print startup lines for (helper_var=0; helper_var < N_STARTUP_LINE; helper_var++) { if (!(settings_read_startup_line(helper_var, line))) { report_status_message(STATUS_SETTING_READ_FAIL); } else { report_startup_line(helper_var,line); } } break; } else { // Store startup line [IDLE Only] Prevents motion during ALARM. if (sys.state != STATE_IDLE) { return(STATUS_IDLE_ERROR); } // Store only when idle. helper_var = true; // Set helper_var to flag storing method. // No break. Continues into default: to read remaining command characters. } default : // Storing setting methods [IDLE/ALARM] if(!read_float(line, &char_counter, ¶meter)) { return(STATUS_BAD_NUMBER_FORMAT); } if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); } if (helper_var) { // Store startup line // Prepare sending gcode block to gcode parser by shifting all characters helper_var = char_counter; // Set helper variable as counter to start of gcode block do { line[char_counter-helper_var] = line[char_counter]; } while (line[char_counter++] != 0); // Execute gcode block to ensure block is valid. helper_var = gc_execute_line(line); // Set helper_var to returned status code. if (helper_var) { return(helper_var); } else { helper_var = trunc(parameter); // Set helper_var to int value of parameter settings_store_startup_line(helper_var,line); } } else { // Store global setting. if(!read_float(line, &char_counter, &value)) { return(STATUS_BAD_NUMBER_FORMAT); } if((line[char_counter] != 0) || (parameter > 255)) { return(STATUS_INVALID_STATEMENT); } return(settings_store_global_setting((uint8_t)parameter, value)); } } } return(STATUS_OK); // If '$' command makes it to here, then everything's ok. }
void mc_probe_cycle(float *target, float feed_rate, uint8_t invert_feed_rate, uint8_t is_probe_away, uint8_t is_no_error) #endif { // TODO: Need to update this cycle so it obeys a non-auto cycle start. if (sys.state == STATE_CHECK_MODE) { return; } // Finish all queued commands and empty planner buffer before starting probe cycle. protocol_buffer_synchronize(); // Initialize probing control variables sys.probe_succeeded = false; // Re-initialize probe history before beginning cycle. probe_configure_invert_mask(is_probe_away); // After syncing, check if probe is already triggered. If so, halt and issue alarm. // NOTE: This probe initialization error applies to all probing cycles. if ( probe_get_state() ) { // Check probe pin state. bit_true_atomic(sys_rt_exec_alarm, EXEC_ALARM_PROBE_FAIL); protocol_execute_realtime(); } if (sys.abort) { return; } // Return if system reset has been issued. // Setup and queue probing motion. Auto cycle-start should not start the cycle. #ifdef USE_LINE_NUMBERS mc_line(target, feed_rate, invert_feed_rate, line_number); #else mc_line(target, feed_rate, invert_feed_rate); #endif // Activate the probing state monitor in the stepper module. sys_probe_state = PROBE_ACTIVE; // Perform probing cycle. Wait here until probe is triggered or motion completes. bit_true_atomic(sys_rt_exec_state, EXEC_CYCLE_START); do { protocol_execute_realtime(); if (sys.abort) { return; } // Check for system abort } while (sys.state != STATE_IDLE); // Probing cycle complete! // Set state variables and error out, if the probe failed and cycle with error is enabled. if (sys_probe_state == PROBE_ACTIVE) { if (is_no_error) { memcpy(sys.probe_position, sys.position, sizeof(float)*N_AXIS); } else { bit_true_atomic(sys_rt_exec_alarm, EXEC_ALARM_PROBE_FAIL); } } else { sys.probe_succeeded = true; // Indicate to system the probing cycle completed successfully. } sys_probe_state = PROBE_OFF; // Ensure probe state monitor is disabled. protocol_execute_realtime(); // Check and execute run-time commands if (sys.abort) { return; } // Check for system abort // Reset the stepper and planner buffers to remove the remainder of the probe motion. st_reset(); // Reest step segment buffer. plan_reset(); // Reset planner buffer. Zero planner positions. Ensure probing motion is cleared. plan_sync_position(); // Sync planner position to current machine position. // TODO: Update the g-code parser code to not require this target calculation but uses a gc_sync_position() call. // NOTE: The target[] variable updated here will be sent back and synced with the g-code parser. system_convert_array_steps_to_mpos(target, sys.position); #ifdef MESSAGE_PROBE_COORDINATES // All done! Output the probe position as message. report_probe_parameters(); #endif }
// Perform tool length probe cycle. Requires probe switch. // NOTE: Upon probe failure, the program will be stopped and placed into ALARM state. uint8_t mc_probe_cycle(float *target, plan_line_data_t *pl_data, uint8_t parser_flags) { // TODO: Need to update this cycle so it obeys a non-auto cycle start. if (sys.state == STATE_CHECK_MODE) { return(GC_PROBE_CHECK_MODE); } // Finish all queued commands and empty planner buffer before starting probe cycle. protocol_buffer_synchronize(); if (sys.abort) { return(GC_PROBE_ABORT); } // Return if system reset has been issued. // Initialize probing control variables uint8_t is_probe_away = bit_istrue(parser_flags,GC_PARSER_PROBE_IS_AWAY); uint8_t is_no_error = bit_istrue(parser_flags,GC_PARSER_PROBE_IS_NO_ERROR); sys.probe_succeeded = false; // Re-initialize probe history before beginning cycle. probe_configure_invert_mask(is_probe_away); // After syncing, check if probe is already triggered. If so, halt and issue alarm. // NOTE: This probe initialization error applies to all probing cycles. if ( probe_get_state() ) { // Check probe pin state. system_set_exec_alarm(EXEC_ALARM_PROBE_FAIL_INITIAL); protocol_execute_realtime(); probe_configure_invert_mask(false); // Re-initialize invert mask before returning. return(GC_PROBE_FAIL_INIT); // Nothing else to do but bail. } // Setup and queue probing motion. Auto cycle-start should not start the cycle. mc_line(target, pl_data); // Activate the probing state monitor in the stepper module. sys_probe_state = PROBE_ACTIVE; // Perform probing cycle. Wait here until probe is triggered or motion completes. system_set_exec_state_flag(EXEC_CYCLE_START); do { protocol_execute_realtime(); if (sys.abort) { return(GC_PROBE_ABORT); } // Check for system abort } while (sys.state != STATE_IDLE); // Probing cycle complete! // Set state variables and error out, if the probe failed and cycle with error is enabled. if (sys_probe_state == PROBE_ACTIVE) { if (is_no_error) { memcpy(sys_probe_position, sys_position, sizeof(sys_position)); } else { system_set_exec_alarm(EXEC_ALARM_PROBE_FAIL_CONTACT); } } else { sys.probe_succeeded = true; // Indicate to system the probing cycle completed successfully. } sys_probe_state = PROBE_OFF; // Ensure probe state monitor is disabled. probe_configure_invert_mask(false); // Re-initialize invert mask. protocol_execute_realtime(); // Check and execute run-time commands // Reset the stepper and planner buffers to remove the remainder of the probe motion. st_reset(); // Reset step segment buffer. plan_reset(); // Reset planner buffer. Zero planner positions. Ensure probing motion is cleared. plan_sync_position(); // Sync planner position to current machine position. #ifdef MESSAGE_PROBE_COORDINATES // All done! Output the probe position as message. report_probe_parameters(); #endif if (sys.probe_succeeded) { return(GC_PROBE_FOUND); } // Successful probe cycle. else { return(GC_PROBE_FAIL_END); } // Failed to trigger probe within travel. With or without error. }
// Homes the specified cycle axes, sets the machine position, and performs a pull-off motion after // completing. Homing is a special motion case, which involves rapid uncontrolled stops to locate // the trigger point of the limit switches. The rapid stops are handled by a system level axis lock // mask, which prevents the stepper algorithm from executing step pulses. Homing motions typically // circumvent the processes for executing motions in normal operation. // NOTE: Only the abort realtime command can interrupt this process. // TODO: Move limit pin-specific calls to a general function for portability. void limits_go_home(uint8_t cycle_mask) { if (sys.abort) { return; } // Block if system reset has been issued. // Initialize uint8_t n_cycle = (2*N_HOMING_LOCATE_CYCLE+1); uint8_t step_pin[N_AXIS]; float target[N_AXIS]; float max_travel = 0.0; uint8_t idx; for (idx=0; idx<N_AXIS; idx++) { // Initialize step pin masks step_pin[idx] = get_step_pin_mask(idx); #ifdef COREXY if ((idx==A_MOTOR)||(idx==B_MOTOR)) { step_pin[idx] = (get_step_pin_mask(X_AXIS)|get_step_pin_mask(Y_AXIS)); } #endif if (bit_istrue(cycle_mask,bit(idx))) { // Set target based on max_travel setting. Ensure homing switches engaged with search scalar. // NOTE: settings.max_travel[] is stored as a negative value. max_travel = max(max_travel,(-HOMING_AXIS_SEARCH_SCALAR)*settings.max_travel[idx]); } } // Set search mode with approach at seek rate to quickly engage the specified cycle_mask limit switches. bool approach = true; float homing_rate = settings.homing_seek_rate; uint8_t limit_state, axislock, n_active_axis; do { system_convert_array_steps_to_mpos(target,sys.position); // Initialize and declare variables needed for homing routine. axislock = 0; n_active_axis = 0; for (idx=0; idx<N_AXIS; idx++) { // Set target location for active axes and setup computation for homing rate. if (bit_istrue(cycle_mask,bit(idx))) { n_active_axis++; sys.position[idx] = 0; // Set target direction based on cycle mask and homing cycle approach state. // NOTE: This happens to compile smaller than any other implementation tried. if (bit_istrue(settings.homing_dir_mask,bit(idx))) { if (approach) { target[idx] = -max_travel; } else { target[idx] = max_travel; } } else { if (approach) { target[idx] = max_travel; } else { target[idx] = -max_travel; } } // Apply axislock to the step port pins active in this cycle. axislock |= step_pin[idx]; } } homing_rate *= sqrt(n_active_axis); // [sqrt(N_AXIS)] Adjust so individual axes all move at homing rate. sys.homing_axis_lock = axislock; plan_sync_position(); // Sync planner position to current machine position. // Perform homing cycle. Planner buffer should be empty, as required to initiate the homing cycle. #ifdef USE_LINE_NUMBERS plan_buffer_line(target, homing_rate, false, false, HOMING_CYCLE_LINE_NUMBER); // Bypass mc_line(). Directly plan homing motion. #else plan_buffer_line(target, homing_rate, false, false); // Bypass mc_line(). Directly plan homing motion. #endif st_prep_buffer(); // Prep and fill segment buffer from newly planned block. st_wake_up(); // Initiate motion do { if (approach) { // Check limit state. Lock out cycle axes when they change. limit_state = limits_get_state(); for (idx=0; idx<N_AXIS; idx++) { if (axislock & step_pin[idx]) { if (limit_state & (1 << idx)) { axislock &= ~(step_pin[idx]); } } } sys.homing_axis_lock = axislock; } st_prep_buffer(); // Check and prep segment buffer. NOTE: Should take no longer than 200us. // Exit routines: No time to run protocol_execute_realtime() in this loop. if (sys_rt_exec_state & (EXEC_SAFETY_DOOR | EXEC_RESET | EXEC_CYCLE_STOP)) { // Homing failure: Limit switches are still engaged after pull-off motion if ( (sys_rt_exec_state & (EXEC_SAFETY_DOOR | EXEC_RESET)) || // Safety door or reset issued (!approach && (limits_get_state() & cycle_mask)) || // Limit switch still engaged after pull-off motion ( approach && (sys_rt_exec_state & EXEC_CYCLE_STOP)) ) { // Limit switch not found during approach. mc_reset(); // Stop motors, if they are running. protocol_execute_realtime(); return; } else { // Pull-off motion complete. Disable CYCLE_STOP from executing. system_clear_exec_state_flag(EXEC_CYCLE_STOP); break; } } } while (STEP_MASK & axislock); st_reset(); // Immediately force kill steppers and reset step segment buffer. plan_reset(); // Reset planner buffer to zero planner current position and to clear previous motions. delay_ms(settings.homing_debounce_delay); // Delay to allow transient dynamics to dissipate. // Reverse direction and reset homing rate for locate cycle(s). approach = !approach; // After first cycle, homing enters locating phase. Shorten search to pull-off distance. if (approach) { max_travel = settings.homing_pulloff*HOMING_AXIS_LOCATE_SCALAR; homing_rate = settings.homing_feed_rate; } else { max_travel = settings.homing_pulloff; homing_rate = settings.homing_seek_rate; } } while (n_cycle-- > 0); // The active cycle axes should now be homed and machine limits have been located. By // default, Grbl defines machine space as all negative, as do most CNCs. Since limit switches // can be on either side of an axes, check and set axes machine zero appropriately. Also, // set up pull-off maneuver from axes limit switches that have been homed. This provides // some initial clearance off the switches and should also help prevent them from falsely // triggering when hard limits are enabled or when more than one axes shares a limit pin. #ifdef COREXY int32_t off_axis_position = 0; #endif int32_t set_axis_position; // Set machine positions for homed limit switches. Don't update non-homed axes. for (idx=0; idx<N_AXIS; idx++) { // NOTE: settings.max_travel[] is stored as a negative value. if (cycle_mask & bit(idx)) { #ifdef HOMING_FORCE_SET_ORIGIN set_axis_position = 0; #else if ( bit_istrue(settings.homing_dir_mask,bit(idx)) ) { set_axis_position = lround((settings.max_travel[idx]+settings.homing_pulloff)*settings.steps_per_mm[idx]); } else { set_axis_position = lround(-settings.homing_pulloff*settings.steps_per_mm[idx]); } #endif #ifdef COREXY if (idx==X_AXIS) { off_axis_position = (sys.position[B_MOTOR] - sys.position[A_MOTOR])/2; sys.position[A_MOTOR] = set_axis_position - off_axis_position; sys.position[B_MOTOR] = set_axis_position + off_axis_position; } else if (idx==Y_AXIS) { off_axis_position = (sys.position[A_MOTOR] + sys.position[B_MOTOR])/2; sys.position[A_MOTOR] = off_axis_position - set_axis_position; sys.position[B_MOTOR] = off_axis_position + set_axis_position; } else { sys.position[idx] = set_axis_position; } #else sys.position[idx] = set_axis_position; #endif } } plan_sync_position(); // Sync planner position to homed machine position. // sys.state = STATE_HOMING; // Ensure system state set as homing before returning. }
/* GRBL PRIMARY LOOP: */ void protocol_main_loop() { // ------------------------------------------------------------ // Complete initialization procedures upon a power-up or reset. // ------------------------------------------------------------ // Print welcome message report_init_message(); // Check for and report alarm state after a reset, error, or an initial power up. if (sys.state == STATE_ALARM) { report_feedback_message(MESSAGE_ALARM_LOCK); } else { // All systems go! But first check for safety door. #ifndef DEFAULTS_TRINAMIC if (system_check_safety_door_ajar()) { bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR); protocol_execute_realtime(); // Enter safety door mode. Should return as IDLE state. } else { sys.state = STATE_IDLE; // Set system to ready. Clear all state flags. } #endif system_execute_startup(line); // Execute startup script. } // --------------------------------------------------------------------------------- // Primary loop! Upon a system abort, this exits back to main() to reset the system. // --------------------------------------------------------------------------------- uint8_t comment = COMMENT_NONE; uint8_t char_counter = 0; uint8_t c; for (;;) { // Process one line of incoming serial data, as the data becomes available. Performs an // initial filtering by removing spaces and comments and capitalizing all letters. // NOTE: While comment, spaces, and block delete(if supported) handling should technically // be done in the g-code parser, doing it here helps compress the incoming data into Grbl's // line buffer, which is limited in size. The g-code standard actually states a line can't // exceed 256 characters, but the Arduino Uno does not have the memory space for this. // With a better processor, it would be very easy to pull this initial parsing out as a // seperate task to be shared by the g-code parser and Grbl's system commands. while((c = serial_read()) != SERIAL_NO_DATA) { if ((c == '\n') || (c == '\r')) { // End of line reached line[char_counter] = 0; // Set string termination character. protocol_execute_line(line); // Line is complete. Execute it! comment = COMMENT_NONE; char_counter = 0; } else { if (comment != COMMENT_NONE) { // Throw away all comment characters if (c == ')') { // End of comment. Resume line. But, not if semicolon type comment. if (comment == COMMENT_TYPE_PARENTHESES) { comment = COMMENT_NONE; } } } else { if (c <= ' ') { // Throw away whitepace and control characters } else if (c == '/') { // Block delete NOT SUPPORTED. Ignore character. // NOTE: If supported, would simply need to check the system if block delete is enabled. } else if (c == '(') { // Enable comments flag and ignore all characters until ')' or EOL. // NOTE: This doesn't follow the NIST definition exactly, but is good enough for now. // In the future, we could simply remove the items within the comments, but retain the // comment control characters, so that the g-code parser can error-check it. comment = COMMENT_TYPE_PARENTHESES; } else if (c == ';') { // NOTE: ';' comment to EOL is a LinuxCNC definition. Not NIST. comment = COMMENT_TYPE_SEMICOLON; // TODO: Install '%' feature // } else if (c == '%') { // Program start-end percent sign NOT SUPPORTED. // NOTE: This maybe installed to tell Grbl when a program is running vs manual input, // where, during a program, the system auto-cycle start will continue to execute // everything until the next '%' sign. This will help fix resuming issues with certain // functions that empty the planner buffer to execute its task on-time. } else if (char_counter >= (LINE_BUFFER_SIZE-1)) { // Detect line buffer overflow. Report error and reset line buffer. report_status_message(STATUS_OVERFLOW); comment = COMMENT_NONE; char_counter = 0; } else if (c >= 'a' && c <= 'z') { // Upcase lowercase line[char_counter++] = c-'a'+'A'; } else { line[char_counter++] = c; } } } } // If there are no more characters in the serial read buffer to be processed and executed, // this indicates that g-code streaming has either filled the planner buffer or has // completed. In either case, auto-cycle start, if enabled, any queued moves. protocol_auto_cycle_start(); protocol_execute_realtime(); // Runtime command check point. if (sys.abort) { return; } // Bail to main() program loop to reset system. } return; /* Never reached */ }