From 76bbfb39ae3c46a874ace54b6d645810cc37d7ac Mon Sep 17 00:00:00 2001 From: midopple Date: Sun, 29 Jan 2012 00:18:21 +0100 Subject: New Version Sprinter V2 - Look Vorward Funktion - - Stepper Control with Timer 1 - SOFT PWM for Extruder heating --> Free Timer 1 - G2 / G3 Command for arc real arc - Baudrate 250 kbaud - M30 Command delete file on SD Card - Text moved to flash to free RAM - M203 Command for Temp debugging --- Sprinter/Sprinter.pde | 2590 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 1673 insertions(+), 917 deletions(-) (limited to 'Sprinter/Sprinter.pde') diff --git a/Sprinter/Sprinter.pde b/Sprinter/Sprinter.pde index e3126b8..821a12b 100644 --- a/Sprinter/Sprinter.pde +++ b/Sprinter/Sprinter.pde @@ -1,15 +1,70 @@ - // Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware. -// Licence: GPL +/* + Reprap firmware based on Sprinter + Optimize for Sanguinololu 1.2 and above + + This program 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. + + This program 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. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* + This firmware is a mashup between Sprinter,grbl and parts from marlin. + (https://github.com/kliment/Sprinter) + + Changes by Doppler Michael (midopple) + + Planner is from Simen Svale Skogsrud + https://github.com/simen/grbl + + Parts of Marlin Firmware from ErikZalm + https://github.com/ErikZalm/Marlin-non-gen6 + + Sprinter V2 + +- Look Vorward Funktion --> Es werden 16 Schritte im Voraus berechnet, übernommen von Marlin, Grbl +- Stepper Ansteuerung ist Interruptgesteuert (Timer 1) +- Extruder wird mit einem PID Regler und SOFT PWM gesteuert (kleinere Frequenz von 500 Hz und Timer 1 bleibt frei) +- Druckgeschwindigkeit kann während des Drucken angepasst werden (+/- 50%) (Command M220 Sxxx) +- G2 und G3 Command vorhanden --> Kreisberechnung (derzeit noch Test) +- Baudrate auf 250 kbaud +- Optimiert für Sanguinololu Board +- M30 Command kann files auf der SD löschen +- Texte für Ausgabe ins Flash verlagert, mehr Speicher für Planner Funktion +- Debug Temperatur für Repetier Host --> M203 Temperature monitor + +*/ + +#include +#include #include "fastio.h" #include "Configuration.h" #include "pins.h" #include "Sprinter.h" +#include "speed_lookuptable.h" +#include "arc_func.h" +#include "heater.h" #ifdef SDSUPPORT #include "SdFat.h" #endif + +#ifndef CRITICAL_SECTION_START +#define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli() +#define CRITICAL_SECTION_END SREG = _sreg +#endif //CRITICAL_SECTION_START + +void __cxa_pure_virtual(){}; + // look here for descriptions of gcodes: http://linuxcnc.org/handbook/gcode/g-code.html // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes @@ -17,6 +72,8 @@ //------------------- // G0 -> G1 // G1 - Coordinated Movement X Y Z E +// G2 - CW ARC +// G3 - CCW ARC // G4 - Dwell S or P // G28 - Home all Axis // G90 - Use Absolute Coordinates @@ -32,7 +89,6 @@ // M114 - Display current position //Custom M Codes -// M80 - Turn on Power Supply // M20 - List SD card // M21 - Init SD card // M22 - Release SD card @@ -43,7 +99,9 @@ // M27 - Report SD print status // M28 - Start SD write (M28 filename.g) // M29 - Stop SD write -// M42 - Set output on free pins, on a non pwm pin (over pin 13 on an arduino mega) use S255 to turn it on and S0 to turn it off. Use P to decide the pin (M42 P23 S255) would turn pin 23 on +// - - Delete file on sd card +// M42 - Set output on free pins, on a non pwm pin (over pin 13 on an arduino mega) use S255 to turn it on and S0 to turn it off. Use P to decide the pin (M42 P23 S255) would turn pin 23 on +// M80 - Turn on Power Supply // M81 - Turn off Power Supply // M82 - Set E codes absolute (default) // M83 - Set E codes relative while in Absolute Coordinates (G90) mode @@ -52,26 +110,56 @@ // M85 - Set inactivity shutdown timer with parameter S. To disable set zero (default) // M92 - Set axis_steps_per_unit - same syntax as G92 // M115 - Capabilities string +// M119 - Show Endstopper State // M140 - Set bed target temp // M190 - Wait for bed current temp to reach target temp. // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) +// M203 - Set temperture monitor to Sx +// M220 - set speed factor override percentage S:factor in percent +// Debug feature / Testing the PID for Hotend +// M601 - Show Temp jitter from Extruder (min / max value from Hotend Temperatur while printing) +// M602 - Reset Temp jitter from Extruder (min / max val) --> Dont use it while Printing +// M603 - Show Free Ram -//Stepper Movement Variables +#define _VERSION_TEXT "1.2.20T / 27.01.2012" + +//Stepper Movement Variables char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'}; +float axis_steps_per_unit[] = _AXIS_STEP_PER_UNIT; + +float max_feedrate[] = _MAX_FEEDRATE; +float homing_feedrate[] = _HOMING_FEEDRATE; +bool axis_relative_modes[] = _AXIS_RELATIVE_MODES; + bool move_direction[NUM_AXIS]; unsigned long axis_previous_micros[NUM_AXIS]; -unsigned long previous_micros = 0, previous_millis_heater, previous_millis_bed_heater; +unsigned long previous_micros = 0; unsigned long move_steps_to_take[NUM_AXIS]; + #ifdef RAMP_ACCELERATION -unsigned long axis_max_interval[NUM_AXIS]; -unsigned long axis_steps_per_sqr_second[NUM_AXIS]; -unsigned long axis_travel_steps_per_sqr_second[NUM_AXIS]; -unsigned long max_interval; -unsigned long steps_per_sqr_second, plateau_steps; + float acceleration = _ACCELERATION; // Normal acceleration mm/s^2 + float retract_acceleration = _RETRACT_ACCELERATION; // Normal acceleration mm/s^2 + float max_xy_jerk = _MAX_XY_JERK; + float max_z_jerk = _MAX_Z_JERK; + float max_start_speed_units_per_second[] = _MAX_START_SPEED_UNITS_PER_SECOND; + long max_acceleration_units_per_sq_second[] = _MAX_ACCELERATION_UNITS_PER_SQ_SECOND; // X, Y, Z and E max acceleration in mm/s^2 for printing moves or retracts + long max_travel_acceleration_units_per_sq_second[] = _MAX_TRAVEL_ACCELERATION_UNITS_PER_SQ_SECOND; // X, Y, Z max acceleration in mm/s^2 for travel moves + + unsigned long axis_max_interval[NUM_AXIS]; + unsigned long axis_steps_per_sqr_second[NUM_AXIS]; + unsigned long axis_travel_steps_per_sqr_second[NUM_AXIS]; + unsigned long max_interval; + unsigned long steps_per_sqr_second, plateau_steps; #endif + +//adjustable feed faktor for online tuning printerspeed +volatile int feedmultiply=100; //100->original / 200-> Faktor 2 / 50 -> Faktor 0.5 +int saved_feedmultiply; +volatile bool feedmultiplychanged=false; + boolean acceleration_enabled = false, accelerating = false; unsigned long interval; float destination[NUM_AXIS] = {0.0, 0.0, 0.0, 0.0}; @@ -85,72 +173,50 @@ long gcode_N, gcode_LastN; bool relative_mode = false; //Determines Absolute or Relative Coordinates bool relative_mode_e = false; //Determines Absolute or Relative E Codes while in Absolute Coordinates mode. E is always relative in Relative Coordinates mode. long timediff = 0; + //experimental feedrate calc -float d = 0; -float axis_diff[NUM_AXIS] = {0, 0, 0, 0}; +//float d = 0; +//float axis_diff[NUM_AXIS] = {0, 0, 0, 0}; + +//For arc centerpont, send bei Command G2/G3 +float offset[3] = {0.0, 0.0, 0.0}; + #ifdef STEP_DELAY_RATIO long long_step_delay_ratio = STEP_DELAY_RATIO * 100; #endif -// comm variables + +// comm variables and Commandbuffer +// BUFSIZE is reduced from 8 to 5 to free more RAM for the PLANNER #define MAX_CMD_SIZE 96 -#define BUFSIZE 8 +#define BUFSIZE 5 //8 char cmdbuffer[BUFSIZE][MAX_CMD_SIZE]; bool fromsd[BUFSIZE]; + int bufindr = 0; int bufindw = 0; int buflen = 0; -int i = 0; char serial_char; int serial_count = 0; boolean comment_mode = false; char *strchr_pointer; // just a pointer to find chars in the cmd string like X, Y, Z, E, etc -// Manage heater variables. For a thermistor or AD595 thermocouple, raw values refer to the -// reading from the analog pin. For a MAX6675 thermocouple, the raw value is the temperature in 0.25 -// degree increments (i.e. 100=25 deg). - -int target_raw = 0; -int target_temp = 0; -int current_raw = 0; -int target_bed_raw = 0; -int current_bed_raw = 0; -int tt = 0, bt = 0; -#ifdef PIDTEMP - int temp_iState = 0; - int prev_temp = 0; - int pTerm; - int iTerm; - int dTerm; - //int output; - int error; - int heater_duty = 0; - const int temp_iState_min = 256L * -PID_INTEGRAL_DRIVE_MAX / PID_IGAIN; - const int temp_iState_max = 256L * PID_INTEGRAL_DRIVE_MAX / PID_IGAIN; -#endif -#ifndef HEATER_CURRENT - #define HEATER_CURRENT 255 -#endif -#ifdef SMOOTHING - uint32_t nma = 0; -#endif -#ifdef WATCHPERIOD - int watch_raw = -1000; - unsigned long watchmillis = 0; -#endif -#ifdef MINTEMP - int minttemp = temp2analogh(MINTEMP); -#endif -#ifdef MAXTEMP -int maxttemp = temp2analogh(MAXTEMP); -#endif - +//Send Temperature in °C to Host +int hotendtC = 0, bedtempC = 0; + //Inactivity shutdown variables unsigned long previous_millis_cmd = 0; unsigned long max_inactive_time = 0; unsigned long stepper_inactive_time = 0; +//Temp Montor for repetier +unsigned char manage_monitor = 255; + + +//------------------------------------------------ +//Init the SD card +//------------------------------------------------ #ifdef SDSUPPORT Sd2Card card; SdVolume volume; @@ -161,23 +227,27 @@ unsigned long stepper_inactive_time = 0; bool sdmode = false; bool sdactive = false; bool savetosd = false; - int16_t n; + int16_t read_char_n; - void initsd(){ + void initsd() + { sdactive = false; #if SDSS >- 1 if(root.isOpen()) root.close(); + if (!card.init(SPI_FULL_SPEED,SDSS)){ //if (!card.init(SPI_HALF_SPEED,SDSS)) - Serial.println("SD init fail"); + showString(PSTR("SD init fail\r\n")); } else if (!volume.init(&card)) - Serial.println("volume.init failed"); + showString(PSTR("volume.init failed\r\n")); else if (!root.openRoot(&volume)) - Serial.println("openRoot failed"); + showString(PSTR("openRoot failed\r\n")); else{ sdactive = true; + print_disk_info(); + #ifdef SDINITFILE file.close(); if(file.open(&root, "init.g", O_READ)){ @@ -187,38 +257,133 @@ unsigned long stepper_inactive_time = 0; } #endif } + #endif } + + + void print_disk_info(void) + { + + // print the type of card + showString(PSTR("\nCard type: ")); + switch(card.type()) + { + case SD_CARD_TYPE_SD1: + showString(PSTR("SD1\r\n")); + break; + case SD_CARD_TYPE_SD2: + showString(PSTR("SD2\r\n")); + break; + case SD_CARD_TYPE_SDHC: + showString(PSTR("SDHC\r\n")); + break; + default: + showString(PSTR("Unknown\r\n")); + } + + //uint64_t freeSpace = volume.clusterCount()*volume.blocksPerCluster()*512; + //uint64_t occupiedSpace = (card.cardSize()*512) - freeSpace; + // print the type and size of the first FAT-type volume + uint32_t volumesize; + showString(PSTR("\nVolume type is FAT")); + Serial.println(volume.fatType(), DEC); + + volumesize = volume.blocksPerCluster(); // clusters are collections of blocks + volumesize *= volume.clusterCount(); // we'll have a lot of clusters + volumesize *= 512; // SD card blocks are always 512 bytes + volumesize /= 1024; //kbytes + volumesize /= 1024; //Mbytes + showString(PSTR("Volume size (Mbytes): ")); + Serial.println(volumesize); + + // list all files in the card with date and size + //root.ls(LS_R | LS_DATE | LS_SIZE); + } + + + + - inline void write_command(char *buf){ + inline void write_command(char *buf) + { char* begin = buf; char* npos = 0; char* end = buf + strlen(buf) - 1; file.writeError = false; - if((npos = strchr(buf, 'N')) != NULL){ + + if((npos = strchr(buf, 'N')) != NULL) + { begin = strchr(npos, ' ') + 1; end = strchr(npos, '*') - 1; } + end[1] = '\r'; end[2] = '\n'; end[3] = '\0'; + //Serial.println(begin); file.write(begin); - if (file.writeError){ - Serial.println("error writing to file"); + + if (file.writeError) + { + showString(PSTR("error writing to file\r\n")); } } + #endif +int FreeRam1(void) +{ + extern int __bss_end; + extern int* __brkval; + int free_memory; + + if (reinterpret_cast(__brkval) == 0) + { + // if no heap use from end of bss section + free_memory = reinterpret_cast(&free_memory) - reinterpret_cast(&__bss_end); + } + else + { + // use from top of stack to heap + free_memory = reinterpret_cast(&free_memory) - reinterpret_cast(__brkval); + } + + return free_memory; +} + +//------------------------------------------------ +//Print a String from Flash to Serial (save RAM) +//------------------------------------------------ +void showString (PGM_P s) +{ + char c; + + while ((c = pgm_read_byte(s++)) != 0) + Serial.print(c); +} + + +//------------------------------------------------ +// Init +//------------------------------------------------ void setup() { + Serial.begin(BAUDRATE); - Serial.println("start"); - for(int i = 0; i < BUFSIZE; i++){ + showString(PSTR("SprinterV2\r\n")); + showString(PSTR(_VERSION_TEXT)); + showString(PSTR("\r\n")); + showString(PSTR("start\r\n")); + + for(int i = 0; i < BUFSIZE; i++) + { fromsd[i] = false; } + //Initialize Dir Pins @@ -253,7 +418,7 @@ void setup() SET_OUTPUT(E_ENABLE_PIN); if(!E_ENABLE_ON) WRITE(E_ENABLE_PIN,HIGH); #endif - + #ifdef CONTROLLERFAN_PIN SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan #endif @@ -329,7 +494,7 @@ void setup() #if (LED_PIN > -1) SET_OUTPUT(LED_PIN); WRITE(LED_PIN,LOW); - #endif + #endif //Initialize Step Pins #if (X_STEP_PIN > -1) @@ -344,8 +509,13 @@ void setup() #if (E_STEP_PIN > -1) SET_OUTPUT(E_STEP_PIN); #endif + #ifdef RAMP_ACCELERATION - setup_acceleration(); + for(int i=0; i < NUM_AXIS; i++){ + axis_max_interval[i] = 100000000.0 / (max_start_speed_units_per_second[i] * axis_steps_per_unit[i]); + axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i]; +// axis_travel_steps_per_sqr_second[i] = max_travel_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i]; + } #endif #ifdef HEATER_USES_MAX6675 @@ -369,125 +539,172 @@ void setup() SET_OUTPUT(SDPOWER); WRITE(SDPOWER,HIGH); #endif + + showString(PSTR("SD Start\r\n")); initsd(); #endif + #ifdef PID_SOFT_PWM + showString(PSTR("Soft PWM Init\r\n")); + init_Timer2_softpwm(); + #endif + + showString(PSTR("Planner Init\r\n")); + plan_init(); // Initialize planner; + + showString(PSTR("Stepper Timer init\r\n")); + st_init(); // Initialize stepper + + //Free Ram + showString(PSTR("Free Ram: ")); + Serial.println(FreeRam1()); + + //Planner Buffer Size + showString(PSTR("Plan Buffer Size:")); + Serial.print((int)sizeof(block_t)*BLOCK_BUFFER_SIZE); + showString(PSTR(" / ")); + Serial.println(BLOCK_BUFFER_SIZE); } + +//------------------------------------------------ +//MAIN LOOP +//------------------------------------------------ void loop() { - if(buflen<3) - get_command(); + if(buflen < (BUFSIZE-1)) + get_command(); - if(buflen){ + if(buflen) + { #ifdef SDSUPPORT - if(savetosd){ - if(strstr(cmdbuffer[bufindr],"M29") == NULL){ + if(savetosd) + { + if(strstr(cmdbuffer[bufindr],"M29") == NULL) + { write_command(cmdbuffer[bufindr]); - Serial.println("ok"); - }else{ + showString(PSTR("ok\r\n")); + } + else + { file.sync(); file.close(); savetosd = false; - Serial.println("Done saving file."); + showString(PSTR("Done saving file.\r\n")); } - }else{ + } + else + { process_commands(); } #else process_commands(); #endif + buflen = (buflen-1); bufindr = (bufindr + 1)%BUFSIZE; - } - //check heater every n milliseconds - manage_heater(); - manage_inactivity(1); } + + //check heater every n milliseconds + manage_heater(); + manage_inactivity(1); +} +//------------------------------------------------ +//READ COMMAND FROM UART +//------------------------------------------------ inline void get_command() { - while( Serial.available() > 0 && buflen < BUFSIZE) { + while( Serial.available() > 0 && buflen < BUFSIZE) + { serial_char = Serial.read(); if(serial_char == '\n' || serial_char == '\r' || serial_char == ':' || serial_count >= (MAX_CMD_SIZE - 1) ) { if(!serial_count) return; //if empty line cmdbuffer[bufindw][serial_count] = 0; //terminate string - if(!comment_mode){ - fromsd[bufindw] = false; - if(strstr(cmdbuffer[bufindw], "N") != NULL) - { - strchr_pointer = strchr(cmdbuffer[bufindw], 'N'); - gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10)); - if(gcode_N != gcode_LastN+1 && (strstr(cmdbuffer[bufindw], "M110") == NULL) ) { - Serial.print("Serial Error: Line Number is not Last Line Number+1, Last Line:"); - Serial.println(gcode_LastN); - //Serial.println(gcode_N); - FlushSerialRequestResend(); - serial_count = 0; - return; - } + if(!comment_mode) + { + fromsd[bufindw] = false; + if(strstr(cmdbuffer[bufindw], "N") != NULL) + { + strchr_pointer = strchr(cmdbuffer[bufindw], 'N'); + gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10)); + if(gcode_N != gcode_LastN+1 && (strstr(cmdbuffer[bufindw], "M110") == NULL) ) + { + showString(PSTR("Serial Error: Line Number is not Last Line Number+1, Last Line:")); + Serial.println(gcode_LastN); + //Serial.println(gcode_N); + FlushSerialRequestResend(); + serial_count = 0; + return; + } - if(strstr(cmdbuffer[bufindw], "*") != NULL) - { - byte checksum = 0; - byte count = 0; - while(cmdbuffer[bufindw][count] != '*') checksum = checksum^cmdbuffer[bufindw][count++]; - strchr_pointer = strchr(cmdbuffer[bufindw], '*'); + if(strstr(cmdbuffer[bufindw], "*") != NULL) + { + byte checksum = 0; + byte count = 0; + while(cmdbuffer[bufindw][count] != '*') checksum = checksum^cmdbuffer[bufindw][count++]; + strchr_pointer = strchr(cmdbuffer[bufindw], '*'); - if( (int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) { - Serial.print("Error: checksum mismatch, Last Line:"); - Serial.println(gcode_LastN); - FlushSerialRequestResend(); - serial_count = 0; - return; - } - //if no errors, continue parsing - } - else - { - Serial.print("Error: No Checksum with line number, Last Line:"); - Serial.println(gcode_LastN); - FlushSerialRequestResend(); - serial_count = 0; - return; - } + if( (int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) + { + showString(PSTR("Error: checksum mismatch, Last Line:")); + Serial.println(gcode_LastN); + FlushSerialRequestResend(); + serial_count = 0; + return; + } + //if no errors, continue parsing + } + else + { + showString(PSTR("Error: No Checksum with line number, Last Line:")); + Serial.println(gcode_LastN); + FlushSerialRequestResend(); + serial_count = 0; + return; + } - gcode_LastN = gcode_N; - //if no errors, continue parsing - } - else // if we don't receive 'N' but still see '*' - { - if((strstr(cmdbuffer[bufindw], "*") != NULL)) - { - Serial.print("Error: No Line Number with checksum, Last Line:"); - Serial.println(gcode_LastN); - serial_count = 0; - return; - } - } - if((strstr(cmdbuffer[bufindw], "G") != NULL)){ - strchr_pointer = strchr(cmdbuffer[bufindw], 'G'); - switch((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))){ - case 0: - case 1: + gcode_LastN = gcode_N; + //if no errors, continue parsing + } + else // if we don't receive 'N' but still see '*' + { + if((strstr(cmdbuffer[bufindw], "*") != NULL)) + { + showString(PSTR("Error: No Line Number with checksum, Last Line:")); + Serial.println(gcode_LastN); + serial_count = 0; + return; + } + } + + if((strstr(cmdbuffer[bufindw], "G") != NULL)) + { + strchr_pointer = strchr(cmdbuffer[bufindw], 'G'); + switch((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))) + { + case 0: + case 1: + case 2: //G2 + case 3: //G3 arc func #ifdef SDSUPPORT if(savetosd) break; #endif - Serial.println("ok"); - break; - default: - break; - } - - } + showString(PSTR("ok\r\n")); + //Serial.println("ok"); + break; + + default: + break; + } + } bufindw = (bufindw + 1)%BUFSIZE; buflen += 1; - } comment_mode = false; //for new command serial_count = 0; //clear buffer @@ -499,35 +716,39 @@ inline void get_command() } } #ifdef SDSUPPORT -if(!sdmode || serial_count!=0){ + if(!sdmode || serial_count!=0) + { return; -} - while( filesize > sdpos && buflen < BUFSIZE) { - n = file.read(); - serial_char = (char)n; - if(serial_char == '\n' || serial_char == '\r' || serial_char == ':' || serial_count >= (MAX_CMD_SIZE - 1) || n == -1) + } + while( filesize > sdpos && buflen < BUFSIZE) + { + read_char_n = file.read(); + serial_char = (char)read_char_n; + if(serial_char == '\n' || serial_char == '\r' || serial_char == ':' || serial_count >= (MAX_CMD_SIZE - 1) || read_char_n == -1) { sdpos = file.curPosition(); - if(sdpos >= filesize){ + if(sdpos >= filesize) + { sdmode = false; - Serial.println("Done printing file"); + showString(PSTR("Done printing file\r\n")); } - if(!serial_count) return; //if empty line - cmdbuffer[bufindw][serial_count] = 0; //terminate string - if(!comment_mode){ - fromsd[bufindw] = true; - buflen += 1; - bufindw = (bufindw + 1)%BUFSIZE; - } - comment_mode = false; //for new command - serial_count = 0; //clear buffer + if(!serial_count) return; //if empty line + cmdbuffer[bufindw][serial_count] = 0; //terminate string + if(!comment_mode) + { + fromsd[bufindw] = true; + buflen += 1; + bufindw = (bufindw + 1)%BUFSIZE; + } + comment_mode = false; //for new command + serial_count = 0; //clear buffer } else { if(serial_char == ';') comment_mode = true; if(!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; } -} + } #endif } @@ -543,6 +764,9 @@ inline bool code_seen(char code) return (strchr_pointer != NULL); //Return True if a character was found } +//------------------------------------------------ +// CHECK COMMAND AND CONVERT VALUES +//------------------------------------------------ inline void process_commands() { unsigned long codenum; //throw away variable @@ -563,6 +787,18 @@ inline void process_commands() //ClearToSend(); return; //break; + case 2: // G2 - CW ARC + get_arc_coordinates(); + prepare_arc_move(true); + previous_millis_cmd = millis(); + //break; + return; + case 3: // G3 - CCW ARC + get_arc_coordinates(); + prepare_arc_move(false); + previous_millis_cmd = millis(); + //break; + return; case 4: // G4 dwell codenum = 0; if(code_seen('P')) codenum = code_value(); // milliseconds to wait @@ -574,75 +810,112 @@ inline void process_commands() break; case 28: //G28 Home all Axis one at a time saved_feedrate = feedrate; - for(int i=0; i < NUM_AXIS; i++) { + saved_feedmultiply = feedmultiply; + feedmultiply = 100; + + for(int i=0; i < NUM_AXIS; i++) + { destination[i] = current_position[i]; } feedrate = 0; home_all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2]))); - if((home_all_axis) || (code_seen(axis_codes[0]))) { - if ((X_MIN_PIN > -1 && X_HOME_DIR==-1) || (X_MAX_PIN > -1 && X_HOME_DIR==1)){ - current_position[0] = 0; - destination[0] = 1.5 * X_MAX_LENGTH * X_HOME_DIR; - feedrate = homing_feedrate[0]; + if((home_all_axis) || (code_seen(axis_codes[X_AXIS]))) + { + if ((X_MIN_PIN > -1 && X_HOME_DIR==-1) || (X_MAX_PIN > -1 && X_HOME_DIR==1)) + { + st_synchronize(); + current_position[X_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[X_AXIS] = 1.5 * X_MAX_LENGTH * X_HOME_DIR; + feedrate = homing_feedrate[X_AXIS]; prepare_move(); - - current_position[0] = 0; - destination[0] = -5 * X_HOME_DIR; + + st_synchronize(); + current_position[X_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[X_AXIS] = -5 * X_HOME_DIR; prepare_move(); - - destination[0] = 10 * X_HOME_DIR; + + st_synchronize(); + destination[X_AXIS] = 10 * X_HOME_DIR; + feedrate = homing_feedrate[X_AXIS]/2 ; prepare_move(); - - current_position[0] = (X_HOME_DIR == -1) ? 0 : X_MAX_LENGTH; - destination[0] = current_position[0]; + st_synchronize(); + + current_position[X_AXIS] = (X_HOME_DIR == -1) ? 0 : X_MAX_LENGTH; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[X_AXIS] = current_position[X_AXIS]; feedrate = 0; } } - - if((home_all_axis) || (code_seen(axis_codes[1]))) { - if ((Y_MIN_PIN > -1 && Y_HOME_DIR==-1) || (Y_MAX_PIN > -1 && Y_HOME_DIR==1)){ - current_position[1] = 0; - destination[1] = 1.5 * Y_MAX_LENGTH * Y_HOME_DIR; - feedrate = homing_feedrate[1]; + showString(PSTR("HOME X AXIS\r\n")); + + if((home_all_axis) || (code_seen(axis_codes[Y_AXIS]))) + { + if ((Y_MIN_PIN > -1 && Y_HOME_DIR==-1) || (Y_MAX_PIN > -1 && Y_HOME_DIR==1)) + { + current_position[Y_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Y_AXIS] = 1.5 * Y_MAX_LENGTH * Y_HOME_DIR; + feedrate = homing_feedrate[Y_AXIS]; prepare_move(); - - current_position[1] = 0; - destination[1] = -5 * Y_HOME_DIR; + st_synchronize(); + + current_position[Y_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Y_AXIS] = -5 * Y_HOME_DIR; prepare_move(); - - destination[1] = 10 * Y_HOME_DIR; + st_synchronize(); + + destination[Y_AXIS] = 10 * Y_HOME_DIR; + feedrate = homing_feedrate[Y_AXIS]/2; prepare_move(); - - current_position[1] = (Y_HOME_DIR == -1) ? 0 : Y_MAX_LENGTH; - destination[1] = current_position[1]; + st_synchronize(); + + current_position[Y_AXIS] = (Y_HOME_DIR == -1) ? 0 : Y_MAX_LENGTH; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Y_AXIS] = current_position[Y_AXIS]; feedrate = 0; } } - - if((home_all_axis) || (code_seen(axis_codes[2]))) { - if ((Z_MIN_PIN > -1 && Z_HOME_DIR==-1) || (Z_MAX_PIN > -1 && Z_HOME_DIR==1)){ - current_position[2] = 0; - destination[2] = 1.5 * Z_MAX_LENGTH * Z_HOME_DIR; - feedrate = homing_feedrate[2]; + showString(PSTR("HOME Y AXIS\r\n")); + + if((home_all_axis) || (code_seen(axis_codes[Z_AXIS]))) + { + if ((Z_MIN_PIN > -1 && Z_HOME_DIR==-1) || (Z_MAX_PIN > -1 && Z_HOME_DIR==1)) + { + current_position[Z_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Z_AXIS] = 1.5 * Z_MAX_LENGTH * Z_HOME_DIR; + feedrate = homing_feedrate[Z_AXIS]; prepare_move(); - - current_position[2] = 0; - destination[2] = -2 * Z_HOME_DIR; + st_synchronize(); + + current_position[Z_AXIS] = 0; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Z_AXIS] = -2 * Z_HOME_DIR; prepare_move(); - - destination[2] = 10 * Z_HOME_DIR; + st_synchronize(); + + destination[Z_AXIS] = 3 * Z_HOME_DIR; + feedrate = homing_feedrate[Z_AXIS]/2; prepare_move(); - - current_position[2] = (Z_HOME_DIR == -1) ? 0 : Z_MAX_LENGTH; - destination[2] = current_position[2]; - feedrate = 0; - - } - } - + st_synchronize(); + + current_position[Z_AXIS] = (Z_HOME_DIR == -1) ? 0 : Z_MAX_LENGTH; + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + destination[Z_AXIS] = current_position[Z_AXIS]; + feedrate = 0; + } + } + + showString(PSTR("HOME Z AXIS\r\n")); + feedrate = saved_feedrate; + feedmultiply = saved_feedmultiply; + previous_millis_cmd = millis(); break; case 90: // G90 @@ -652,11 +925,21 @@ inline void process_commands() relative_mode = true; break; case 92: // G92 - for(int i=0; i < NUM_AXIS; i++) { + if(!code_seen(axis_codes[E_AXIS])) + st_synchronize(); + + for(int i=0; i < NUM_AXIS; i++) + { if(code_seen(axis_codes[i])) current_position[i] = code_value(); } + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); break; - + default: + #ifdef SEND_WRONG_CMD_INFO + showString(PSTR("Unknown G-COM:")); + Serial.println(cmdbuffer[bufindr]); + #endif + break; } } @@ -668,9 +951,9 @@ inline void process_commands() #ifdef SDSUPPORT case 20: // M20 - list SD card - Serial.println("Begin file list"); + showString(PSTR("Begin file list\r\n")); root.ls(); - Serial.println("End file list"); + showString(PSTR("End file list\r\n")); break; case 21: // M21 - init SD card sdmode = false; @@ -681,72 +964,88 @@ inline void process_commands() sdactive = false; break; case 23: //M23 - Select file - if(sdactive){ + if(sdactive) + { sdmode = false; file.close(); starpos = (strchr(strchr_pointer + 4,'*')); + if(starpos!=NULL) *(starpos-1)='\0'; - if (file.open(&root, strchr_pointer + 4, O_READ)) { - Serial.print("File opened:"); + + if (file.open(&root, strchr_pointer + 4, O_READ)) + { + showString(PSTR("File opened:")); Serial.print(strchr_pointer + 4); - Serial.print(" Size:"); + showString(PSTR(" Size:")); Serial.println(file.fileSize()); sdpos = 0; filesize = file.fileSize(); - Serial.println("File selected"); + showString(PSTR("File selected\r\n")); } - else{ - Serial.println("file.open failed"); + else + { + showString(PSTR("file.open failed\r\n")); } } break; case 24: //M24 - Start SD print - if(sdactive){ + if(sdactive) + { sdmode = true; } break; case 25: //M25 - Pause SD print - if(sdmode){ + if(sdmode) + { sdmode = false; } break; case 26: //M26 - Set SD index - if(sdactive && code_seen('S')){ + if(sdactive && code_seen('S')) + { sdpos = code_value_long(); file.seekSet(sdpos); } break; case 27: //M27 - Get SD status - if(sdactive){ - Serial.print("SD printing byte "); + if(sdactive) + { + showString(PSTR("SD printing byte ")); Serial.print(sdpos); - Serial.print("/"); + showString(PSTR("/")); Serial.println(filesize); - }else{ - Serial.println("Not SD printing"); + } + else + { + showString(PSTR("Not SD printing\r\n")); } break; - case 28: //M28 - Start SD write - if(sdactive){ + case 28: //M28 - Start SD write + if(sdactive) + { char* npos = 0; file.close(); sdmode = false; starpos = (strchr(strchr_pointer + 4,'*')); - if(starpos != NULL){ + if(starpos != NULL) + { npos = strchr(cmdbuffer[bufindr], 'N'); strchr_pointer = strchr(npos,' ') + 1; *(starpos-1) = '\0'; } - if (!file.open(&root, strchr_pointer+4, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) + + if (!file.open(&root, strchr_pointer+4, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) + { + showString(PSTR("open failed, File: ")); + Serial.print(strchr_pointer + 4); + showString(PSTR(".")); + } + else { - Serial.print("open failed, File: "); - Serial.print(strchr_pointer + 4); - Serial.print("."); - }else{ - savetosd = true; - Serial.print("Writing to file: "); - Serial.println(strchr_pointer + 4); + savetosd = true; + showString(PSTR("Writing to file: ")); + Serial.println(strchr_pointer + 4); } } break; @@ -754,6 +1053,28 @@ inline void process_commands() //processed in write to file routine above //savetosd = false; break; + case 30: // M30 filename - Delete file + if(sdactive) + { + sdmode = false; + file.close(); + + starpos = (strchr(strchr_pointer + 4,'*')); + + if(starpos!=NULL) + *(starpos-1)='\0'; + + if(file.remove(&root, strchr_pointer + 4)) + { + showString(PSTR("File deleted\r\n")); + } + else + { + showString(PSTR("Deletion failed\r\n")); + } + } + break; + #endif case 42: //M42 -Change pin status via gcode if (code_seen('S')) @@ -775,7 +1096,7 @@ inline void process_commands() { pinMode(pin_number, OUTPUT); digitalWrite(pin_number, pin_status); - analogWrite(pin_number, pin_status); + //analogWrite(pin_number, pin_status); } } } @@ -783,10 +1104,13 @@ inline void process_commands() case 104: // M104 if (code_seen('S')) target_raw = temp2analogh(target_temp = code_value()); #ifdef WATCHPERIOD - if(target_raw > current_raw){ + if(target_raw > current_raw) + { watchmillis = max(1,millis()); watch_raw = current_raw; - }else{ + } + else + { watchmillis = 0; } #endif @@ -798,23 +1122,31 @@ inline void process_commands() break; case 105: // M105 #if (TEMP_0_PIN > -1) || defined (HEATER_USES_MAX6675)|| defined HEATER_USES_AD595 - tt = analog2temp(current_raw); + hotendtC = analog2temp(current_raw); #endif #if TEMP_1_PIN > -1 || defined BED_USES_AD595 - bt = analog2tempBed(current_bed_raw); + bedtempC = analog2tempBed(current_bed_raw); #endif #if (TEMP_0_PIN > -1) || defined (HEATER_USES_MAX6675) || defined HEATER_USES_AD595 - Serial.print("ok T:"); - Serial.print(tt); + showString(PSTR("ok T:")); + Serial.print(hotendtC); #ifdef PIDTEMP - Serial.print(" @:"); + showString(PSTR(" @:")); Serial.print(heater_duty); - Serial.print(","); + showString(PSTR(",P:")); + Serial.print(pTerm); + showString(PSTR(",I:")); Serial.print(iTerm); + showString(PSTR(",D:")); + Serial.print(dTerm); + #ifdef AUTOTEMP + showString(PSTR(",AU:")); + Serial.print(autotemp_setpoint); + #endif #endif #if TEMP_1_PIN > -1 || defined BED_USES_AD595 - Serial.print(" B:"); - Serial.println(bt); + showString(PSTR(" B:")); + Serial.println(bedtempC); #else Serial.println(); #endif @@ -826,10 +1158,13 @@ inline void process_commands() case 109: { // M109 - Wait for extruder heater to reach target. if (code_seen('S')) target_raw = temp2analogh(target_temp = code_value()); #ifdef WATCHPERIOD - if(target_raw>current_raw){ + if(target_raw>current_raw) + { watchmillis = max(1,millis()); watch_raw = current_raw; - }else{ + } + else + { watchmillis = 0; } #endif @@ -850,7 +1185,7 @@ inline void process_commands() #endif if( (millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up/cooling down { - Serial.print("T:"); + showString(PSTR("T:")); Serial.println( analog2temp(current_raw) ); codenum = millis(); } @@ -869,35 +1204,38 @@ inline void process_commands() break; case 190: // M190 - Wait bed for heater to reach target. #if TEMP_1_PIN > -1 - if (code_seen('S')) target_bed_raw = temp2analogh(code_value()); + if (code_seen('S')) target_bed_raw = temp2analogBed(code_value()); codenum = millis(); - while(current_bed_raw < target_bed_raw) { + while(current_bed_raw < target_bed_raw) + { if( (millis()-codenum) > 1000 ) //Print Temp Reading every 1 second while heating up. { - tt=analog2temp(current_raw); - Serial.print("T:"); - Serial.print( tt ); - Serial.print(" B:"); - Serial.println( analog2temp(current_bed_raw) ); + hotendtC=analog2temp(current_raw); + showString(PSTR("T:")); + Serial.print( hotendtC ); + showString(PSTR(" B:")); + Serial.println( analog2tempBed(current_bed_raw) ); codenum = millis(); } - manage_heater(); + manage_heater(); } #endif break; #if FAN_PIN > -1 case 106: //M106 Fan On - if (code_seen('S')){ + if (code_seen('S')) + { WRITE(FAN_PIN, HIGH); - analogWrite(FAN_PIN, constrain(code_value(),0,255) ); + //analogWrite(FAN_PIN, constrain(code_value(),0,255) ); } - else { + else + { WRITE(FAN_PIN, HIGH); - analogWrite(FAN_PIN, 255 ); + //analogWrite(FAN_PIN, 255 ); } break; case 107: //M107 Fan Off - analogWrite(FAN_PIN, 0); + //analogWrite(FAN_PIN, 0); WRITE(FAN_PIN, LOW); break; #endif @@ -916,82 +1254,153 @@ inline void process_commands() axis_relative_modes[3] = true; break; case 84: - if(code_seen('S')){ stepper_inactive_time = code_value() * 1000; } - else{ disable_x(); disable_y(); disable_z(); disable_e(); } + st_synchronize(); // wait for all movements to finish + if(code_seen('S')) + { + stepper_inactive_time = code_value() * 1000; + } + else + { + disable_x(); + disable_y(); + disable_z(); + disable_e(); + } break; case 85: // M85 code_seen('S'); max_inactive_time = code_value() * 1000; break; case 92: // M92 - for(int i=0; i < NUM_AXIS; i++) { + for(int i=0; i < NUM_AXIS; i++) + { if(code_seen(axis_codes[i])) axis_steps_per_unit[i] = code_value(); } + //Update start speed intervals and axis order. TODO: refactor axis_max_interval[] calculation into a function, as it + // should also be used in setup() as well #ifdef RAMP_ACCELERATION - setup_acceleration(); + long temp_max_intervals[NUM_AXIS]; + for(int i=0; i < NUM_AXIS; i++) + { + axis_max_interval[i] = 100000000.0 / (max_start_speed_units_per_second[i] * axis_steps_per_unit[i]);//TODO: do this for + // all steps_per_unit related variables + } #endif - break; case 115: // M115 - Serial.print("FIRMWARE_NAME:Sprinter FIRMWARE_URL:http%%3A/github.com/kliment/Sprinter/ PROTOCOL_VERSION:1.0 MACHINE_TYPE:Mendel EXTRUDER_COUNT:1 UUID:"); - Serial.println(uuid); + showString(PSTR("FIRMWARE_NAME: SprinterV2 PROTOCOL_VERSION:1.0 MACHINE_TYPE:Mendel EXTRUDER_COUNT:1\r\n")); + //Serial.println(uuid); + showString(PSTR(_DEF_CHAR_UUID)); + showString(PSTR("\r\n")); break; case 114: // M114 - Serial.print("X:"); + showString(PSTR("X:")); Serial.print(current_position[0]); - Serial.print("Y:"); + showString(PSTR("Y:")); Serial.print(current_position[1]); - Serial.print("Z:"); + showString(PSTR("Z:")); Serial.print(current_position[2]); - Serial.print("E:"); + showString(PSTR("E:")); Serial.println(current_position[3]); break; case 119: // M119 + #if (X_MIN_PIN > -1) - Serial.print("x_min:"); - Serial.print((READ(X_MIN_PIN)^X_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("x_min:")); + Serial.print((READ(X_MIN_PIN)^X_ENDSTOP_INVERT)?"H ":"L "); #endif #if (X_MAX_PIN > -1) - Serial.print("x_max:"); - Serial.print((READ(X_MAX_PIN)^X_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("x_max:")); + Serial.print((READ(X_MAX_PIN)^X_ENDSTOP_INVERT)?"H ":"L "); #endif #if (Y_MIN_PIN > -1) - Serial.print("y_min:"); - Serial.print((READ(Y_MIN_PIN)^Y_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("y_min:")); + Serial.print((READ(Y_MIN_PIN)^Y_ENDSTOP_INVERT)?"H ":"L "); #endif #if (Y_MAX_PIN > -1) - Serial.print("y_max:"); - Serial.print((READ(Y_MAX_PIN)^Y_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("y_max:")); + Serial.print((READ(Y_MAX_PIN)^Y_ENDSTOP_INVERT)?"H ":"L "); #endif #if (Z_MIN_PIN > -1) - Serial.print("z_min:"); - Serial.print((READ(Z_MIN_PIN)^Z_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("z_min:")); + Serial.print((READ(Z_MIN_PIN)^Z_ENDSTOP_INVERT)?"H ":"L "); #endif #if (Z_MAX_PIN > -1) - Serial.print("z_max:"); - Serial.print((READ(Z_MAX_PIN)^Z_ENDSTOP_INVERT)?"H ":"L "); + showString(PSTR("z_max:")); + Serial.print((READ(Z_MAX_PIN)^Z_ENDSTOP_INVERT)?"H ":"L "); #endif - Serial.println(""); + + showString(PSTR("\r\n")); break; #ifdef RAMP_ACCELERATION //TODO: update for all axis, use for loop case 201: // M201 - for(int i=0; i < NUM_AXIS; i++) { + for(int i=0; i < NUM_AXIS; i++) + { if(code_seen(axis_codes[i])) axis_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i]; } break; case 202: // M202 - for(int i=0; i < NUM_AXIS; i++) { + for(int i=0; i < NUM_AXIS; i++) + { if(code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i]; } break; #endif + case 203: // M203 Temperature monitor + if(code_seen('S')) manage_monitor = code_value(); + if(manage_monitor==100) manage_monitor=1; // Set 100 to heated bed + break; + case 220: // M220 S- set speed factor override percentage + { + if(code_seen('S')) + { + feedmultiply = code_value() ; + if(feedmultiply < 20) feedmultiply = 20; + if(feedmultiply > 200) feedmultiply = 200; + feedmultiplychanged=true; + } + } + break; +#ifdef DEBUG_HEATER_TEMP + case 601: // M601 show Extruder Temp jitter + #if (TEMP_0_PIN > -1) || defined (HEATER_USES_MAX6675)|| defined HEATER_USES_AD595 + if(current_raw_maxval > 0) + tt_maxval = analog2temp(current_raw_maxval); + if(current_raw_minval < 10000) + tt_minval = analog2temp(current_raw_minval); + #endif + + showString(PSTR("Tmin:")); + Serial.print(tt_minval); + showString(PSTR(" / Tmax:")); + Serial.print(tt_maxval); + showString(PSTR(" ")); + break; + case 602: // M602 reset Extruder Temp jitter + current_raw_minval = 32000; + current_raw_maxval = -32000; + + showString(PSTR("T Minmax Reset ")); + break; +#endif + case 603: // M603 Free RAM + showString(PSTR("Free Ram: ")); + Serial.println(FreeRam1()); + break; + default: + #ifdef SEND_WRONG_CMD_INFO + showString(PSTR("Unknown M-COM:")); + Serial.println(cmdbuffer[bufindr]); + #endif + break; + } } else{ - Serial.println("Unknown command:"); + showString(PSTR("Unknown command:\r\n")); Serial.println(cmdbuffer[bufindr]); } @@ -999,11 +1408,13 @@ inline void process_commands() } + + void FlushSerialRequestResend() { //char cmdbuffer[bufindr][100]="Resend:"; Serial.flush(); - Serial.print("Resend:"); + showString(PSTR("Resend:")); Serial.println(gcode_LastN + 1); ClearToSend(); } @@ -1015,724 +1426,1069 @@ void ClearToSend() if(fromsd[bufindr]) return; #endif - Serial.println("ok"); + showString(PSTR("ok\r\n")); + //Serial.println("ok"); } inline void get_coordinates() { - for(int i=0; i < NUM_AXIS; i++) { + for(int i=0; i < NUM_AXIS; i++) + { if(code_seen(axis_codes[i])) destination[i] = (float)code_value() + (axis_relative_modes[i] || relative_mode)*current_position[i]; else destination[i] = current_position[i]; //Are these else lines really needed? } - if(code_seen('F')) { + + if(code_seen('F')) + { next_feedrate = code_value(); if(next_feedrate > 0.0) feedrate = next_feedrate; } } +inline void get_arc_coordinates() +{ + get_coordinates(); + if(code_seen('I')) offset[0] = code_value(); + if(code_seen('J')) offset[1] = code_value(); +} + + void prepare_move() { - //Find direction - for(int i=0; i < NUM_AXIS; i++) { - if(destination[i] >= current_position[i]) move_direction[i] = 1; - else move_direction[i] = 0; - } - - - if (min_software_endstops) { - if (destination[0] < 0) destination[0] = 0.0; - if (destination[1] < 0) destination[1] = 0.0; - if (destination[2] < 0) destination[2] = 0.0; - } + long help_feedrate = 0; - if (max_software_endstops) { - if (destination[0] > X_MAX_LENGTH) destination[0] = X_MAX_LENGTH; - if (destination[1] > Y_MAX_LENGTH) destination[1] = Y_MAX_LENGTH; - if (destination[2] > Z_MAX_LENGTH) destination[2] = Z_MAX_LENGTH; + if (min_software_endstops) + { + if (destination[X_AXIS] < 0) destination[X_AXIS] = 0.0; + if (destination[Y_AXIS] < 0) destination[Y_AXIS] = 0.0; + if (destination[Z_AXIS] < 0) destination[Z_AXIS] = 0.0; } - for(int i=0; i < NUM_AXIS; i++) { - axis_diff[i] = destination[i] - current_position[i]; - move_steps_to_take[i] = abs(axis_diff[i]) * axis_steps_per_unit[i]; - } - if(feedrate < 10) - feedrate = 10; - - //Feedrate calc based on XYZ travel distance - float xy_d; - //Check for cases where only one axis is moving - handle those without float sqrt - if(abs(axis_diff[0]) > 0 && abs(axis_diff[1]) == 0 && abs(axis_diff[2])==0) - d=abs(axis_diff[0]); - else if(abs(axis_diff[0]) == 0 && abs(axis_diff[1]) > 0 && abs(axis_diff[2])==0) - d=abs(axis_diff[1]); - else if(abs(axis_diff[0]) == 0 && abs(axis_diff[1]) == 0 && abs(axis_diff[2])>0) - d=abs(axis_diff[2]); - //two or three XYZ axes moving - else if(abs(axis_diff[0]) > 0 || abs(axis_diff[1]) > 0) { //X or Y or both - xy_d = sqrt(axis_diff[0] * axis_diff[0] + axis_diff[1] * axis_diff[1]); - //check if Z involved - if so interpolate that too - d = (abs(axis_diff[2])>0)?sqrt(xy_d * xy_d + axis_diff[2] * axis_diff[2]):xy_d; - } - else if(abs(axis_diff[3]) > 0) - d = abs(axis_diff[3]); - else{ //zero length move - #ifdef DEBUG_PREPARE_MOVE - - log_message("_PREPARE_MOVE - No steps to take!"); - - #endif - return; - } - time_for_move = (d / (feedrate / 60000000.0) ); - //Check max feedrate for each axis is not violated, update time_for_move if necessary - for(int i = 0; i < NUM_AXIS; i++) { - if(move_steps_to_take[i] && abs(axis_diff[i]) / (time_for_move / 60000000.0) > max_feedrate[i]) { - time_for_move = time_for_move / max_feedrate[i] * (abs(axis_diff[i]) / (time_for_move / 60000000.0)); - } - } - //Calculate the full speed stepper interval for each axis - for(int i=0; i < NUM_AXIS; i++) { - if(move_steps_to_take[i]) axis_interval[i] = time_for_move / move_steps_to_take[i] * 100; + if (max_software_endstops) + { + if (destination[X_AXIS] > X_MAX_LENGTH) destination[X_AXIS] = X_MAX_LENGTH; + if (destination[Y_AXIS] > Y_MAX_LENGTH) destination[Y_AXIS] = Y_MAX_LENGTH; + if (destination[Z_AXIS] > Z_MAX_LENGTH) destination[Z_AXIS] = Z_MAX_LENGTH; } - - #ifdef DEBUG_PREPARE_MOVE - log_float("_PREPARE_MOVE - Move distance on the XY plane", xy_d); - log_float("_PREPARE_MOVE - Move distance on the XYZ space", d); - log_int("_PREPARE_MOVE - Commanded feedrate", feedrate); - log_float("_PREPARE_MOVE - Constant full speed move time", time_for_move); - log_float_array("_PREPARE_MOVE - Destination", destination, NUM_AXIS); - log_float_array("_PREPARE_MOVE - Current position", current_position, NUM_AXIS); - log_ulong_array("_PREPARE_MOVE - Steps to take", move_steps_to_take, NUM_AXIS); - log_long_array("_PREPARE_MOVE - Axes full speed intervals", axis_interval, NUM_AXIS); - #endif - unsigned long move_steps[NUM_AXIS]; + help_feedrate = ((long)feedrate*(long)feedmultiply); + plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], help_feedrate/6000.0); + for(int i=0; i < NUM_AXIS; i++) - move_steps[i] = move_steps_to_take[i]; - linear_move(move_steps); // make the move + { + current_position[i] = destination[i]; + } } -inline void linear_move(unsigned long axis_steps_remaining[]) // make linear move with preset speeds and destinations, see G0 and G1 + + +void prepare_arc_move(char isclockwise) { - //Determine direction of movement - if (destination[0] > current_position[0]) WRITE(X_DIR_PIN,!INVERT_X_DIR); - else WRITE(X_DIR_PIN,INVERT_X_DIR); - if (destination[1] > current_position[1]) WRITE(Y_DIR_PIN,!INVERT_Y_DIR); - else WRITE(Y_DIR_PIN,INVERT_Y_DIR); - if (destination[2] > current_position[2]) WRITE(Z_DIR_PIN,!INVERT_Z_DIR); - else WRITE(Z_DIR_PIN,INVERT_Z_DIR); - if (destination[3] > current_position[3]) WRITE(E_DIR_PIN,!INVERT_E_DIR); - else WRITE(E_DIR_PIN,INVERT_E_DIR); - movereset: - #if (X_MIN_PIN > -1) - if(!move_direction[0]) if(READ(X_MIN_PIN) != X_ENDSTOP_INVERT) axis_steps_remaining[0]=0; - #endif - #if (Y_MIN_PIN > -1) - if(!move_direction[1]) if(READ(Y_MIN_PIN) != Y_ENDSTOP_INVERT) axis_steps_remaining[1]=0; - #endif - #if (Z_MIN_PIN > -1) - if(!move_direction[2]) if(READ(Z_MIN_PIN) != Z_ENDSTOP_INVERT) axis_steps_remaining[2]=0; - #endif - #if (X_MAX_PIN > -1) - if(move_direction[0]) if(READ(X_MAX_PIN) != X_ENDSTOP_INVERT) axis_steps_remaining[0]=0; - #endif - #if (Y_MAX_PIN > -1) - if(move_direction[1]) if(READ(Y_MAX_PIN) != Y_ENDSTOP_INVERT) axis_steps_remaining[1]=0; - #endif - # if(Z_MAX_PIN > -1) - if(move_direction[2]) if(READ(Z_MAX_PIN) != Z_ENDSTOP_INVERT) axis_steps_remaining[2]=0; - #endif + + float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc + long help_feedrate = 0; + + help_feedrate = ((long)feedrate*(long)feedmultiply); + // Trace the arc + mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, help_feedrate/6000.0, r, isclockwise); - //Only enable axis that are moving. If the axis doesn't need to move then it can stay disabled depending on configuration. - // TODO: maybe it's better to refactor into a generic enable(int axis) function, that will probably take more ram, - // but will reduce code size - if(axis_steps_remaining[0]) enable_x(); - if(axis_steps_remaining[1]) enable_y(); - if(axis_steps_remaining[2]) enable_z(); - if(axis_steps_remaining[3]) enable_e(); - - //Define variables that are needed for the Bresenham algorithm. Please note that Z is not currently included in the Bresenham algorithm. - unsigned long delta[] = {axis_steps_remaining[0], axis_steps_remaining[1], axis_steps_remaining[2], axis_steps_remaining[3]}; //TODO: implement a "for" to support N axes - long axis_error[NUM_AXIS]; - int primary_axis; - if(delta[1] > delta[0] && delta[1] > delta[2] && delta[1] > delta[3]) primary_axis = 1; - else if (delta[0] >= delta[1] && delta[0] > delta[2] && delta[0] > delta[3]) primary_axis = 0; - else if (delta[2] >= delta[0] && delta[2] >= delta[1] && delta[2] > delta[3]) primary_axis = 2; - else primary_axis = 3; - unsigned long steps_remaining = delta[primary_axis]; - unsigned long steps_to_take = steps_remaining; - for(int i=0; i < NUM_AXIS; i++){ - if(i != primary_axis) axis_error[i] = delta[primary_axis] / 2; - steps_taken[i]=0; - } - interval = axis_interval[primary_axis]; - bool is_print_move = delta[3] > 0; - #ifdef DEBUG_BRESENHAM - log_int("_BRESENHAM - Primary axis", primary_axis); - log_int("_BRESENHAM - Primary axis full speed interval", interval); - log_ulong_array("_BRESENHAM - Deltas", delta, NUM_AXIS); - log_long_array("_BRESENHAM - Errors", axis_error, NUM_AXIS); - #endif + // As far as the parser is concerned, the position is now == target. In reality the + // motion control system might still be processing the action and the real tool position + // in any intermediate location. + for(int8_t i=0; i < NUM_AXIS; i++) + { + current_position[i] = destination[i]; + } +} - //If acceleration is enabled, do some Bresenham calculations depending on which axis will lead it. - #ifdef RAMP_ACCELERATION - long max_speed_steps_per_second; - long min_speed_steps_per_second; - max_interval = axis_max_interval[primary_axis]; - #ifdef DEBUG_RAMP_ACCELERATION - log_ulong_array("_RAMP_ACCELERATION - Teoric step intervals at move start", axis_max_interval, NUM_AXIS); - #endif - unsigned long new_axis_max_intervals[NUM_AXIS]; - max_speed_steps_per_second = 100000000 / interval; - min_speed_steps_per_second = 100000000 / max_interval; //TODO: can this be deleted? - //Calculate start speeds based on moving axes max start speed constraints. - int slowest_start_axis = primary_axis; - unsigned long slowest_start_axis_max_interval = max_interval; - for(int i = 0; i < NUM_AXIS; i++) - if (axis_steps_remaining[i] >0 && - i != primary_axis && - axis_max_interval[i] * axis_steps_remaining[i]/ axis_steps_remaining[slowest_start_axis] > slowest_start_axis_max_interval) { - slowest_start_axis = i; - slowest_start_axis_max_interval = axis_max_interval[i]; - } - for(int i = 0; i < NUM_AXIS; i++) - if(axis_steps_remaining[i] >0) { - // multiplying slowest_start_axis_max_interval by axis_steps_remaining[slowest_start_axis] - // could lead to overflows when we have long distance moves (say, 390625*390625 > sizeof(unsigned long)) - float steps_remaining_ratio = (float) axis_steps_remaining[slowest_start_axis] / axis_steps_remaining[i]; - new_axis_max_intervals[i] = slowest_start_axis_max_interval * steps_remaining_ratio; - - if(i == primary_axis) { - max_interval = new_axis_max_intervals[i]; - min_speed_steps_per_second = 100000000 / max_interval; - } - } - //Calculate slowest axis plateau time - float slowest_axis_plateau_time = 0; - for(int i=0; i < NUM_AXIS ; i++) { - if(axis_steps_remaining[i] > 0) { - if(is_print_move && axis_steps_remaining[i] > 0) slowest_axis_plateau_time = max(slowest_axis_plateau_time, - (100000000.0 / axis_interval[i] - 100000000.0 / new_axis_max_intervals[i]) / (float) axis_steps_per_sqr_second[i]); - else if(axis_steps_remaining[i] > 0) slowest_axis_plateau_time = max(slowest_axis_plateau_time, - (100000000.0 / axis_interval[i] - 100000000.0 / new_axis_max_intervals[i]) / (float) axis_travel_steps_per_sqr_second[i]); - } - } - //Now we can calculate the new primary axis acceleration, so that the slowest axis max acceleration is not violated - steps_per_sqr_second = (100000000.0 / axis_interval[primary_axis] - 100000000.0 / new_axis_max_intervals[primary_axis]) / slowest_axis_plateau_time; - plateau_steps = (long) ((steps_per_sqr_second / 2.0 * slowest_axis_plateau_time + min_speed_steps_per_second) * slowest_axis_plateau_time); - #ifdef DEBUG_RAMP_ACCELERATION - log_int("_RAMP_ACCELERATION - Start speed limiting axis", slowest_start_axis); - log_ulong("_RAMP_ACCELERATION - Limiting axis start interval", slowest_start_axis_max_interval); - log_ulong_array("_RAMP_ACCELERATION - Actual step intervals at move start", new_axis_max_intervals, NUM_AXIS); - #endif + +inline void kill() +{ + #if TEMP_0_PIN > -1 + target_raw=0; + WRITE(HEATER_0_PIN,LOW); #endif - unsigned long steps_done = 0; - #ifdef RAMP_ACCELERATION - plateau_steps *= 1.01; // This is to compensate we use discrete intervals - acceleration_enabled = true; - unsigned long full_interval = interval; - if(interval > max_interval) acceleration_enabled = false; - boolean decelerating = false; + #if TEMP_1_PIN > -1 + target_bed_raw=0; + if(HEATER_1_PIN > -1) WRITE(HEATER_1_PIN,LOW); #endif + + disable_x(); + disable_y(); + disable_z(); + disable_e(); - unsigned long start_move_micros = micros(); - for(int i = 0; i < NUM_AXIS; i++) { - axis_previous_micros[i] = start_move_micros * 100; + if(PS_ON_PIN > -1) pinMode(PS_ON_PIN,INPUT); + +} + +inline void manage_inactivity(byte debug) +{ + if( (millis()-previous_millis_cmd) > max_inactive_time ) if(max_inactive_time) kill(); + + if( (millis()-previous_millis_cmd) > stepper_inactive_time ) if(stepper_inactive_time) + { + disable_x(); + disable_y(); + disable_z(); + disable_e(); } + check_axes_activity(); +} - #ifdef DISABLE_CHECK_DURING_TRAVEL - //If the move time is more than allowed in DISABLE_CHECK_DURING_TRAVEL, let's - // consider this a print move and perform heat management during it - if(time_for_move / 1000 > DISABLE_CHECK_DURING_TRAVEL) is_print_move = true; - //else, if the move is a retract, consider it as a travel move for the sake of this feature - else if(delta[3]>0 && delta[0] + delta[1] + delta[2] == 0) is_print_move = false; - #ifdef DEBUG_DISABLE_CHECK_DURING_TRAVEL - log_bool("_DISABLE_CHECK_DURING_TRAVEL - is_print_move", is_print_move); - #endif - #endif - #ifdef DEBUG_MOVE_TIME - unsigned long startmove = micros(); - #endif + + +// Planner with Interrupt for Stepper + +/* + Reasoning behind the mathematics in this module (in the key of 'Mathematica'): + + s == speed, a == acceleration, t == time, d == distance + + Basic definitions: + + Speed[s_, a_, t_] := s + (a*t) + Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t] + + Distance to reach a specific speed with a constant acceleration: + + Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t] + d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance() + + Speed after a given distance of travel with constant acceleration: + + Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t] + m -> Sqrt[2 a d + s^2] + + DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2] + + When to start braking (di) to reach a specified destionation speed (s2) after accelerating + from initial speed s1 without ever stopping at a plateau: + + Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di] + di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance() + + IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a) + */ + + +static block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instructions +static volatile unsigned char block_buffer_head; // Index of the next block to be pushed +static volatile unsigned char block_buffer_tail; // Index of the block to process now + +// The current position of the tool in absolute steps +static long position[4]; + +#define ONE_MINUTE_OF_MICROSECONDS 60000000.0 + +// Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the +// given acceleration: +inline long estimate_acceleration_distance(long initial_rate, long target_rate, long acceleration) +{ + return( + (target_rate*target_rate-initial_rate*initial_rate)/ + (2L*acceleration) + ); +} + +// This function gives you the point at which you must start braking (at the rate of -acceleration) if +// you started at speed initial_rate and accelerated until this point and want to end at the final_rate after +// a total travel of distance. This can be used to compute the intersection point between acceleration and +// deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed) + +inline long intersection_distance(long initial_rate, long final_rate, long acceleration, long distance) +{ + return( + (2*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/ + (4*acceleration) + ); +} + +// Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors. + +void calculate_trapezoid_for_block(block_t *block, float entry_speed, float exit_speed) +{ + if(block->busy == true) return; // If block is busy then bail out. + float entry_factor = entry_speed / block->nominal_speed; + float exit_factor = exit_speed / block->nominal_speed; + long initial_rate = ceil(block->nominal_rate*entry_factor); + long final_rate = ceil(block->nominal_rate*exit_factor); +#ifdef ADVANCE + long initial_advance = block->advance*entry_factor*entry_factor; + long final_advance = block->advance*exit_factor*exit_factor; +#endif // ADVANCE + + // Limit minimal step rate (Otherwise the timer will overflow.) + if(initial_rate <120) initial_rate=120; + if(final_rate < 120) final_rate=120; - //move until no more steps remain - while(axis_steps_remaining[0] + axis_steps_remaining[1] + axis_steps_remaining[2] + axis_steps_remaining[3] > 0) { - #if defined RAMP_ACCELERATION && defined DISABLE_CHECK_DURING_ACC - if(!accelerating && !decelerating) { - //If more that HEATER_CHECK_INTERVAL ms have passed since previous heating check, adjust temp - #ifdef DISABLE_CHECK_DURING_TRAVEL - if(is_print_move) - #endif - manage_heater(); - } - #else - #ifdef DISABLE_CHECK_DURING_MOVE - {} //Do nothing - #else - //If more that HEATER_CHECK_INTERVAL ms have passed since previous heating check, adjust temp - #ifdef DISABLE_CHECK_DURING_TRAVEL - if(is_print_move) - #endif - manage_heater(); - #endif - #endif - #ifdef RAMP_ACCELERATION - //If acceleration is enabled on this move and we are in the acceleration segment, calculate the current interval - if (acceleration_enabled && steps_done == 0) { - interval = max_interval; - } else if (acceleration_enabled && steps_done <= plateau_steps) { - long current_speed = (long) ((((long) steps_per_sqr_second) / 100) - * ((micros() - start_move_micros) / 100)/100 + (long) min_speed_steps_per_second); - interval = 100000000 / current_speed; - if (interval < full_interval) { - accelerating = false; - interval = full_interval; + // Calculate the acceleration steps + long acceleration = block->acceleration_st; + long accelerate_steps = estimate_acceleration_distance(initial_rate, block->nominal_rate, acceleration); + long decelerate_steps = estimate_acceleration_distance(final_rate, block->nominal_rate, acceleration); + // Calculate the size of Plateau of Nominal Rate. + long plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps; + + // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will + // have to use intersection_distance() to calculate when to abort acceleration and start braking + // in order to reach the final_rate exactly at the end of this block. + if (plateau_steps < 0) { + accelerate_steps = intersection_distance(initial_rate, final_rate, acceleration, block->step_event_count); + plateau_steps = 0; + } + + long decelerate_after = accelerate_steps+plateau_steps; + long acceleration_rate = (long)((float)acceleration * 8.388608); + + CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section + if(block->busy == false) { // Don't update variables if block is busy. + block->accelerate_until = accelerate_steps; + block->decelerate_after = decelerate_after; + block->acceleration_rate = acceleration_rate; + block->initial_rate = initial_rate; + block->final_rate = final_rate; +#ifdef ADVANCE + block->initial_advance = initial_advance; + block->final_advance = final_advance; +#endif ADVANCE + } + CRITICAL_SECTION_END; +} + +// Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the +// acceleration within the allotted distance. +inline float max_allowable_speed(float acceleration, float target_velocity, float distance) { + return( + sqrt(target_velocity*target_velocity-2*acceleration*60*60*distance) + ); +} + +// "Junction jerk" in this context is the immediate change in speed at the junction of two blocks. +// This method will calculate the junction jerk as the euclidean distance between the nominal +// velocities of the respective blocks. +inline float junction_jerk(block_t *before, block_t *after) { + return(sqrt( + pow((before->speed_x-after->speed_x), 2)+ + pow((before->speed_y-after->speed_y), 2))); +} + +// Return the safe speed which is max_jerk/2, e.g. the +// speed under which you cannot exceed max_jerk no matter what you do. +float safe_speed(block_t *block) { + float safe_speed; + safe_speed = max_xy_jerk/2; + if(abs(block->speed_z) > max_z_jerk/2) safe_speed = max_z_jerk/2; + if (safe_speed > block->nominal_speed) safe_speed = block->nominal_speed; + return safe_speed; +} + +// The kernel called by planner_recalculate() when scanning the plan from last to first entry. +void planner_reverse_pass_kernel(block_t *previous, block_t *current, block_t *next) { + if(!current) { + return; + } + + float entry_speed = current->nominal_speed; + float exit_factor; + float exit_speed; + if (next) { + exit_speed = next->entry_speed; + } + else { + exit_speed = safe_speed(current); + } + + // Calculate the entry_factor for the current block. + if (previous) { + // Reduce speed so that junction_jerk is within the maximum allowed + float jerk = junction_jerk(previous, current); + if((previous->steps_x == 0) && (previous->steps_y == 0)) { + entry_speed = safe_speed(current); + } + else if (jerk > max_xy_jerk) { + entry_speed = (max_xy_jerk/jerk) * entry_speed; + } + if(abs(previous->speed_z - current->speed_z) > max_z_jerk) { + entry_speed = (max_z_jerk/abs(previous->speed_z - current->speed_z)) * entry_speed; + } + // If the required deceleration across the block is too rapid, reduce the entry_factor accordingly. + if (entry_speed > exit_speed) { + float max_entry_speed = max_allowable_speed(-current->acceleration,exit_speed, current->millimeters); + if (max_entry_speed < entry_speed) { + entry_speed = max_entry_speed; } - if (steps_done >= steps_to_take / 2) { - plateau_steps = steps_done; - max_speed_steps_per_second = 100000000 / interval; - accelerating = false; + } + } + else { + entry_speed = safe_speed(current); + } + // Store result + current->entry_speed = entry_speed; +} + +// planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This +// implements the reverse pass. +void planner_reverse_pass() { + char block_index = block_buffer_head; + block_t *block[3] = { NULL, NULL, NULL }; + while(block_index != block_buffer_tail) { + block_index--; + if(block_index < 0) block_index = BLOCK_BUFFER_SIZE-1; + block[2]= block[1]; + block[1]= block[0]; + block[0] = &block_buffer[block_index]; + planner_reverse_pass_kernel(block[0], block[1], block[2]); + } + planner_reverse_pass_kernel(NULL, block[0], block[1]); +} + +// The kernel called by planner_recalculate() when scanning the plan from first to last entry. +void planner_forward_pass_kernel(block_t *previous, block_t *current, block_t *next) { + if(!current) { + return; + } + if(previous) { + // If the previous block is an acceleration block, but it is not long enough to + // complete the full speed change within the block, we need to adjust out entry + // speed accordingly. Remember current->entry_factor equals the exit factor of + // the previous block. + if(previous->entry_speed < current->entry_speed) { + float max_entry_speed = max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters); + if (max_entry_speed < current->entry_speed) { + current->entry_speed = max_entry_speed; } - } else if (acceleration_enabled && steps_remaining <= plateau_steps) { //(interval > minInterval * 100) { - if (!accelerating) { - start_move_micros = micros(); - accelerating = true; - decelerating = true; - } - long current_speed = (long) ((long) max_speed_steps_per_second - ((((long) steps_per_sqr_second) / 100) - * ((micros() - start_move_micros) / 100)/100)); - interval = 100000000 / current_speed; - if (interval > max_interval) - interval = max_interval; - } else { - //Else, we are just use the full speed interval as current interval - interval = full_interval; - accelerating = false; } - #endif + } +} - //If there are x or y steps remaining, perform Bresenham algorithm - if(axis_steps_remaining[primary_axis]) { - #if (X_MIN_PIN > -1) - if(!move_direction[0]) if(READ(X_MIN_PIN) != X_ENDSTOP_INVERT) if(primary_axis==0) break; else if(axis_steps_remaining[0]) axis_steps_remaining[0]=0; - #endif - #if (Y_MIN_PIN > -1) - if(!move_direction[1]) if(READ(Y_MIN_PIN) != Y_ENDSTOP_INVERT) if(primary_axis==1) break; else if(axis_steps_remaining[1]) axis_steps_remaining[1]=0; - #endif - #if (X_MAX_PIN > -1) - if(move_direction[0]) if(READ(X_MAX_PIN) != X_ENDSTOP_INVERT) if(primary_axis==0) break; else if(axis_steps_remaining[0]) axis_steps_remaining[0]=0; - #endif - #if (Y_MAX_PIN > -1) - if(move_direction[1]) if(READ(Y_MAX_PIN) != Y_ENDSTOP_INVERT) if(primary_axis==1) break; else if(axis_steps_remaining[1]) axis_steps_remaining[1]=0; - #endif - #if (Z_MIN_PIN > -1) - if(!move_direction[2]) if(READ(Z_MIN_PIN) != Z_ENDSTOP_INVERT) if(primary_axis==2) break; else if(axis_steps_remaining[2]) axis_steps_remaining[2]=0; - #endif - #if (Z_MAX_PIN > -1) - if(move_direction[2]) if(READ(Z_MAX_PIN) != Z_ENDSTOP_INVERT) if(primary_axis==2) break; else if(axis_steps_remaining[2]) axis_steps_remaining[2]=0; - #endif - timediff = micros() * 100 - axis_previous_micros[primary_axis]; - if(timediff<0){//check for overflow - axis_previous_micros[primary_axis]=micros()*100; - timediff=interval/2; //approximation - } - while(((unsigned long)timediff) >= interval && axis_steps_remaining[primary_axis] > 0) { - steps_done++; - steps_remaining--; - axis_steps_remaining[primary_axis]--; timediff -= interval; - do_step(primary_axis); - axis_previous_micros[primary_axis] += interval; - for(int i=0; i < NUM_AXIS; i++) if(i != primary_axis && axis_steps_remaining[i] > 0) { - axis_error[i] = axis_error[i] - delta[i]; - if(axis_error[i] < 0) { - do_step(i); axis_steps_remaining[i]--; - axis_error[i] = axis_error[i] + delta[primary_axis]; - } - } - #ifdef STEP_DELAY_RATIO - if(timediff >= interval) delayMicroseconds(long_step_delay_ratio * interval / 10000); - #endif - #ifdef STEP_DELAY_MICROS - if(timediff >= interval) delayMicroseconds(STEP_DELAY_MICROS); - #endif - } +// planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This +// implements the forward pass. +void planner_forward_pass() { + char block_index = block_buffer_tail; + block_t *block[3] = { + NULL, NULL, NULL }; + + while(block_index != block_buffer_head) { + block[0] = block[1]; + block[1] = block[2]; + block[2] = &block_buffer[block_index]; + planner_forward_pass_kernel(block[0],block[1],block[2]); + block_index = (block_index+1) & BLOCK_BUFFER_MASK; + } + planner_forward_pass_kernel(block[1], block[2], NULL); +} + +// Recalculates the trapezoid speed profiles for all blocks in the plan according to the +// entry_factor for each junction. Must be called by planner_recalculate() after +// updating the blocks. +void planner_recalculate_trapezoids() { + char block_index = block_buffer_tail; + block_t *current; + block_t *next = NULL; + while(block_index != block_buffer_head) { + current = next; + next = &block_buffer[block_index]; + if (current) { + calculate_trapezoid_for_block(current, current->entry_speed, next->entry_speed); } + block_index = (block_index+1) & BLOCK_BUFFER_MASK; } - #ifdef DEBUG_MOVE_TIME - log_ulong("_MOVE_TIME - This move took", micros()-startmove); - #endif - - if(DISABLE_X) disable_x(); - if(DISABLE_Y) disable_y(); - if(DISABLE_Z) disable_z(); - if(DISABLE_E) disable_e(); - - // Update current position partly based on direction, we probably can combine this with the direction code above... - for(int i=0; i < NUM_AXIS; i++) { - if (destination[i] > current_position[i]) current_position[i] = current_position[i] + steps_taken[i] / axis_steps_per_unit[i]; - else current_position[i] = current_position[i] - steps_taken[i] / axis_steps_per_unit[i]; + calculate_trapezoid_for_block(next, next->entry_speed, safe_speed(next)); +} + +// Recalculates the motion plan according to the following algorithm: +// +// 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor) +// so that: +// a. The junction jerk is within the set limit +// b. No speed reduction within one block requires faster deceleration than the one, true constant +// acceleration. +// 2. Go over every block in chronological order and dial down junction speed reduction values if +// a. The speed increase within one block would require faster accelleration than the one, true +// constant acceleration. +// +// When these stages are complete all blocks have an entry_factor that will allow all speed changes to +// be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than +// the set limit. Finally it will: +// +// 3. Recalculate trapezoids for all blocks. + +void planner_recalculate() { + planner_reverse_pass(); + planner_forward_pass(); + planner_recalculate_trapezoids(); +} + +void plan_init() { + block_buffer_head = 0; + block_buffer_tail = 0; + memset(position, 0, sizeof(position)); // clear position +} + + +inline void plan_discard_current_block() { + if (block_buffer_head != block_buffer_tail) { + block_buffer_tail = (block_buffer_tail + 1) & BLOCK_BUFFER_MASK; } } -void do_step(int axis) { - switch(axis){ - case 0: - WRITE(X_STEP_PIN, HIGH); - break; - case 1: - WRITE(Y_STEP_PIN, HIGH); - break; - case 2: - WRITE(Z_STEP_PIN, HIGH); - break; - case 3: - WRITE(E_STEP_PIN, HIGH); - break; +inline block_t *plan_get_current_block() { + if (block_buffer_head == block_buffer_tail) { + return(NULL); } - steps_taken[axis]+=1; - WRITE(X_STEP_PIN, LOW); - WRITE(Y_STEP_PIN, LOW); - WRITE(Z_STEP_PIN, LOW); - WRITE(E_STEP_PIN, LOW); + block_t *block = &block_buffer[block_buffer_tail]; + block->busy = true; + return(block); } -#define HEAT_INTERVAL 250 -#ifdef HEATER_USES_MAX6675 -unsigned long max6675_previous_millis = 0; -int max6675_temp = 2000; +void check_axes_activity() { + unsigned char x_active = 0; + unsigned char y_active = 0; + unsigned char z_active = 0; + unsigned char e_active = 0; + block_t *block; + + if(block_buffer_tail != block_buffer_head) { + char block_index = block_buffer_tail; + while(block_index != block_buffer_head) { + block = &block_buffer[block_index]; + if(block->steps_x != 0) x_active++; + if(block->steps_y != 0) y_active++; + if(block->steps_z != 0) z_active++; + if(block->steps_e != 0) e_active++; + block_index = (block_index+1) & BLOCK_BUFFER_MASK; + } + } + if((DISABLE_X) && (x_active == 0)) disable_x(); + if((DISABLE_Y) && (y_active == 0)) disable_y(); + if((DISABLE_Z) && (z_active == 0)) disable_z(); + if((DISABLE_E) && (e_active == 0)) disable_e(); +} -int read_max6675() -{ - if (millis() - max6675_previous_millis < HEAT_INTERVAL) - return max6675_temp; +// Add a new linear movement to the buffer. steps_x, _y and _z is the absolute position in +// mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration +// calculation the caller must also provide the physical length of the line in millimeters. +void plan_buffer_line(float x, float y, float z, float e, float feed_rate) { + + // The target position of the tool in absolute steps + // Calculate target position in absolute steps + long target[4]; + target[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]); + target[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]); + target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]); + target[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]); - max6675_previous_millis = millis(); - - max6675_temp = 0; - - #ifdef PRR - PRR &= ~(1<busy = false; + + // Number of steps for each axis + block->steps_x = labs(target[X_AXIS]-position[X_AXIS]); + block->steps_y = labs(target[Y_AXIS]-position[Y_AXIS]); + block->steps_z = labs(target[Z_AXIS]-position[Z_AXIS]); + block->steps_e = labs(target[E_AXIS]-position[E_AXIS]); + block->step_event_count = max(block->steps_x, max(block->steps_y, max(block->steps_z, block->steps_e))); + + // Bail if this is a zero-length block + if (block->step_event_count == 0) { + return; + }; - // ensure 100ns delay - a bit extra is fine - delay(1); + //enable active axes + if(block->steps_x != 0) enable_x(); + if(block->steps_y != 0) enable_y(); + if(block->steps_z != 0) enable_z(); + if(block->steps_e != 0) enable_e(); + + float delta_x_mm = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS]; + float delta_y_mm = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS]; + float delta_z_mm = (target[Z_AXIS]-position[Z_AXIS])/axis_steps_per_unit[Z_AXIS]; + float delta_e_mm = (target[E_AXIS]-position[E_AXIS])/axis_steps_per_unit[E_AXIS]; + block->millimeters = sqrt(square(delta_x_mm) + square(delta_y_mm) + square(delta_z_mm) + square(delta_e_mm)); + + unsigned long microseconds; + microseconds = lround((block->millimeters/feed_rate)*1000000); - // read MSB - SPDR = 0; - for (;(SPSR & (1<speed_z = delta_z_mm * multiplier; + block->speed_x = delta_x_mm * multiplier; + block->speed_y = delta_y_mm * multiplier; + block->speed_e = delta_e_mm * multiplier; + + // Limit speed per axis + float speed_factor = 1; + float tmp_speed_factor; + if(abs(block->speed_x) > max_feedrate[X_AXIS]) { + speed_factor = max_feedrate[X_AXIS] / abs(block->speed_x); + } + if(abs(block->speed_y) > max_feedrate[Y_AXIS]){ + tmp_speed_factor = max_feedrate[Y_AXIS] / abs(block->speed_y); + if(speed_factor > tmp_speed_factor) speed_factor = tmp_speed_factor; + } + if(abs(block->speed_z) > max_feedrate[Z_AXIS]){ + tmp_speed_factor = max_feedrate[Z_AXIS] / abs(block->speed_z); + if(speed_factor > tmp_speed_factor) speed_factor = tmp_speed_factor; + } + if(abs(block->speed_e) > max_feedrate[E_AXIS]){ + tmp_speed_factor = max_feedrate[E_AXIS] / abs(block->speed_e); + if(speed_factor > tmp_speed_factor) speed_factor = tmp_speed_factor; + } + multiplier = multiplier * speed_factor; + block->speed_z = delta_z_mm * multiplier; + block->speed_x = delta_x_mm * multiplier; + block->speed_y = delta_y_mm * multiplier; + block->speed_e = delta_e_mm * multiplier; + block->nominal_speed = block->millimeters * multiplier; + block->nominal_rate = ceil(block->step_event_count * multiplier / 60); - // read LSB - SPDR = 0; - for (;(SPSR & (1<nominal_rate < 120) block->nominal_rate = 120; + block->entry_speed = safe_speed(block); + + // Compute the acceleration rate for the trapezoid generator. + float travel_per_step = block->millimeters/block->step_event_count; + if(block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0) { + block->acceleration_st = ceil( (retract_acceleration)/travel_per_step); // convert to: acceleration steps/sec^2 + } + else { + block->acceleration_st = ceil( (acceleration)/travel_per_step); // convert to: acceleration steps/sec^2 + // Limit acceleration per axis + if((block->acceleration_st * block->steps_x / block->step_event_count) > axis_steps_per_sqr_second[X_AXIS]) + block->acceleration_st = axis_steps_per_sqr_second[X_AXIS]; + if((block->acceleration_st * block->steps_y / block->step_event_count) > axis_steps_per_sqr_second[Y_AXIS]) + block->acceleration_st = axis_steps_per_sqr_second[Y_AXIS]; + if((block->acceleration_st * block->steps_e / block->step_event_count) > axis_steps_per_sqr_second[E_AXIS]) + block->acceleration_st = axis_steps_per_sqr_second[E_AXIS]; + if(((block->acceleration_st / block->step_event_count) * block->steps_z ) > axis_steps_per_sqr_second[Z_AXIS]) + block->acceleration_st = axis_steps_per_sqr_second[Z_AXIS]; + } + block->acceleration = block->acceleration_st * travel_per_step; - // disable TT_MAX6675 - WRITE(MAX6675_SS, 1); +#ifdef ADVANCE + // Calculate advance rate + if((block->steps_e == 0) || (block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)) { + block->advance_rate = 0; + block->advance = 0; + } + else { + long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st); + float advance = (STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K) * + (block->speed_e * block->speed_e * EXTRUTION_AREA * EXTRUTION_AREA / 3600.0)*65536; + block->advance = advance; + if(acc_dist == 0) { + block->advance_rate = 0; + } + else { + block->advance_rate = advance / (float)acc_dist; + } + } - if (max6675_temp & 4) - { - // thermocouple open - max6675_temp = 2000; +#endif // ADVANCE + + // compute a preliminary conservative acceleration trapezoid + float safespeed = safe_speed(block); + calculate_trapezoid_for_block(block, safespeed, safespeed); + + // Compute direction bits for this block + block->direction_bits = 0; + if (target[X_AXIS] < position[X_AXIS]) { + block->direction_bits |= (1<> 3; + if (target[Y_AXIS] < position[Y_AXIS]) { + block->direction_bits |= (1<direction_bits |= (1<direction_bits |= (1<= 2500) //Not a time critical function, so we only check every 2500ms +#ifdef AUTOTEMP +void getHighESpeed() +{ + static float oldt=0; + if(!autotemp_enabled) + return; + if((target_temp+2) < autotemp_min) //probably temperature set to zero. + return; //do nothing + + float high=0; + uint8_t block_index = block_buffer_tail; + + while(block_index != block_buffer_head) { - lastMotorCheck = millis(); - - if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || !READ(E_ENABLE_PIN)) //If any of the drivers are enabled... + float se=block_buffer[block_index].steps_e/float(block_buffer[block_index].step_event_count)*block_buffer[block_index].nominal_rate; + //se; units steps/sec; + if(se>high) { - lastMotor = millis(); //... set time to NOW so the fan will turn on - } - - if ((millis() - lastMotor) >= (CONTROLLERFAN_SEC*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC... - { - WRITE(CONTROLLERFAN_PIN, LOW); //... turn the fan off - } - else - { - WRITE(CONTROLLERFAN_PIN, HIGH); //... turn the fan on + high=se; } + block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1); + } + + float t=autotemp_min+high*autotemp_factor; + + if(tautotemp_max) + t=autotemp_max; + + if(oldt>t) + { + t=AUTOTEMP_OLDWEIGHT*oldt+(1-AUTOTEMP_OLDWEIGHT)*t; } + oldt=t; + autotemp_setpoint = (int)t; + } #endif -void manage_heater() + + + +// Stepper + +// intRes = intIn1 * intIn2 >> 16 +// uses: +// r26 to store 0 +// r27 to store the byte 1 of the 24 bit result +#define MultiU16X8toH16(intRes, charIn1, intIn2) \ +asm volatile ( \ +"clr r26 \n\t" \ +"mul %A1, %B2 \n\t" \ +"movw %A0, r0 \n\t" \ +"mul %A1, %A2 \n\t" \ +"add %A0, r1 \n\t" \ +"adc %B0, r26 \n\t" \ +"lsr r0 \n\t" \ +"adc %A0, r26 \n\t" \ +"adc %B0, r26 \n\t" \ +"clr r1 \n\t" \ +: \ +"=&r" (intRes) \ +: \ +"d" (charIn1), \ +"d" (intIn2) \ +: \ +"r26" \ +) + +// intRes = longIn1 * longIn2 >> 24 +// uses: +// r26 to store 0 +// r27 to store the byte 1 of the 48bit result +#define MultiU24X24toH16(intRes, longIn1, longIn2) \ +asm volatile ( \ +"clr r26 \n\t" \ +"mul %A1, %B2 \n\t" \ +"mov r27, r1 \n\t" \ +"mul %B1, %C2 \n\t" \ +"movw %A0, r0 \n\t" \ +"mul %C1, %C2 \n\t" \ +"add %B0, r0 \n\t" \ +"mul %C1, %B2 \n\t" \ +"add %A0, r0 \n\t" \ +"adc %B0, r1 \n\t" \ +"mul %A1, %C2 \n\t" \ +"add r27, r0 \n\t" \ +"adc %A0, r1 \n\t" \ +"adc %B0, r26 \n\t" \ +"mul %B1, %B2 \n\t" \ +"add r27, r0 \n\t" \ +"adc %A0, r1 \n\t" \ +"adc %B0, r26 \n\t" \ +"mul %C1, %A2 \n\t" \ +"add r27, r0 \n\t" \ +"adc %A0, r1 \n\t" \ +"adc %B0, r26 \n\t" \ +"mul %B1, %A2 \n\t" \ +"add r27, r1 \n\t" \ +"adc %A0, r26 \n\t" \ +"adc %B0, r26 \n\t" \ +"lsr r27 \n\t" \ +"adc %A0, r26 \n\t" \ +"adc %B0, r26 \n\t" \ +"clr r1 \n\t" \ +: \ +"=&r" (intRes) \ +: \ +"d" (longIn1), \ +"d" (longIn2) \ +: \ +"r26" , "r27" \ +) + +// Some useful constants + +#define ENABLE_STEPPER_DRIVER_INTERRUPT() TIMSK1 |= (1< +// +// The trapezoid is the shape the speed curve over time. It starts at block->initial_rate, accelerates +// first block->accelerate_until step_events_completed, then keeps going at constant speed until +// step_events_completed reaches block->decelerate_after after which it decelerates until the trapezoid generator is reset. +// The slope of acceleration is calculated with the leib ramp alghorithm. + +void st_wake_up() { - if((millis() - previous_millis_heater) < HEATER_CHECK_INTERVAL ) - return; - previous_millis_heater = millis(); - #ifdef HEATER_USES_THERMISTOR - current_raw = analogRead(TEMP_0_PIN); - #ifdef DEBUG_HEAT_MGMT - log_int("_HEAT_MGMT - analogRead(TEMP_0_PIN)", current_raw); - log_int("_HEAT_MGMT - NUMTEMPS", NUMTEMPS); - #endif - // When using thermistor, when the heater is colder than targer temp, we get a higher analog reading than target, - // this switches it up so that the reading appears lower than target for the control logic. - current_raw = 1023 - current_raw; - #elif defined HEATER_USES_AD595 - current_raw = analogRead(TEMP_0_PIN); - #elif defined HEATER_USES_MAX6675 - current_raw = read_max6675(); - #endif - #ifdef SMOOTHING - if (!nma) nma = SMOOTHFACTOR * current_raw; - nma = (nma + current_raw) - (nma / SMOOTHFACTOR); - current_raw = nma / SMOOTHFACTOR; - #endif - #ifdef WATCHPERIOD - if(watchmillis && millis() - watchmillis > WATCHPERIOD){ - if(watch_raw + 1 >= current_raw){ - target_temp = target_raw = 0; - WRITE(HEATER_0_PIN,LOW); - analogWrite(HEATER_0_PIN, 0); - #if LED_PIN>-1 - WRITE(LED_PIN,LOW); - #endif - }else{ - watchmillis = 0; - } - } - #endif - #ifdef MINTEMP - if(current_raw <= minttemp) - target_temp = target_raw = 0; - #endif - #ifdef MAXTEMP - if(current_raw >= maxttemp) { - target_temp = target_raw = 0; - #if (ALARM_PIN > -1) - WRITE(ALARM_PIN,HIGH); - #endif - } - #endif - #if (TEMP_0_PIN > -1) || defined (HEATER_USES_MAX6675) || defined (HEATER_USES_AD595) - #ifdef PIDTEMP - int current_temp = analog2temp(current_raw); - error = target_temp - current_temp; - int delta_temp = current_temp - prev_temp; - prev_temp = current_temp; - pTerm = ((long)PID_PGAIN * error) / 256; - const int H0 = min(HEATER_DUTY_FOR_SETPOINT(target_temp),HEATER_CURRENT); - heater_duty = H0 + pTerm; - if(error < 20){ - temp_iState += error; - temp_iState = constrain(temp_iState, temp_iState_min, temp_iState_max); - iTerm = ((long)PID_IGAIN * temp_iState) / 256; - heater_duty += iTerm; - } - int prev_error = abs(target_temp - prev_temp); - int log3 = 1; // discrete logarithm base 3, plus 1 - if(prev_error > 81){ prev_error /= 81; log3 += 4; } - if(prev_error > 9){ prev_error /= 9; log3 += 2; } - if(prev_error > 3){ prev_error /= 3; log3 ++; } - dTerm = ((long)PID_DGAIN * delta_temp) / (256*log3); - heater_duty += dTerm; - heater_duty = constrain(heater_duty, 0, HEATER_CURRENT); - analogWrite(HEATER_0_PIN, heater_duty); - #if LED_PIN>-1 - analogWrite(LED_PIN, constrain(LED_PWM_FOR_BRIGHTNESS(heater_duty),0,255)); - #endif - #else - if(current_raw >= target_raw) - { - WRITE(HEATER_0_PIN,LOW); - analogWrite(HEATER_0_PIN, 0); - #if LED_PIN>-1 - WRITE(LED_PIN,LOW); - #endif - } - else - { - WRITE(HEATER_0_PIN,HIGH); - analogWrite(HEATER_0_PIN, HEATER_CURRENT); - #if LED_PIN > -1 - WRITE(LED_PIN,HIGH); - #endif - } - #endif - #endif - - if(millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL) - return; - previous_millis_bed_heater = millis(); - #ifndef TEMP_1_PIN - return; - #endif - #if TEMP_1_PIN == -1 - return; - #else + // TCNT1 = 0; + ENABLE_STEPPER_DRIVER_INTERRUPT(); +} + +inline unsigned short calc_timer(unsigned short step_rate) +{ + unsigned short timer; + if(step_rate < 32) step_rate = 32; + step_rate -= 32; // Correct for minimal speed - #ifdef BED_USES_THERMISTOR + if(step_rate >= (8*256)) + { // higher step rate + unsigned short table_address = (unsigned short)&speed_lookuptable_fast[(unsigned char)(step_rate>>8)][0]; + unsigned char tmp_step_rate = (step_rate & 0x00ff); + unsigned short gain = (unsigned short)pgm_read_word_near(table_address+2); + MultiU16X8toH16(timer, tmp_step_rate, gain); + timer = (unsigned short)pgm_read_word_near(table_address) - timer; + } + else + { // lower step rates + unsigned short table_address = (unsigned short)&speed_lookuptable_slow[0][0]; + table_address += ((step_rate)>>1) & 0xfffc; + timer = (unsigned short)pgm_read_word_near(table_address); + timer -= (((unsigned short)pgm_read_word_near(table_address+2) * (unsigned char)(step_rate & 0x0007))>>3); + } - current_bed_raw = analogRead(TEMP_1_PIN); - #ifdef DEBUG_HEAT_MGMT - log_int("_HEAT_MGMT - analogRead(TEMP_1_PIN)", current_bed_raw); - log_int("_HEAT_MGMT - BNUMTEMPS", BNUMTEMPS); - #endif + if(timer < 100) timer = 100; - // If using thermistor, when the heater is colder than targer temp, we get a higher analog reading than target, - // this switches it up so that the reading appears lower than target for the control logic. - current_bed_raw = 1023 - current_bed_raw; - #elif defined BED_USES_AD595 - current_bed_raw = analogRead(TEMP_1_PIN); + return timer; +} +// Initializes the trapezoid generator from the current block. Called whenever a new +// block begins. +inline void trapezoid_generator_reset() +{ + accelerate_until = current_block->accelerate_until; + decelerate_after = current_block->decelerate_after; + acceleration_rate = current_block->acceleration_rate; + initial_rate = current_block->initial_rate; + final_rate = current_block->final_rate; + nominal_rate = current_block->nominal_rate; + + #ifdef ADVANCE + advance = current_block->initial_advance; + final_advance = current_block->final_advance; + advance_rate = current_block->advance_rate; #endif + deceleration_time = 0; - #ifdef MINTEMP - if(current_bed_raw >= target_bed_raw || current_bed_raw < minttemp) - #else - if(current_bed_raw >= target_bed_raw) - #endif - { - WRITE(HEATER_1_PIN,LOW); - } - else - { - WRITE(HEATER_1_PIN,HIGH); - } - #endif - -#ifdef CONTROLLERFAN_PIN - controllerFan(); //Check if fan should be turned on to cool stepper drivers down -#endif + // step_rate to timer interval + acc_step_rate = initial_rate; + acceleration_time = calc_timer(acc_step_rate); + OCR1A = acceleration_time; } -#if defined (HEATER_USES_THERMISTOR) || defined (BED_USES_THERMISTOR) -int temp2analog_thermistor(int celsius, const short table[][2], int numtemps) { - int raw = 0; - byte i; - - for (i=1; istep_event_count >> 1); + counter_y = counter_x; + counter_z = counter_x; + counter_e = counter_x; + step_events_completed = 0; + e_steps = 0; + } + else { + DISABLE_STEPPER_DRIVER_INTERRUPT(); + } + } + + if (current_block != NULL) { + // Set directions TO DO This should be done once during init of trapezoid. Endstops -> interrupt + out_bits = current_block->direction_bits; + +#ifdef ADVANCE + // Calculate E early. + counter_e += current_block->steps_e; + if (counter_e > 0) { + counter_e -= current_block->step_event_count; + if ((out_bits & (1<> 16) - old_advance); + CRITICAL_SECTION_END; + old_advance = advance >> 16; +#endif //ADVANCE + + // Set direction en check limit switches + if ((out_bits & (1<step_event_count; } } + else // +direction + WRITE(X_DIR_PIN,!INVERT_X_DIR); - // Overflow: Set to last value in the table - if (i == numtemps) raw = table[i-1][0]; - - return 1023 - raw; -} -#endif - -#if defined (HEATER_USES_AD595) || defined (BED_USES_AD595) -int temp2analog_ad595(int celsius) { - return celsius * 1024 / (500); -} -#endif - -#if defined (HEATER_USES_MAX6675) || defined (BED_USES_MAX6675) -int temp2analog_max6675(int celsius) { - return celsius * 4; -} -#endif + if ((out_bits & (1<step_event_count; + } + } + else // +direction + WRITE(Y_DIR_PIN,!INVERT_Y_DIR); -#if defined (HEATER_USES_THERMISTOR) || defined (BED_USES_THERMISTOR) -int analog2temp_thermistor(int raw,const short table[][2], int numtemps) { - int celsius = 0; - byte i; - - raw = 1023 - raw; + if ((out_bits & (1<step_event_count; + } + } + else // +direction + WRITE(Z_DIR_PIN,!INVERT_Z_DIR); + +#ifndef ADVANCE + if ((out_bits & (1<steps_x; + if (counter_x > 0) { + WRITE(X_STEP_PIN, HIGH); + counter_x -= current_block->step_event_count; + WRITE(X_STEP_PIN, LOW); + } - for (i=1; i raw) - { - celsius = table[i-1][1] + - (raw - table[i-1][0]) * - (table[i][1] - table[i-1][1]) / - (table[i][0] - table[i-1][0]); + counter_y += current_block->steps_y; + if (counter_y > 0) { + WRITE(Y_STEP_PIN, HIGH); + counter_y -= current_block->step_event_count; + WRITE(Y_STEP_PIN, LOW); + } - break; - } + counter_z += current_block->steps_z; + if (counter_z > 0) { + WRITE(Z_STEP_PIN, HIGH); + counter_z -= current_block->step_event_count; + WRITE(Z_STEP_PIN, LOW); } - // Overflow: Set to last value in the table - if (i == numtemps) celsius = table[i-1][1]; +#ifndef ADVANCE + counter_e += current_block->steps_e; + if (counter_e > 0) { + WRITE(E_STEP_PIN, HIGH); + counter_e -= current_block->step_event_count; + WRITE(E_STEP_PIN, LOW); + } +#endif //!ADVANCE + + // Calculare new timer value + unsigned short timer; + unsigned short step_rate; + if (step_events_completed < accelerate_until) { + MultiU24X24toH16(acc_step_rate, acceleration_time, acceleration_rate); + acc_step_rate += initial_rate; + + // upper limit + if(acc_step_rate > nominal_rate) + acc_step_rate = nominal_rate; + + // step_rate to timer interval + timer = calc_timer(acc_step_rate); + advance += advance_rate; + acceleration_time += timer; + OCR1A = timer; + } + else if (step_events_completed >= decelerate_after) { + MultiU24X24toH16(step_rate, deceleration_time, acceleration_rate); + + if(step_rate > acc_step_rate) { // Check step_rate stays positive + step_rate = final_rate; + } + else { + step_rate = acc_step_rate - step_rate; // Decelerate from aceleration end point. + } - return celsius; + // lower limit + if(step_rate < final_rate) + step_rate = final_rate; + + // step_rate to timer interval + timer = calc_timer(step_rate); +#ifdef ADVANCE + advance -= advance_rate; + if(advance < final_advance) + advance = final_advance; +#endif //ADVANCE + deceleration_time += timer; + OCR1A = timer; + } + // If current block is finished, reset pointer + step_events_completed += 1; + if (step_events_completed >= current_block->step_event_count) { + current_block = NULL; + plan_discard_current_block(); + } + } + busy=false; } -#endif -#if defined (HEATER_USES_AD595) || defined (BED_USES_AD595) -int analog2temp_ad595(int raw) { - return raw * 500 / 1024; -} -#endif +#ifdef ADVANCE -#if defined (HEATER_USES_MAX6675) || defined (BED_USES_MAX6675) -int analog2temp_max6675(int raw) { - return raw / 4; +unsigned char old_OCR0A; +// Timer interrupt for E. e_steps is set in the main routine; +// Timer 0 is shared with millies +ISR(TIMER0_COMPA_vect) +{ + // Critical section needed because Timer 1 interrupt has higher priority. + // The pin set functions are placed on trategic position to comply with the stepper driver timing. + WRITE(E_STEP_PIN, LOW); + // Set E direction (Depends on E direction + advance) + if (e_steps < 0) { + WRITE(E_DIR_PIN,INVERT_E_DIR); + e_steps++; + WRITE(E_STEP_PIN, HIGH); + } + if (e_steps > 0) { + WRITE(E_DIR_PIN,!INVERT_E_DIR); + e_steps--; + WRITE(E_STEP_PIN, HIGH); + } + old_OCR0A += 25; // 10kHz interrupt + OCR0A = old_OCR0A; } -#endif +#endif // ADVANCE -inline void kill() +void st_init() { - #if TEMP_0_PIN > -1 - target_raw=0; - WRITE(HEATER_0_PIN,LOW); - #endif - #if TEMP_1_PIN > -1 - target_bed_raw=0; - if(HEATER_1_PIN > -1) WRITE(HEATER_1_PIN,LOW); - #endif - disable_x(); - disable_y(); - disable_z(); - disable_e(); - - if(PS_ON_PIN > -1) pinMode(PS_ON_PIN,INPUT); - + // waveform generation = 0100 = CTC + TCCR1B &= ~(1< max_inactive_time ) if(max_inactive_time) kill(); -if( (millis()-previous_millis_cmd) > stepper_inactive_time ) if(stepper_inactive_time) { disable_x(); disable_y(); disable_z(); disable_e(); } +// Block until all buffered steps are executed +void st_synchronize() +{ + while(plan_get_current_block()) { + manage_heater(); + manage_inactivity(1); + } } -#ifdef RAMP_ACCELERATION -void setup_acceleration() { - for (int i=0; i < NUM_AXIS; i++) { - axis_max_interval[i] = 100000000.0 / (max_start_speed_units_per_second[i] * axis_steps_per_unit[i]); - axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i]; - axis_travel_steps_per_sqr_second[i] = max_travel_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i]; - } -} -#endif #ifdef DEBUG void log_message(char* message) { -- cgit v1.2.1