Browse Source

Merge pull request #1485 from XPila/MK3-bed_fast_pwm

Mk3 bed fast pwm
PavelSindler 5 years ago
parent
commit
220437316b

+ 15 - 4
Firmware/Marlin.h

@@ -16,8 +16,7 @@
 #include <avr/pgmspace.h>
 #include <avr/eeprom.h>
 #include <avr/interrupt.h>
-
-
+#include "system_timer.h"
 #include "fastio.h"
 #include "Configuration.h"
 #include "pins.h"
@@ -259,10 +258,22 @@ void refresh_cmd_timeout(void);
 // The standard Arduino timer() function returns this value atomically
 // by disabling / enabling interrupts. This is costly, if the interrupts are known
 // to be disabled.
+#ifdef SYSTEM_TIMER_2
+extern volatile unsigned long timer2_millis;
+#else //SYSTEM_TIMER_2
 extern volatile unsigned long timer0_millis;
-// An unsynchronized equivalent to a standard Arduino millis() function.
+#endif //SYSTEM_TIMER_2
+
+// An unsynchronized equivalent to a standard Arduino _millis() function.
 // To be used inside an interrupt routine.
-FORCE_INLINE unsigned long millis_nc() { return timer0_millis; }
+
+FORCE_INLINE unsigned long millis_nc() { 
+#ifdef SYSTEM_TIMER_2
+	return timer2_millis;
+#else //SYSTEM_TIMER_2
+	return timer0_millis;
+#endif //SYSTEM_TIMER_2
+}
 
 #ifdef FAST_PWM_FAN
 void setPwmFrequency(uint8_t pin, int val);

+ 97 - 97
Firmware/Marlin_main.cpp

@@ -163,7 +163,7 @@
 CardReader card;
 #endif
 
-unsigned long PingTime = millis();
+unsigned long PingTime = _millis();
 unsigned long NcTime;
 
 
@@ -196,15 +196,15 @@ bool homing_flag = false;
 
 bool temp_cal_active = false;
 
-unsigned long kicktime = millis()+100000;
+unsigned long kicktime = _millis()+100000;
 
 unsigned int  usb_printing_counter;
 
 int8_t lcd_change_fil_state = 0;
 
 unsigned long pause_time = 0;
-unsigned long start_pause_print = millis();
-unsigned long t_fan_rising_edge = millis();
+unsigned long start_pause_print = _millis();
+unsigned long t_fan_rising_edge = _millis();
 LongTimer safetyTimer;
 static LongTimer crashDetTimer;
 
@@ -912,7 +912,7 @@ void update_sec_lang_from_external_flash()
 		{
 			fputs_P(PSTR(ESC_H(1,3) "Language update."), lcdout);
 			for (uint8_t i = 0; i < state; i++) fputc('.', lcdout);
-			delay(100);
+			_delay(100);
 			boot_reserved = (state + 1) | (lang << 4);
 			if ((state * LANGBOOT_BLOCKSIZE) < header.size)
 			{
@@ -1310,9 +1310,9 @@ void setup()
     for (uint16_t phase = (tmc2130_rd_MSCNT(Z_AXIS) + 8) >> 4; phase > 0; -- phase) {
       // Until the phase counter is reset to zero.
       WRITE(Z_STEP_PIN, !INVERT_Z_STEP_PIN);
-      delay(2);
+      _delay(2);
       WRITE(Z_STEP_PIN, INVERT_Z_STEP_PIN);
-      delay(2);
+      _delay(2);
     }
   }
 #endif //TMC2130
@@ -1358,16 +1358,16 @@ void setup()
 		uint32_t sumw = 0;
 		for (int i = 0; i < 1024; i++)
 		{
-			uint32_t u = micros();
+			uint32_t u = _micros();
 			bool res = card.card.readBlock(i, buff);
-			u = micros() - u;
+			u = _micros() - u;
 			if (res)
 			{
 				printf_P(PSTR("readBlock %4d 512 bytes %lu us\n"), i, u);
 				sumr += u;
-				u = micros();
+				u = _micros();
 				res = card.card.writeBlock(i, buff);
-				u = micros() - u;
+				u = _micros() - u;
 				if (res)
 				{
 					printf_P(PSTR("writeBlock %4d 512 bytes %lu us\n"), i, u);
@@ -1700,7 +1700,7 @@ void serial_read_stream() {
 */
 void host_keepalive() {
   if (farm_mode) return;
-  long ms = millis();
+  long ms = _millis();
   if (host_keepalive_interval && busy_state != NOT_BUSY) {
     if ((ms - prev_busy_signal_ms) < (long)(1000L * host_keepalive_interval)) return;
      switch (busy_state) {
@@ -1731,11 +1731,11 @@ void loop()
 {
 	KEEPALIVE_STATE(NOT_BUSY);
 
-	if ((usb_printing_counter > 0) && ((millis()-_usb_timer) > 1000))
+	if ((usb_printing_counter > 0) && ((_millis()-_usb_timer) > 1000))
 	{
 		is_usb_printing = true;
 		usb_printing_counter--;
-		_usb_timer = millis();
+		_usb_timer = _millis();
 	}
 	if (usb_printing_counter == 0)
 	{
@@ -1887,7 +1887,7 @@ static int setup_for_endstop_move(bool enable_endstops_now = true) {
     saved_feedrate = feedrate;
     int l_feedmultiply = feedmultiply;
     feedmultiply = 100;
-    previous_millis_cmd = millis();
+    previous_millis_cmd = _millis();
     
     enable_endstops(enable_endstops_now);
     return l_feedmultiply;
@@ -1901,7 +1901,7 @@ static void clean_up_after_endstop_move(int original_feedmultiply) {
     
     feedrate = saved_feedrate;
     feedmultiply = original_feedmultiply;
-    previous_millis_cmd = millis();
+    previous_millis_cmd = _millis();
 }
 
 
@@ -2276,7 +2276,7 @@ void home_xy()
 
 void refresh_cmd_timeout(void)
 {
-  previous_millis_cmd = millis();
+  previous_millis_cmd = _millis();
 }
 
 #ifdef FWRETRACT
@@ -2317,9 +2317,9 @@ void refresh_cmd_timeout(void)
 void trace() {
 //if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
     tone(BEEPER, 440);
-    delay(25);
+    _delay(25);
     noTone(BEEPER);
-    delay(20);
+    _delay(20);
 }
 /*
 void ramming() {
@@ -2380,7 +2380,7 @@ void ramming() {
 		//plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
 		//current_position[X_AXIS] -= 23; //delay
 		//plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 600/60, active_extruder); //delay
-		delay(4700);
+		_delay(4700);
 		max_feedrate[E_AXIS] = 80;
 		current_position[E_AXIS] -= 92;
 		plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 9900 / 60, active_extruder);
@@ -2487,7 +2487,7 @@ void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_
       saved_feedrate = feedrate;
       int l_feedmultiply = feedmultiply;
       feedmultiply = 100;
-      previous_millis_cmd = millis();
+      previous_millis_cmd = _millis();
 
       enable_endstops(true);
 
@@ -2675,7 +2675,7 @@ void gcode_G28(bool home_x_axis, long home_x_value, bool home_y_axis, long home_
 
       feedrate = saved_feedrate;
       feedmultiply = l_feedmultiply;
-      previous_millis_cmd = millis();
+      previous_millis_cmd = _millis();
       endstops_hit_on_purpose();
 #ifndef MESH_BED_LEVELING
       // If MESH_BED_LEVELING is not active, then it is the original Prusa i3.
@@ -3176,9 +3176,9 @@ static void gcode_PRUSA_SN()
 #if 0
         for (int b = 0; b < 3; b++) {
             tone(BEEPER, 110);
-            delay(50);
+            _delay(50);
             noTone(BEEPER);
-            delay(50);
+            _delay(50);
         }
 #endif
     } else {
@@ -3458,7 +3458,7 @@ void process_commands()
   else if(code_seen("PRUSA")){
 		if (code_seen("Ping")) {  //! PRUSA Ping
 			if (farm_mode) {
-				PingTime = millis();
+				PingTime = _millis();
 				//MYSERIAL.print(farm_no); MYSERIAL.println(": OK");
 			}	  
 		}
@@ -3544,7 +3544,7 @@ void process_commands()
 
 	} else if(code_seen("Beat")) { //! PRUSA Beat
         // Kick farm link timer
-        kicktime = millis();
+        kicktime = _millis();
 
     } else if(code_seen("FR")) { //! PRUSA FR
         // Factory full reset
@@ -3611,7 +3611,7 @@ void process_commands()
                         disable_e0();
                         disable_e1();
                         disable_e2();
-                        delay(100);
+                        _delay(100);
                         
                         //LCD_ALERTMESSAGEPGM(_T(MSG_FILAMENTCHANGE));
                         uint8_t cnt=0;
@@ -3778,9 +3778,9 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
       if(code_seen('S')) codenum = code_value() * 1000; // seconds to wait
 	  if(codenum != 0) LCD_MESSAGERPGM(_n("Sleep..."));////MSG_DWELL c=0 r=0
       st_synchronize();
-      codenum += millis();  // keep track of when we started waiting
-      previous_millis_cmd = millis();
-      while(millis() < codenum) {
+      codenum += _millis();  // keep track of when we started waiting
+      previous_millis_cmd = _millis();
+      while(_millis() < codenum) {
         manage_heater();
         manage_inactivity();
         lcd_update(0);
@@ -4798,7 +4798,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
 	case 98: //! G98 (activate farm mode)
 		farm_mode = 1;
-		PingTime = millis();
+		PingTime = _millis();
 		eeprom_update_byte((unsigned char *)EEPROM_FARM_MODE, farm_mode);
 		EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
           SilentModeMenu = SILENT_MODE_OFF;
@@ -4863,11 +4863,11 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
       lcd_ignore_click();				//call lcd_ignore_click aslo for else ???
       st_synchronize();
-      previous_millis_cmd = millis();
+      previous_millis_cmd = _millis();
       if (codenum > 0){
-        codenum += millis();  // keep track of when we started waiting
+        codenum += _millis();  // keep track of when we started waiting
 		KEEPALIVE_STATE(PAUSED_FOR_USER);
-        while(millis() < codenum && !lcd_clicked()){
+        while(_millis() < codenum && !lcd_clicked()){
           manage_heater();
           manage_inactivity(true);
           lcd_update(0);
@@ -4924,7 +4924,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 	  if (!card.paused) 
 		failstats_reset_print();
       card.startFileprint();
-      starttime=millis();
+      starttime=_millis();
 	  break;
     case 25: //M25 - Pause SD print
       card.pauseSDPrint();
@@ -4994,7 +4994,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
             card.setIndex(code_value_long());
         card.startFileprint();
         if(!call_procedure)
-          starttime=millis(); //procedure calls count as normal print time.
+          starttime=_millis(); //procedure calls count as normal print time.
       }
     } break;
     case 928: //M928 - Start SD write
@@ -5011,7 +5011,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
     case 31: //M31 take time since the start of the SD print or an M109 command
       {
-      stoptime=millis();
+      stoptime=_millis();
       char time[30];
       unsigned long t=(stoptime-starttime)/1000;
       int sec,min;
@@ -5287,9 +5287,9 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 		double radius=0.0, theta=0.0, x_sweep, y_sweep;
 		int rotational_direction, l;
 
-			rotational_direction = (unsigned long) millis() & 0x0001;			// clockwise or counter clockwise
-			radius = (unsigned long) millis() % (long) (X_MAX_LENGTH/4); 			// limit how far out to go 
-			theta = (float) ((unsigned long) millis() % (long) 360) / (360./(2*3.1415926));	// turn into radians
+			rotational_direction = (unsigned long) _millis() & 0x0001;			// clockwise or counter clockwise
+			radius = (unsigned long) _millis() % (long) (X_MAX_LENGTH/4); 			// limit how far out to go 
+			theta = (float) ((unsigned long) _millis() % (long) 360) / (360./(2*3.1415926));	// turn into radians
 
 //SERIAL_ECHOPAIR("starting radius: ",radius);
 //SERIAL_ECHOPAIR("   theta: ",theta);
@@ -5298,11 +5298,11 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
 			for( l=0; l<n_legs-1; l++) {
 				if (rotational_direction==1)
-					theta += (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
+					theta += (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
 				else
-					theta -= (float) ((unsigned long) millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
+					theta -= (float) ((unsigned long) _millis() % (long) 20) / (360.0/(2*3.1415926)); // turn into radians
 
-				radius += (float) ( ((long) ((unsigned long) millis() % (long) 10)) - 5);
+				radius += (float) ( ((long) ((unsigned long) _millis() % (long) 10)) - 5);
 				if ( radius<0.0 )
 					radius = -radius;
 
@@ -5379,7 +5379,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
 	}
 
-	delay(1000);
+	_delay(1000);
 
     clean_up_after_endstop_move(l_feedmultiply);
 
@@ -5557,7 +5557,7 @@ Sigma_Exit:
       #endif
 
       setWatch();
-      codenum = millis();
+      codenum = _millis();
 
       /* See if we are heating up or cooling down */
       target_direction = isHeatingHotend(extruder); // true if heating, false if cooling
@@ -5573,8 +5573,8 @@ Sigma_Exit:
 		heating_status = 2;
 		if (farm_mode) { prusa_statistics(2); };
         
-        //starttime=millis();
-        previous_millis_cmd = millis();
+        //starttime=_millis();
+        previous_millis_cmd = _millis();
       }
       break;
     case 190: // M190 - Wait for bed heater to reach target.
@@ -5592,7 +5592,7 @@ Sigma_Exit:
           setTargetBed(code_value());
           CooldownNoWait = false;
         }
-        codenum = millis();
+        codenum = _millis();
         
         cancel_heatup = false;
         target_direction = isHeatingBed(); // true if heating, false if cooling
@@ -5600,7 +5600,7 @@ Sigma_Exit:
 		KEEPALIVE_STATE(NOT_BUSY);
         while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) )
         {
-          if(( millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
+          if(( _millis() - codenum) > 1000 ) //Print Temp Reading every 1 second while heating up.
           {
 			  if (!farm_mode) {
 				  float tt = degHotend(active_extruder);
@@ -5612,7 +5612,7 @@ Sigma_Exit:
 				  SERIAL_PROTOCOL_F(degBed(), 1);
 				  SERIAL_PROTOCOLLN("");
 			  }
-				  codenum = millis();
+				  codenum = _millis();
 			  
           }
           manage_heater();
@@ -5623,7 +5623,7 @@ Sigma_Exit:
 		KEEPALIVE_STATE(IN_HANDLER);
 		heating_status = 4;
 
-        previous_millis_cmd = millis();
+        previous_millis_cmd = _millis();
     #endif
         break;
 
@@ -5668,7 +5668,7 @@ Sigma_Exit:
         disable_e2();
         finishAndDisableSteppers();
         fanSpeed = 0;
-        delay(1000); // Wait a little before to switch off
+        _delay(1000); // Wait a little before to switch off
       #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
         st_synchronize();
         suicide();
@@ -6221,7 +6221,7 @@ Sigma_Exit:
 #endif
             servos[servo_index].write(servo_position);
 #if defined (ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0)
-              delay(PROBE_SERVO_DEACTIVATION_DELAY);
+              _delay(PROBE_SERVO_DEACTIVATION_DELAY);
               servos[servo_index].detach();
 #endif
           }
@@ -6254,13 +6254,13 @@ Sigma_Exit:
         #if BEEPER > 0
 if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
           tone(BEEPER, beepS);
-          delay(beepP);
+          _delay(beepP);
           noTone(BEEPER);
         #endif
       }
       else
       {
-        delay(beepP);
+        _delay(beepP);
       }
     }
     break;
@@ -6319,7 +6319,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
        
          SET_OUTPUT(CHDK);
          WRITE(CHDK, HIGH);
-         chdkHigh = millis();
+         chdkHigh = _millis();
          chdkActive = true;
        
        #else
@@ -6333,7 +6333,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
         WRITE(PHOTOGRAPH_PIN, LOW);
         _delay_ms(PULSE_LENGTH);
         }
-        delay(7.33);
+        _delay(7.33);
         for(int i=0; i < NUM_PULSES; i++) {
         WRITE(PHOTOGRAPH_PIN, HIGH);
         _delay_ms(PULSE_LENGTH);
@@ -6567,7 +6567,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 		SERIAL_PROTOCOL(set_target_pinda);
 		SERIAL_PROTOCOLLN("");
 
-		codenum = millis();
+		codenum = _millis();
 		cancel_heatup = false;
 
 		bool is_pinda_cooling = false;
@@ -6576,14 +6576,14 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 		}
 
 		while ( ((!is_pinda_cooling) && (!cancel_heatup) && (current_temperature_pinda < set_target_pinda)) || (is_pinda_cooling && (current_temperature_pinda > set_target_pinda)) ) {
-			if ((millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
+			if ((_millis() - codenum) > 1000) //Print Temp Reading every 1 second while waiting.
 			{
 				SERIAL_PROTOCOLPGM("P:");
 				SERIAL_PROTOCOL_F(current_temperature_pinda, 1);
 				SERIAL_PROTOCOLPGM("/");
 				SERIAL_PROTOCOL(set_target_pinda);
 				SERIAL_PROTOCOLLN("");
-				codenum = millis();
+				codenum = _millis();
 			}
 			manage_heater();
 			manage_inactivity();
@@ -6982,7 +6982,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
               mmu_extruder = tmp_extruder;
 
 
-              delay(100);
+              _delay(100);
 
               disable_e0();
               disable_e1();
@@ -6991,7 +6991,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
               pinMode(E_MUX0_PIN, OUTPUT);
               pinMode(E_MUX1_PIN, OUTPUT);
 
-              delay(100);
+              _delay(100);
               SERIAL_ECHO_START;
               SERIAL_ECHO("T:");
               SERIAL_ECHOLN((int)tmp_extruder);
@@ -7017,7 +7017,7 @@ if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
 
                   break;
               }
-              delay(100);
+              _delay(100);
 
 #else //SNMM
               if (tmp_extruder >= EXTRUDERS) {
@@ -7146,7 +7146,7 @@ void FlushSerialRequestResend()
 // Execution of a command from a SD card will not be confirmed.
 void ClearToSend()
 {
-    previous_millis_cmd = millis();
+    previous_millis_cmd = _millis();
 	if ((CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB) || (CMDBUFFER_CURRENT_TYPE == CMDBUFFER_CURRENT_TYPE_USB_WITH_LINENR)) 
 		SERIAL_PROTOCOLLNRPGM(MSG_OK);
 }
@@ -7317,7 +7317,7 @@ void clamp_to_software_endstops(float target[3])
 void prepare_move()
 {
   clamp_to_software_endstops(destination);
-  previous_millis_cmd = millis();
+  previous_millis_cmd = _millis();
 
   // Do not use feedmultiply for E or Z only moves
   if( (current_position[X_AXIS] == destination [X_AXIS]) && (current_position[Y_AXIS] == destination [Y_AXIS])) {
@@ -7348,7 +7348,7 @@ void prepare_arc_move(char isclockwise) {
   for(int8_t i=0; i < NUM_AXIS; i++) {
     current_position[i] = destination[i];
   }
-  previous_millis_cmd = millis();
+  previous_millis_cmd = _millis();
 }
 
 #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1
@@ -7364,9 +7364,9 @@ unsigned long lastMotorCheck = 0;
 
 void controllerFan()
 {
-  if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
+  if ((_millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms
   {
-    lastMotorCheck = millis();
+    lastMotorCheck = _millis();
 
     if(!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) || (soft_pwm_bed > 0)
     #if EXTRUDERS > 2
@@ -7380,10 +7380,10 @@ void controllerFan()
     #endif
        || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled...
     {
-      lastMotor = millis(); //... set time to NOW so the fan will turn on
+      lastMotor = _millis(); //... set time to NOW so the fan will turn on
     }
 
-    if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
+    if ((_millis() - lastMotor) >= (CONTROLLERFAN_SECS*1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC...
     {
         digitalWrite(CONTROLLERFAN_PIN, 0);
         analogWrite(CONTROLLERFAN_PIN, 0);
@@ -7405,7 +7405,7 @@ static uint32_t stat_update = 0;
 
 void handle_status_leds(void) {
   float max_temp = 0.0;
-  if(millis() > stat_update) {
+  if(_millis() > stat_update) {
     stat_update += 500; // Update every 0.5s
     for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) {
        max_temp = max(max_temp, degHotend(cur_extruder));
@@ -7514,11 +7514,11 @@ void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument s
         get_command();
     }
 
-  if( (millis() - previous_millis_cmd) >  max_inactive_time )
+  if( (_millis() - previous_millis_cmd) >  max_inactive_time )
     if(max_inactive_time)
       kill(_n(""), 4);
   if(stepper_inactive_time)  {
-    if( (millis() - previous_millis_cmd) >  stepper_inactive_time )
+    if( (_millis() - previous_millis_cmd) >  stepper_inactive_time )
     {
       if(blocks_queued() == false && ignore_stepper_queue == false) {
         disable_x();
@@ -7532,7 +7532,7 @@ void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument s
   }
   
   #ifdef CHDK //Check if pin should be set to LOW after M240 set it to HIGH
-    if (chdkActive && (millis() - chdkHigh > CHDK_DELAY))
+    if (chdkActive && (_millis() - chdkHigh > CHDK_DELAY))
     {
       chdkActive = false;
       WRITE(CHDK, LOW);
@@ -7565,7 +7565,7 @@ void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument s
     controllerFan(); //Check if fan should be turned on to cool stepper drivers down
   #endif
   #ifdef EXTRUDER_RUNOUT_PREVENT
-    if( (millis() - previous_millis_cmd) >  EXTRUDER_RUNOUT_SECONDS*1000 )
+    if( (_millis() - previous_millis_cmd) >  EXTRUDER_RUNOUT_SECONDS*1000 )
     if(degHotend(active_extruder)>EXTRUDER_RUNOUT_MINTEMP)
     {
      bool oldstatus=READ(E0_ENABLE_PIN);
@@ -7578,7 +7578,7 @@ void manage_inactivity(bool ignore_stepper_queue/*=false*/) //default argument s
      current_position[E_AXIS]=oldepos;
      destination[E_AXIS]=oldedes;
      plan_set_e_position(oldepos);
-     previous_millis_cmd=millis();
+     previous_millis_cmd=_millis();
      st_synchronize();
      WRITE(E0_ENABLE_PIN,oldstatus);
     }
@@ -7621,7 +7621,7 @@ void kill(const char *full_screen_message, unsigned char id)
   sei();   // enable interrupts
   for ( int i=5; i--; lcd_update(0))
   {
-     delay(200);	
+     _delay(200);	
   }
   cli();   // disable interrupts
   suicide();
@@ -7809,10 +7809,10 @@ void delay_keep_alive(unsigned int ms)
         if (ms == 0)
             break;
         else if (ms >= 50) {
-            delay(50);
+            _delay(50);
             ms -= 50;
         } else {
-            delay(ms);
+			_delay(ms);
             ms = 0;
         }
     }
@@ -7826,11 +7826,11 @@ static void wait_for_heater(long codenum, uint8_t extruder) {
 	/* continue to loop until we have reached the target temp
 	_and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */
 	while ((!cancel_heatup) && ((residencyStart == -1) ||
-		(residencyStart >= 0 && (((unsigned int)(millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
+		(residencyStart >= 0 && (((unsigned int)(_millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL))))) {
 #else
 	while (target_direction ? (isHeatingHotend(tmp_extruder)) : (isCoolingHotend(tmp_extruder) && (CooldownNoWait == false))) {
 #endif //TEMP_RESIDENCY_TIME
-		if ((millis() - codenum) > 1000UL)
+		if ((_millis() - codenum) > 1000UL)
 		{ //Print Temp Reading and remaining time every 1 second while heating up/cooling down
 			if (!farm_mode) {
 				SERIAL_PROTOCOLPGM("T:");
@@ -7842,7 +7842,7 @@ static void wait_for_heater(long codenum, uint8_t extruder) {
 				SERIAL_PROTOCOLPGM(" W:");
 				if (residencyStart > -1)
 				{
-					codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL;
+					codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (_millis() - residencyStart)) / 1000UL;
 					SERIAL_PROTOCOLLN(codenum);
 				}
 				else
@@ -7853,7 +7853,7 @@ static void wait_for_heater(long codenum, uint8_t extruder) {
 #else
 				SERIAL_PROTOCOLLN("");
 #endif
-				codenum = millis();
+				codenum = _millis();
 		}
 			manage_heater();
 			manage_inactivity(true); //do not disable steppers
@@ -7865,7 +7865,7 @@ static void wait_for_heater(long codenum, uint8_t extruder) {
 				(residencyStart == -1 && !target_direction && (degHotend(extruder) <= (degTargetHotend(extruder) + TEMP_WINDOW))) ||
 				(residencyStart > -1 && labs(degHotend(extruder) - degTargetHotend(extruder)) > TEMP_HYSTERESIS))
 			{
-				residencyStart = millis();
+				residencyStart = _millis();
 			}
 #endif //TEMP_RESIDENCY_TIME
 	}
@@ -8028,9 +8028,9 @@ void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_
 
 		
 		//MYSERIAL.println(data_wldsd);
-		//delay(1000);
-		//delay(3000);
-		//t1 = millis();
+		//_delay(1000);
+		//_delay(3000);
+		//t1 = _millis();
 		
 		//while (digitalRead(D_DATACLOCK) == LOW) {}
 		//while (digitalRead(D_DATACLOCK) == HIGH) {}
@@ -8040,14 +8040,14 @@ void bed_analysis(float x_dimension, float y_dimension, int x_points_num, int y_
 		
 		for (int i = 0; i<13; i++)
 		{
-			//t1 = millis();
+			//t1 = _millis();
 			for (int j = 0; j < 4; j++)
 			{
 				while (digitalRead(D_DATACLOCK) == LOW) {}				
 				while (digitalRead(D_DATACLOCK) == HIGH) {}
 				bitWrite(digit[i], j, digitalRead(D_DATA));
 			}
-			//t_delay = (millis() - t1);
+			//t_delay = (_millis() - t1);
 			//SERIAL_PROTOCOLPGM(" ");
 			//SERIAL_PROTOCOL_F(t_delay, 5);
 			//SERIAL_PROTOCOLPGM(" ");
@@ -8248,7 +8248,7 @@ void long_pause() //long pause print
 {
 	st_synchronize();
 	
-	start_pause_print = millis();
+	start_pause_print = _millis();
 
 	//retract
 	current_position[E_AXIS] -= default_retraction;
@@ -8287,7 +8287,7 @@ extern uint32_t sdpos_atomic;
 
 void uvlo_() 
 {
-	unsigned long time_start = millis();
+	unsigned long time_start = _millis();
 	bool sd_print = card.sdprinting;
     // Conserve power as soon as possible.
     disable_x();
@@ -8417,7 +8417,7 @@ void uvlo_()
 	eeprom_update_byte((uint8_t*)EEPROM_POWER_COUNT, eeprom_read_byte((uint8_t*)EEPROM_POWER_COUNT) + 1);
 	eeprom_update_word((uint16_t*)EEPROM_POWER_COUNT_TOT, eeprom_read_word((uint16_t*)EEPROM_POWER_COUNT_TOT) + 1);
     
-		printf_P(_N("UVLO - end %d\n"), millis() - time_start);
+		printf_P(_N("UVLO - end %d\n"), _millis() - time_start);
     
 #if 0
     // Move the print head to the side of the print until all the power stored in the power supply capacitors is depleted.
@@ -8929,7 +8929,7 @@ void restore_print_from_ram_and_continue(float e_move)
 	active_extruder = saved_active_extruder; //restore active_extruder
 	setTargetHotendSafe(saved_extruder_temperature,saved_active_extruder);
 	heating_status = 1;
-	wait_for_heater(millis(),saved_active_extruder);
+	wait_for_heater(_millis(),saved_active_extruder);
 	heating_status = 2;
 	feedrate = saved_feedrate2; //restore feedrate
 	axis_relative_modes[E_AXIS] = saved_extruder_relative_mode;
@@ -9080,7 +9080,7 @@ void M600_wait_for_user(float HotendTempBckp) {
 		KEEPALIVE_STATE(PAUSED_FOR_USER);
 
 		int counterBeep = 0;
-		unsigned long waiting_start_time = millis();
+		unsigned long waiting_start_time = _millis();
 		uint8_t wait_for_user_state = 0;
 		lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
 		bool bFirst=true;
@@ -9112,7 +9112,7 @@ void M600_wait_for_user(float HotendTempBckp) {
 			case 0: //nozzle is hot, waiting for user to press the knob to unload filament
 				delay_keep_alive(4);
 
-				if (millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
+				if (_millis() > waiting_start_time + (unsigned long)M600_TIMEOUT * 1000) {
 					lcd_display_message_fullscreen_P(_i("Press knob to preheat nozzle and continue."));////MSG_PRESS_TO_PREHEAT c=20 r=4
 					wait_for_user_state = 1;
 					setAllTargetHotends(0);
@@ -9136,7 +9136,7 @@ void M600_wait_for_user(float HotendTempBckp) {
 
 				if (abs(degTargetHotend(active_extruder) - degHotend(active_extruder)) < 1) {
 					lcd_display_message_fullscreen_P(_T(MSG_PRESS_TO_UNLOAD));
-					waiting_start_time = millis();
+					waiting_start_time = _millis();
 					wait_for_user_state = 0;
 				}
 				else {
@@ -9185,7 +9185,7 @@ void M600_load_filament() {
 	//load filament for single material and SNMM 
 	lcd_wait_interact();
 
-	//load_filament_time = millis();
+	//load_filament_time = _millis();
 	KEEPALIVE_STATE(PAUSED_FOR_USER);
 
 #ifdef FILAMENT_SENSOR

+ 9 - 9
Firmware/Sd2Card.cpp

@@ -287,7 +287,7 @@ bool Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
   errorCode_ = type_ = 0;
   chipSelectPin_ = chipSelectPin;
   // 16-bit init start time allows over a minute
-  uint16_t t0 = (uint16_t)millis();
+  uint16_t t0 = (uint16_t)_millis();
   uint32_t arg;
 
   // set pin modes
@@ -314,7 +314,7 @@ bool Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
 
   // command to go idle in SPI mode
   while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) {
-    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
+    if (((uint16_t)_millis() - t0) > SD_INIT_TIMEOUT) {
       error(SD_CARD_ERROR_CMD0);
       goto fail;
     }
@@ -336,7 +336,7 @@ bool Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) {
 
   while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
     // check for timeout
-    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
+    if (((uint16_t)_millis() - t0) > SD_INIT_TIMEOUT) {
       error(SD_CARD_ERROR_ACMD41);
       goto fail;
     }
@@ -469,9 +469,9 @@ static uint16_t CRC_CCITT(const uint8_t* data, size_t n) {
 //------------------------------------------------------------------------------
 bool Sd2Card::readData(uint8_t* dst, uint16_t count) {
   // wait for start block token
-  uint16_t t0 = millis();
+  uint16_t t0 = _millis();
   while ((status_ = spiRec()) == 0XFF) {
-    if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
+    if (((uint16_t)_millis() - t0) > SD_READ_TIMEOUT) {
       error(SD_CARD_ERROR_READ_TIMEOUT);
       goto fail;
     }
@@ -593,9 +593,9 @@ bool Sd2Card::setSckRate(uint8_t sckRateID) {
 //------------------------------------------------------------------------------
 // wait for card to go not busy
 bool Sd2Card::waitNotBusy(uint16_t timeoutMillis) {
-  uint16_t t0 = millis();
+  uint16_t t0 = _millis();
   while (spiRec() != 0XFF) {
-    if (((uint16_t)millis() - t0) >= timeoutMillis) goto fail;
+    if (((uint16_t)_millis() - t0) >= timeoutMillis) goto fail;
   }
   return true;
 
@@ -731,9 +731,9 @@ bool Sd2Card::writeStop() {
 //FIXME Vojtech: Copied from a current version of Sd2Card Arduino code.
 // We shall likely upgrade the rest of the Sd2Card.
 uint8_t Sd2Card::waitStartBlock(void) {
-  uint16_t t0 = millis();
+  uint16_t t0 = _millis();
   while ((status_ = spiRec()) == 0XFF) {
-    if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) {
+    if (((uint16_t)_millis() - t0) > SD_READ_TIMEOUT) {
       error(SD_CARD_ERROR_READ_TIMEOUT);
       goto fail;
     }

+ 3 - 3
Firmware/Timer.cpp

@@ -4,7 +4,7 @@
  */
 
 #include "Timer.h"
-#include "Arduino.h"
+#include "system_timer.h"
 
 /**
  * @brief construct Timer
@@ -23,7 +23,7 @@ Timer<T>::Timer() : m_isRunning(false), m_started()
 template<typename T>
 void Timer<T>::start()
 {
-    m_started = millis();
+    m_started = _millis();
     m_isRunning = true;
 }
 
@@ -45,7 +45,7 @@ bool Timer<T>::expired(T msPeriod)
 {
     if (!m_isRunning) return false;
     bool expired = false;
-    const T now = millis();
+    const T now = _millis();
     if (m_started <=  m_started + msPeriod)
     {
         if ((now >= m_started + msPeriod) || (now < m_started))

+ 2 - 1
Firmware/TimerRemaining.h

@@ -8,6 +8,7 @@
 
 #include "Timer.h"
 #include "Arduino.h"
+#include "system_timer.h"
 #include <limits.h>
 
 class TimerRemaining : public LongTimer
@@ -36,7 +37,7 @@ public:
     {
       if (!running()) return 0;
       if (expired()) return 0;
-      const unsigned long now = millis();
+      const unsigned long now = _millis();
       return (started() + m_period - now);
     }
     /**

+ 4 - 4
Firmware/cardreader.cpp

@@ -41,7 +41,7 @@ CardReader::CardReader()
     WRITE(SDPOWER,HIGH);
   #endif //SDPOWER
   
-  autostart_atmillis=millis()+5000;
+  autostart_atmillis=_millis()+5000;
 }
 
 char *createFilename(char *buffer,const dir_t &p) //buffer>12characters
@@ -497,7 +497,7 @@ void CardReader::getStatus()
     SERIAL_PROTOCOL(sdpos);
     SERIAL_PROTOCOLPGM("/");
     SERIAL_PROTOCOLLN(filesize);
-    uint16_t time = millis()/60000 - starttime/60000;
+    uint16_t time = _millis()/60000 - starttime/60000;
     SERIAL_PROTOCOL(itostr2(time/60));
     SERIAL_PROTOCOL(':');
     SERIAL_PROTOCOL(itostr2(time%60));
@@ -556,7 +556,7 @@ void CardReader::checkautostart(bool force)
   {
     if(!autostart_stilltocheck)
       return;
-    if(autostart_atmillis<millis())
+    if(autostart_atmillis<_millis())
       return;
   }
   autostart_stilltocheck=false;
@@ -954,7 +954,7 @@ void CardReader::presort() {
 		lcd_set_cursor(column, 2);
 		lcd_print('\x01'); //simple progress bar
 	}
-	delay(300);
+	_delay(300);
 	lcd_set_degree();
 	lcd_clear();
 #endif

+ 6 - 6
Firmware/cmdqueue.cpp

@@ -22,8 +22,8 @@ int serial_count = 0;  //index of character read from serial line
 boolean comment_mode = false;
 char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
 
-unsigned long TimeSent = millis();
-unsigned long TimeNow = millis();
+unsigned long TimeSent = _millis();
+unsigned long TimeNow = _millis();
 
 long gcode_N = 0;
 long gcode_LastN = 0;
@@ -391,8 +391,8 @@ void get_command()
         MYSERIAL.write(serial_char); // for debuging serial line 2 in farm_mode
         selectedSerialPort = 1; 
     } */ //RP - removed
-      TimeSent = millis();
-      TimeNow = millis();
+      TimeSent = _millis();
+      TimeNow = _millis();
 
     if (serial_char < 0)
         // Ignore extended ASCII characters. These characters have no meaning in the G-code apart from the file names
@@ -527,7 +527,7 @@ void get_command()
   } // end of serial line processing loop
 
     if(farm_mode){
-        TimeNow = millis();
+        TimeNow = _millis();
         if ( ((TimeNow - TimeSent) > 800) && (serial_count > 0) ) {
             cmdbuffer[bufindw+serial_count+CMDHDRSIZE] = 0;
             
@@ -576,7 +576,7 @@ void get_command()
     {
       if(card.eof()){
         SERIAL_PROTOCOLLNRPGM(_n("Done printing file"));////MSG_FILE_PRINTED c=0 r=0
-        stoptime=millis();
+        stoptime=_millis();
         char time[30];
         unsigned long t=(stoptime-starttime-pause_time)/1000;
         pause_time = 0;

+ 3 - 3
Firmware/fsensor.cpp

@@ -215,7 +215,7 @@ void fsensor_autoload_check_start(void)
 	fsensor_autoload_y = pat9125_y; //save current y value
 	fsensor_autoload_c = 0; //reset number of changes counter
 	fsensor_autoload_sum = 0;
-	fsensor_autoload_last_millis = millis();
+	fsensor_autoload_last_millis = _millis();
 	fsensor_watch_runout = false;
 	fsensor_watch_autoload = true;
 	fsensor_err_cnt = 0;
@@ -248,8 +248,8 @@ bool fsensor_check_autoload(void)
 #if 0
 	uint8_t fsensor_autoload_c_old = fsensor_autoload_c;
 #endif
-	if ((millis() - fsensor_autoload_last_millis) < 25) return false;
-	fsensor_autoload_last_millis = millis();
+	if ((_millis() - fsensor_autoload_last_millis) < 25) return false;
+	fsensor_autoload_last_millis = _millis();
 	if (!pat9125_update_y()) //update sensor
 	{
 		fsensor_disable();

+ 1 - 1
Firmware/lcd.cpp

@@ -755,7 +755,7 @@ void lcd_update_enable(uint8_t enabled)
 			// Reset the timeout interval.
 			lcd_timeoutToStatus.start();
 			// Force the keypad update now.
-			lcd_next_update_millis = millis() - 1;
+			lcd_next_update_millis = _millis() - 1;
 			// Full update.
 			lcd_clear();
 			if (lcd_charsetup_func)

+ 11 - 11
Firmware/mmu.cpp

@@ -74,7 +74,7 @@ int mmu_puts_P(const char* str)
 {
 	mmu_clr_rx_buf();                          //clear rx buffer
     int r = fputs_P(str, uart2io);             //send command
-	mmu_last_request = millis();
+	mmu_last_request = _millis();
 	return r;
 }
 
@@ -86,7 +86,7 @@ int mmu_printf_P(const char* format, ...)
 	mmu_clr_rx_buf();                          //clear rx buffer
 	int r = vfprintf_P(uart2io, format, args); //send command
 	va_end(args);
-	mmu_last_request = millis();
+	mmu_last_request = _millis();
 	return r;
 }
 
@@ -94,7 +94,7 @@ int mmu_printf_P(const char* format, ...)
 int8_t mmu_rx_ok(void)
 {
 	int8_t res = uart2_rx_str_P(PSTR("ok\n"));
-	if (res == 1) mmu_last_response = millis();
+	if (res == 1) mmu_last_response = _millis();
 	return res;
 }
 
@@ -102,7 +102,7 @@ int8_t mmu_rx_ok(void)
 int8_t mmu_rx_start(void)
 {
 	int8_t res = uart2_rx_str_P(PSTR("start\n"));
-	if (res == 1) mmu_last_response = millis();
+	if (res == 1) mmu_last_response = _millis();
 	return res;
 }
 
@@ -158,7 +158,7 @@ void mmu_loop(void)
 		    mmu_puts_P(PSTR("S1\n")); //send 'read version' request
 			mmu_state = -2;
 		}
-		else if (millis() > 30000) //30sec after reset disable mmu
+		else if (_millis() > 30000) //30sec after reset disable mmu
 		{
 			puts_P(PSTR("MMU not responding - DISABLED"));
 			mmu_state = 0;
@@ -300,7 +300,7 @@ void mmu_loop(void)
 			mmu_last_cmd = mmu_cmd;
 			mmu_cmd = 0;
 		}
-		else if ((mmu_last_response + 300) < millis()) //request every 300ms
+		else if ((mmu_last_response + 300) < _millis()) //request every 300ms
 		{
 			if(check_for_idler_sensor()) mmu_idler_sensor_detected = true;
 #if defined MMU_DEBUG && defined MMU_FINDA_DEBUG
@@ -335,7 +335,7 @@ void mmu_loop(void)
 			if (mmu_cmd == 0)
 				mmu_ready = true;
 		}
-		else if ((mmu_last_request + MMU_P0_TIMEOUT) < millis())
+		else if ((mmu_last_request + MMU_P0_TIMEOUT) < _millis())
 		{ //resend request after timeout (30s)
 			mmu_state = 1;
 		}
@@ -365,7 +365,7 @@ void mmu_loop(void)
 			mmu_ready = true;
 			mmu_state = 1;
 		}
-		else if ((mmu_last_request + MMU_CMD_TIMEOUT) < millis())
+		else if ((mmu_last_request + MMU_CMD_TIMEOUT) < _millis())
 		{ //resend request after timeout (5 min)
 			if (mmu_last_cmd)
 			{
@@ -395,7 +395,7 @@ void mmu_loop(void)
 			mmu_ready = true;
 			mmu_state = 1;
 		}
-		else if ((mmu_last_request + MMU_CMD_TIMEOUT) < millis())
+		else if ((mmu_last_request + MMU_CMD_TIMEOUT) < _millis())
 		{ //resend request after timeout (5 min)
 			mmu_state = 1;
 		}
@@ -815,7 +815,7 @@ void change_extr(int
         ) { //switches multiplexer for extruders
 #ifdef SNMM
 	st_synchronize();
-	delay(100);
+	_delay(100);
 
 	disable_e0();
 	disable_e1();
@@ -848,7 +848,7 @@ void change_extr(int
 		
 		break;
 	}
-	delay(100);
+	_delay(100);
 #endif
 }
 

+ 2 - 2
Firmware/planner.cpp

@@ -535,9 +535,9 @@ void check_axes_activity()
     if (tail_fan_speed) {
       if (fan_kick_end == 0) {
         // Just starting up fan - run at full power.
-        fan_kick_end = millis() + FAN_KICKSTART_TIME;
+        fan_kick_end = _millis() + FAN_KICKSTART_TIME;
         tail_fan_speed = 255;
-      } else if (fan_kick_end > millis())
+      } else if (fan_kick_end > _millis())
         // Fan still spinning up.
         tail_fan_speed = 255;
     } else {

+ 1 - 1
Firmware/stepper.cpp

@@ -1537,7 +1537,7 @@ void digitalPotWrite(int address, int value) // From Arduino DigitalPotControl e
     SPI.transfer(address); //  send in the address and value via SPI:
     SPI.transfer(value);
     digitalWrite(DIGIPOTSS_PIN,HIGH); // take the SS pin high to de-select the chip:
-    //delay(10);
+    //_delay(10);
 }
 #endif
 

+ 21 - 0
Firmware/system_timer.h

@@ -0,0 +1,21 @@
+//! @file
+
+#ifndef FIRMWARE_SYSTEM_TIMER_H_
+#define FIRMWARE_SYSTEM_TIMER_H_
+
+#include "Arduino.h"
+#define SYSTEM_TIMER_2
+
+#ifdef SYSTEM_TIMER_2
+#include "timer02.h"
+#define _millis millis2
+#define _micros micros2
+#define _delay delay2
+#else //SYSTEM_TIMER_2
+#define _millis millis
+#define _micros micros
+#define _delay delay
+#define timer02_set_pwm0(pwm0)
+#endif //SYSTEM_TIMER_2
+
+#endif /* FIRMWARE_SYSTEM_TIMER_H_ */

+ 45 - 35
Firmware/temperature.cpp

@@ -45,11 +45,6 @@
 #include "Configuration_prusa.h"
 
 
-extern "C" {
-extern void timer02_init(void);
-extern void timer02_set_pwm0(uint8_t pwm0);
-}
-
 
 //===========================================================================
 //=============================public variables============================
@@ -226,7 +221,7 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
   pid_cycle=0;
   bool heating = true;
 
-  unsigned long temp_millis = millis();
+  unsigned long temp_millis = _millis();
   unsigned long t1=temp_millis;
   unsigned long t2=temp_millis;
   long t_high = 0;
@@ -242,7 +237,7 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
 #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1) || \
     (defined(EXTRUDER_1_AUTO_FAN_PIN) && EXTRUDER_1_AUTO_FAN_PIN > -1) || \
     (defined(EXTRUDER_2_AUTO_FAN_PIN) && EXTRUDER_2_AUTO_FAN_PIN > -1)
-  unsigned long extruder_autofan_last_check = millis();
+  unsigned long extruder_autofan_last_check = _millis();
 #endif
 
   if ((extruder >= EXTRUDERS)
@@ -290,14 +285,14 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
       #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1) || \
           (defined(EXTRUDER_1_AUTO_FAN_PIN) && EXTRUDER_1_AUTO_FAN_PIN > -1) || \
           (defined(EXTRUDER_2_AUTO_FAN_PIN) && EXTRUDER_2_AUTO_FAN_PIN > -1)
-      if(millis() - extruder_autofan_last_check > 2500) {
+      if(_millis() - extruder_autofan_last_check > 2500) {
         checkExtruderAutoFans();
-        extruder_autofan_last_check = millis();
+        extruder_autofan_last_check = _millis();
       }
       #endif
 
       if(heating == true && input > temp) {
-        if(millis() - t2 > 5000) { 
+        if(_millis() - t2 > 5000) { 
           heating=false;
           if (extruder<0)
 		  {
@@ -306,15 +301,15 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
 		  }
           else
             soft_pwm[extruder] = (bias - d) >> 1;
-          t1=millis();
+          t1=_millis();
           t_high=t1 - t2;
           max=temp;
         }
       }
       if(heating == false && input < temp) {
-        if(millis() - t1 > 5000) {
+        if(_millis() - t1 > 5000) {
           heating=true;
-          t2=millis();
+          t2=_millis();
           t_low=t2 - t1;
           if(pid_cycle > 0) {
             bias += (d*(t_high - t_low))/(t_low + t_high);
@@ -374,7 +369,7 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
 	  pid_cycle = 0;
       return;
     }
-    if(millis() - temp_millis > 2000) {
+    if(_millis() - temp_millis > 2000) {
       int p;
       if (extruder<0){
         p=soft_pwm_bed;       
@@ -409,9 +404,9 @@ static void temp_runaway_stop(bool isPreheat, bool isBed);
 				return;
 			}
 		}
-      temp_millis = millis();
+      temp_millis = _millis();
     }
-    if(((millis() - t1) + (millis() - t2)) > (10L*60L*1000L*2L)) {
+    if(((_millis() - t1) + (_millis() - t2)) > (10L*60L*1000L*2L)) {
       SERIAL_PROTOCOLLNPGM("PID Autotune failed! timeout");
 	  pid_tuning_finished = true;
 	  pid_cycle = 0;
@@ -475,9 +470,9 @@ void setExtruderAutoFanState(int pin, bool state)
 void countFanSpeed()
 {
 	//SERIAL_ECHOPGM("edge counter 1:"); MYSERIAL.println(fan_edge_counter[1]);
-	fan_speed[0] = (fan_edge_counter[0] * (float(250) / (millis() - extruder_autofan_last_check)));
-	fan_speed[1] = (fan_edge_counter[1] * (float(250) / (millis() - extruder_autofan_last_check)));
-	/*SERIAL_ECHOPGM("time interval: "); MYSERIAL.println(millis() - extruder_autofan_last_check);
+	fan_speed[0] = (fan_edge_counter[0] * (float(250) / (_millis() - extruder_autofan_last_check)));
+	fan_speed[1] = (fan_edge_counter[1] * (float(250) / (_millis() - extruder_autofan_last_check)));
+	/*SERIAL_ECHOPGM("time interval: "); MYSERIAL.println(_millis() - extruder_autofan_last_check);
 	SERIAL_ECHOPGM("extruder fan speed:"); MYSERIAL.print(fan_speed[0]); SERIAL_ECHOPGM("; edge counter:"); MYSERIAL.println(fan_edge_counter[0]);
 	SERIAL_ECHOPGM("print fan speed:"); MYSERIAL.print(fan_speed[1]); SERIAL_ECHOPGM("; edge counter:"); MYSERIAL.println(fan_edge_counter[1]);
 	SERIAL_ECHOLNPGM(" ");*/
@@ -711,7 +706,7 @@ void manage_heater()
     }
 
     #ifdef WATCH_TEMP_PERIOD
-    if(watchmillis[e] && millis() - watchmillis[e] > WATCH_TEMP_PERIOD)
+    if(watchmillis[e] && _millis() - watchmillis[e] > WATCH_TEMP_PERIOD)
     {
         if(degHotend(e) < watch_start_temp[e] + WATCH_TEMP_INCREASE)
         {
@@ -743,22 +738,22 @@ void manage_heater()
   #if (defined(EXTRUDER_0_AUTO_FAN_PIN) && EXTRUDER_0_AUTO_FAN_PIN > -1) || \
       (defined(EXTRUDER_1_AUTO_FAN_PIN) && EXTRUDER_1_AUTO_FAN_PIN > -1) || \
       (defined(EXTRUDER_2_AUTO_FAN_PIN) && EXTRUDER_2_AUTO_FAN_PIN > -1)
-  if(millis() - extruder_autofan_last_check > 1000)  // only need to check fan state very infrequently
+  if(_millis() - extruder_autofan_last_check > 1000)  // only need to check fan state very infrequently
   {
 #if (defined(FANCHECK) && ((defined(TACH_0) && (TACH_0 >-1)) || (defined(TACH_1) && (TACH_1 > -1))))
 	countFanSpeed();
 	checkFanSpeed();
 #endif //(defined(TACH_0) && TACH_0 >-1) || (defined(TACH_1) && TACH_1 > -1)
     checkExtruderAutoFans();
-    extruder_autofan_last_check = millis();
+    extruder_autofan_last_check = _millis();
   }  
   #endif       
 #endif //DEBUG_DISABLE_FANCHECK
   
   #ifndef PIDTEMPBED
-  if(millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
+  if(_millis() - previous_millis_bed_heater < BED_CHECK_INTERVAL)
     return;
-  previous_millis_bed_heater = millis();
+  previous_millis_bed_heater = _millis();
   #endif
 
   #if TEMP_SENSOR_BED != 0
@@ -845,7 +840,10 @@ void manage_heater()
       }
     #endif
       if(target_temperature_bed==0)
+	  {
         soft_pwm_bed = 0;
+		timer02_set_pwm0(soft_pwm_bed << 1);
+	  }
   #endif
   
 #ifdef HOST_KEEPALIVE_FEATURE
@@ -1083,15 +1081,21 @@ void tp_init()
 
   adc_init();
 
+#ifdef SYSTEM_TIMER_2
   timer02_init();
-
-  // Use timer0 for temperature measurement
-  // Interleave temperature interrupt with millies interrupt
   OCR2B = 128;
   TIMSK2 |= (1<<OCIE2B);  
+#else //SYSTEM_TIMER_2
+  // Use timer0 for temperature measurement
+  // Interleave temperature interrupt with millies interrupt
+  OCR0B = 128;
+  TIMSK0 |= (1<<OCIE0B);  
+#endif //SYSTEM_TIMER_2
+
+
   
   // Wait for temperature measurement to settle
-  delay(250);
+  _delay(250);
 
 #ifdef HEATER_0_MINTEMP
   minttemp[0] = HEATER_0_MINTEMP;
@@ -1186,7 +1190,7 @@ void setWatch()
     if(degHotend(e) < degTargetHotend(e) - (WATCH_TEMP_INCREASE * 2))
     {
       watch_start_temp[e] = degHotend(e);
-      watchmillis[e] = millis();
+      watchmillis[e] = _millis();
     } 
   }
 #endif 
@@ -1203,7 +1207,7 @@ void temp_runaway_check(int _heater_id, float _target_temperature, float _curren
 	static int __preheat_errors[2] = { 0,0};
 		
 
-	if (millis() - temp_runaway_timer[_heater_id] > 2000)
+	if (_millis() - temp_runaway_timer[_heater_id] > 2000)
 	{
 
 #ifdef 	TEMP_RUNAWAY_BED_TIMEOUT
@@ -1221,7 +1225,7 @@ void temp_runaway_check(int _heater_id, float _target_temperature, float _curren
           }
 #endif
 
-		temp_runaway_timer[_heater_id] = millis();
+		temp_runaway_timer[_heater_id] = _millis();
 		if (_output == 0)
 		{
 			temp_runaway_check_active = false;
@@ -1488,10 +1492,10 @@ int max6675_temp = 2000;
 
 int read_max6675()
 {
-  if (millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL) 
+  if (_millis() - max6675_previous_millis < MAX6675_HEAT_INTERVAL) 
     return max6675_temp;
   
-  max6675_previous_millis = millis();
+  max6675_previous_millis = _millis();
   max6675_temp = 0;
     
   #ifdef	PRR
@@ -1538,9 +1542,9 @@ int read_max6675()
 #endif
 
 
-
 extern "C" {
 
+
 void adc_ready(void) //callback from adc when sampling finished
 {
 	current_temperature_raw[0] = adc_values[ADC_PIN_IDX(TEMP_0_PIN)]; //heater
@@ -1562,7 +1566,11 @@ void adc_ready(void) //callback from adc when sampling finished
 
 
 // Timer2 (originaly timer0) is shared with millies
+#ifdef SYSTEM_TIMER_2
 ISR(TIMER2_COMPB_vect)
+#else //SYSTEM_TIMER_2
+ISR(TIMER0_COMPB_vect)
+#endif //SYSTEM_TIMER_2
 {
 	static bool _lock = false;
 	if (_lock) return;
@@ -1629,7 +1637,9 @@ ISR(TIMER2_COMPB_vect)
 #endif
 #if defined(HEATER_BED_PIN) && HEATER_BED_PIN > -1
     soft_pwm_b = soft_pwm_bed;
-    //if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
+#ifndef SYSTEM_TIMER_2
+	if(soft_pwm_b > 0) WRITE(HEATER_BED_PIN,1); else WRITE(HEATER_BED_PIN,0);
+#endif //SYSTEM_TIMER_2
 #endif
 #ifdef FAN_SOFT_PWM
     soft_pwm_fan = fanSpeedSoftPwm / 2;

+ 11 - 0
Firmware/temperature.h

@@ -27,9 +27,20 @@
   #include "stepper.h"
 #endif
 
+
+#ifdef SYSTEM_TIMER_2
+
 #define ENABLE_TEMPERATURE_INTERRUPT()  TIMSK2 |= (1<<OCIE2B)
 #define DISABLE_TEMPERATURE_INTERRUPT() TIMSK2 &= ~(1<<OCIE2B)
 
+#else //SYSTEM_TIMER_2
+
+#define ENABLE_TEMPERATURE_INTERRUPT()  TIMSK0 |= (1<<OCIE0B)
+#define DISABLE_TEMPERATURE_INTERRUPT() TIMSK0 &= ~(1<<OCIE0B)
+
+#endif //SYSTEM_TIMER_2
+
+
 // public functions
 void tp_init();  //initialize the heating
 void manage_heater(); //it is critical that this is called periodically.

+ 62 - 10
Firmware/timer02.c

@@ -45,7 +45,7 @@ void timer02_init(void)
 	TCCR0A &= ~(2 << COM0B0);
 	//setup timer2
 	TCCR2A = 0x00; //COM_A-B=00, WGM_0-1=00
-	TCCR2B = (3 << CS20); //WGM_2=0, CS_0-2=011
+	TCCR2B = (4 << CS20); //WGM_2=0, CS_0-2=011
 	//mask timer2 interrupts - enable OVF, disable others
 	TIMSK2 |= (1<<TOIE2);
 	TIMSK2 &= ~(1<<OCIE2A);
@@ -77,17 +77,19 @@ void timer02_init(void)
 #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
 #define FRACT_MAX (1000 >> 3)
 
-extern volatile unsigned long timer0_overflow_count;
-extern volatile unsigned long timer0_millis;
-unsigned char timer0_fract = 0;
+//extern volatile unsigned long timer0_overflow_count;
+//extern volatile unsigned long timer0_millis;
+//unsigned char timer0_fract = 0;
+volatile unsigned long timer2_overflow_count;
+volatile unsigned long timer2_millis;
+unsigned char timer2_fract = 0;
 
 ISR(TIMER2_OVF_vect)
 {
 	// copy these to local variables so they can be stored in registers
 	// (volatile variables must be read from memory on every access)
-	unsigned long m = timer0_millis;
-	unsigned char f = timer0_fract;
-
+	unsigned long m = timer2_millis;
+	unsigned char f = timer2_fract;
 	m += MILLIS_INC;
 	f += FRACT_INC;
 	if (f >= FRACT_MAX)
@@ -95,9 +97,59 @@ ISR(TIMER2_OVF_vect)
 		f -= FRACT_MAX;
 		m += 1;
 	}
+	timer2_fract = f;
+	timer2_millis = m;
+	timer2_overflow_count++;
+}
+
+unsigned long millis2(void)
+{
+	unsigned long m;
+	uint8_t oldSREG = SREG;
+
+	// disable interrupts while we read timer0_millis or we might get an
+	// inconsistent value (e.g. in the middle of a write to timer0_millis)
+	cli();
+	m = timer2_millis;
+	SREG = oldSREG;
+
+	return m;
+}
 
-	timer0_fract = f;
-	timer0_millis = m;
-	timer0_overflow_count++;
+unsigned long micros2(void)
+{
+	unsigned long m;
+	uint8_t oldSREG = SREG, t;
+	cli();
+	m = timer2_overflow_count;
+#if defined(TCNT2)
+	t = TCNT2;
+#elif defined(TCNT2L)
+	t = TCNT2L;
+#else
+	#error TIMER 2 not defined
+#endif
+#ifdef TIFR2
+	if ((TIFR2 & _BV(TOV2)) && (t < 255))
+		m++;
+#else
+	if ((TIFR & _BV(TOV2)) && (t < 255))
+		m++;
+#endif
+	SREG = oldSREG;	
+	return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
 }
 
+void delay2(unsigned long ms)
+{
+	uint32_t start = micros2();
+	while (ms > 0)
+	{
+		yield();
+		while ( ms > 0 && (micros2() - start) >= 1000)
+		{
+			ms--;
+			start += 1000;
+		}
+	}
+}

+ 32 - 0
Firmware/timer02.h

@@ -0,0 +1,32 @@
+//timer02.h
+// use atmega timer2 as main system timer instead of timer0
+// timer0 is used for fast pwm (OC0B output)
+// original OVF handler is disabled
+#ifndef TIMER02_H
+#define TIMER02_H
+
+#include <inttypes.h>
+
+#if defined(__cplusplus)
+extern "C" {
+#endif //defined(__cplusplus)
+
+
+extern uint8_t timer02_pwm0;
+
+extern void timer02_set_pwm0(uint8_t pwm0);
+
+extern void timer02_init(void);
+
+extern unsigned long millis2(void);
+
+extern unsigned long micros2(void);
+
+extern void delay2(unsigned long ms);
+
+
+#if defined(__cplusplus)
+}
+#endif //defined(__cplusplus)
+
+#endif //TIMER02_H

+ 4 - 4
Firmware/tmc2130.cpp

@@ -381,7 +381,7 @@ bool tmc2130_wait_standstill_xy(int timeout)
 void tmc2130_check_overtemp()
 {
 	static uint32_t checktime = 0;
-	if (millis() - checktime > 1000 )
+	if (_millis() - checktime > 1000 )
 	{
 		for (int i = 0; i < 4; i++)
 		{
@@ -398,7 +398,7 @@ void tmc2130_check_overtemp()
 			}
 
 		}
-		checktime = millis();
+		checktime = _millis();
 		tmc2130_sg_change = true;
 	}
 #ifdef DEBUG_CRASHDET_COUNTERS
@@ -697,9 +697,9 @@ uint16_t tmc2130_get_res(uint8_t axis)
 void tmc2130_set_res(uint8_t axis, uint16_t res)
 {
 	tmc2130_mres[axis] = tmc2130_usteps2mres(res);
-//	uint32_t u = micros();
+//	uint32_t u = _micros();
 	tmc2130_setup_chopper(axis, tmc2130_mres[axis], tmc2130_current_h[axis], tmc2130_current_r[axis]);
-//	u = micros() - u;
+//	u = _micros() - u;
 //	printf_P(PSTR("tmc2130_setup_chopper %c %lu us"), "XYZE"[axis], u);
 }
 

+ 77 - 77
Firmware/ultralcd.cpp

@@ -300,8 +300,8 @@ static void lcd_implementation_drawmenu_sdfile_selected(uint8_t row, char* longF
 				j = 0;
 				break;
             }else{
-				if (j == 1) delay(3);	//wait around 1.2 s to start scrolling text
-				delay(1);				//then scroll with redrawing every 300 ms 
+				if (j == 1) _delay(3);	//wait around 1.2 s to start scrolling text
+				_delay(1);				//then scroll with redrawing every 300 ms 
             }
 
           }
@@ -595,7 +595,7 @@ void lcdui_print_farm(void)
         
         // Beat display
         lcd_set_cursor(LCD_WIDTH - 1, 0);
-        if ( (millis() - kicktime) < 60000 ) {
+        if ( (_millis() - kicktime) < 60000 ) {
         
             lcd_puts_P(PSTR("L"));
         
@@ -636,7 +636,7 @@ void lcdui_print_time(void)
 	if (print_time_remaining_normal != PRINT_TIME_REMAINING_INIT)
 		print_t = print_time_remaining();
 	else if(starttime != 0)
-		print_t = millis() / 60000 - starttime / 60000;
+		print_t = _millis() / 60000 - starttime / 60000;
 	int chars = 0;
 	if ((PRINTER_ACTIVE) && ((print_time_remaining_normal != PRINT_TIME_REMAINING_INIT) || (starttime != 0)))
 	{
@@ -1755,10 +1755,10 @@ void lcd_commands()
 			else {
 				SERIAL_ECHOPGM("Invalid PID cal. results. Not stored to EEPROM.");
 			}
-			display_time = millis();
+			display_time = _millis();
 			lcd_commands_step = 1;
 		}
-		if ((lcd_commands_step == 1) && ((millis()- display_time)>2000)) { //calibration finished message
+		if ((lcd_commands_step == 1) && ((_millis()- display_time)>2000)) { //calibration finished message
 			lcd_setstatuspgm(_T(WELCOME_MSG));
 			custom_message_type = CUSTOM_MSG_TYPE_STATUS;
 			pid_temp = DEFAULT_PID_TEMP;
@@ -2384,7 +2384,7 @@ void lcd_loading_filament() {
       manage_heater();
       manage_inactivity(true);
 
-      delay(153);
+      _delay(153);
     }
 
 
@@ -2464,7 +2464,7 @@ void lcd_alright() {
         lcd_set_cursor(0, cursor_pos);
         lcd_print(">");
         enc_dif = lcd_encoder_diff;
-        delay(100);
+        _delay(100);
       }
 
     }
@@ -2473,7 +2473,7 @@ void lcd_alright() {
     if (lcd_clicked()) {
 
       lcd_change_fil_state = cursor_pos;
-      delay(500);
+      _delay(500);
 
     }
 
@@ -2494,7 +2494,7 @@ void show_preheat_nozzle_warning()
     lcd_puts_P(_T(MSG_ERROR));
     lcd_set_cursor(0, 2);
     lcd_puts_P(_T(MSG_PREHEAT_NOZZLE));
-    delay(2000);
+    _delay(2000);
     lcd_clear();
 }
 
@@ -2578,7 +2578,7 @@ void lcd_menu_statistics()
 	if (IS_SD_PRINTING)
 	{
 		const float _met = ((float)total_filament_used) / (100000.f);
-		const uint32_t _t = (millis() - starttime) / 1000ul;
+		const uint32_t _t = (_millis() - starttime) / 1000ul;
 		const int _h = _t / 3600;
 		const int _m = (_t - (_h * 3600ul)) / 60ul;
 		const int _s = _t - ((_h * 3600ul) + (_m * 60ul));
@@ -2627,7 +2627,7 @@ void lcd_menu_statistics()
 		{
 			manage_heater();
 			manage_inactivity(true);
-			delay(100);
+			_delay(100);
 		}
 		KEEPALIVE_STATE(NOT_BUSY);
 		lcd_quick_feedback();
@@ -2885,7 +2885,7 @@ static void _lcd_babystep(int axis, const char *msg)
 			}
 		}
 		_md->babystepMemMM[axis] = _md->babystepMem[axis]/cs.axis_steps_per_unit[axis]; 
-		delay(50);
+		_delay(50);
 		lcd_encoder = 0;
 		lcd_draw_update = 1;
 	}
@@ -3048,7 +3048,7 @@ void lcd_adjust_z() {
         lcd_set_cursor(0, cursor_pos);
         lcd_print(">");
         enc_dif = lcd_encoder_diff;
-        delay(100);
+        _delay(100);
       }
 
     }
@@ -3068,7 +3068,7 @@ void lcd_adjust_z() {
         EEPROM_save_B(EEPROM_BABYSTEP_Y, &zero);
         EEPROM_save_B(EEPROM_BABYSTEP_Z, &zero);
       }
-      delay(500);
+      _delay(500);
     }
   };
 
@@ -3156,22 +3156,22 @@ bool lcd_calibrate_z_end_stop_manual(bool only_z)
 
     // Until confirmed by the confirmation dialog.
     for (;;) {
-        unsigned long previous_millis_cmd = millis();
+        unsigned long previous_millis_cmd = _millis();
         const char   *msg                 = only_z ? _i("Calibrating Z. Rotate the knob to move the Z carriage up to the end stoppers. Click when done.") : _i("Calibrating XYZ. Rotate the knob to move the Z carriage up to the end stoppers. Click when done.");////MSG_MOVE_CARRIAGE_TO_THE_TOP c=20 r=8////MSG_MOVE_CARRIAGE_TO_THE_TOP_Z c=20 r=8
         const char   *msg_next            = lcd_display_message_fullscreen_P(msg);
         const bool    multi_screen        = msg_next != NULL;
-        unsigned long previous_millis_msg = millis();
+        unsigned long previous_millis_msg = _millis();
         // Until the user finishes the z up movement.
         lcd_encoder_diff = 0;
         lcd_encoder = 0;
         for (;;) {
-//          if (millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
+//          if (_millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
 //             goto canceled;
             manage_heater();
             manage_inactivity(true);
             if (abs(lcd_encoder_diff) >= ENCODER_PULSES_PER_STEP) {
-                delay(50);
-                previous_millis_cmd = millis();
+                _delay(50);
+                previous_millis_cmd = _millis();
                 lcd_encoder += abs(lcd_encoder_diff / ENCODER_PULSES_PER_STEP);
                 lcd_encoder_diff = 0;
                 if (! planner_queue_full()) {
@@ -3185,15 +3185,15 @@ bool lcd_calibrate_z_end_stop_manual(bool only_z)
                 // Abort a move if in progress.
                 planner_abort_hard();
                 while (lcd_clicked()) ;
-                delay(10);
+                _delay(10);
                 while (lcd_clicked()) ;
                 break;
             }
-            if (multi_screen && millis() - previous_millis_msg > 5000) {
+            if (multi_screen && _millis() - previous_millis_msg > 5000) {
                 if (msg_next == NULL)
                     msg_next = msg;
                 msg_next = lcd_display_message_fullscreen_P(msg_next);
-                previous_millis_msg = millis();
+                previous_millis_msg = _millis();
             }
         }
         // Let the user confirm, that the Z carriage is at the top end stoppers.
@@ -3363,13 +3363,13 @@ bool lcd_wait_for_click_delay(uint16_t nDelay)
 // true ~ clicked, false ~ delayed
 {
 bool bDelayed;
-long nTime0 = millis()/1000;
+long nTime0 = _millis()/1000;
 	lcd_consume_click();
 	KEEPALIVE_STATE(PAUSED_FOR_USER);
     for (;;) {
         manage_heater();
         manage_inactivity(true);
-        bDelayed = ((millis()/1000-nTime0) > nDelay);
+        bDelayed = ((_millis()/1000-nTime0) > nDelay);
         bDelayed = (bDelayed && (nDelay != 0));   // 0 ~ no timeout, always waiting for click
         if (lcd_clicked() || bDelayed) {
 			KEEPALIVE_STATE(IN_HANDLER);
@@ -3411,14 +3411,14 @@ int8_t lcd_show_multiscreen_message_two_choices_and_wait_P(const char *msg, bool
 	bool yes = default_first ? true : false;
 
 	// Wait for user confirmation or a timeout.
-	unsigned long previous_millis_cmd = millis();
+	unsigned long previous_millis_cmd = _millis();
 	int8_t        enc_dif = lcd_encoder_diff;
 	lcd_consume_click();
 	//KEEPALIVE_STATE(PAUSED_FOR_USER);
 	for (;;) {
 		for (uint8_t i = 0; i < 100; ++i) {
 			delay_keep_alive(50);
-			if (allow_timeouting && millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
+			if (allow_timeouting && _millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
 				return -1;
 			manage_heater();
 			manage_inactivity(true);
@@ -3501,12 +3501,12 @@ int8_t lcd_show_fullscreen_message_yes_no_and_wait_P(const char *msg, bool allow
 	bool yes = default_yes ? true : false;
 
 	// Wait for user confirmation or a timeout.
-	unsigned long previous_millis_cmd = millis();
+	unsigned long previous_millis_cmd = _millis();
 	int8_t        enc_dif = lcd_encoder_diff;
 	lcd_consume_click();
 	KEEPALIVE_STATE(PAUSED_FOR_USER);
 	for (;;) {
-		if (allow_timeouting && millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
+		if (allow_timeouting && _millis() - previous_millis_cmd > LCD_TIMEOUT_TO_STATUS)
 			return -1;
 		manage_heater();
 		manage_inactivity(true);
@@ -3908,7 +3908,7 @@ static void prusa_stat_printinfo()
 	SERIAL_ECHO("][TIM:");
 	if (starttime != 0)
 	{
-		SERIAL_ECHO(millis() / 1000 - starttime / 1000);
+		SERIAL_ECHO(_millis() / 1000 - starttime / 1000);
 	}
 	else
 	{
@@ -4002,7 +4002,7 @@ void lcd_pick_babystep(){
                 
    
                 enc_dif = lcd_encoder_diff;
-                delay(100);
+                _delay(100);
             }
             
         }
@@ -4013,7 +4013,7 @@ void lcd_pick_babystep(){
             EEPROM_read_B(EEPROM_BABYSTEP_Z0+((fsm-1)*2),&babyStepZ);
             EEPROM_save_B(EEPROM_BABYSTEP_Z,&babyStepZ);
             calibration_status_store(CALIBRATION_STATUS_CALIBRATED);
-            delay(500);
+            _delay(500);
             
         }
     };
@@ -4079,10 +4079,10 @@ static void lcd_crash_mode_info()
 {
 	lcd_update_enable(true);
 	static uint32_t tim = 0;
-	if ((tim + 1000) < millis())
+	if ((tim + 1000) < _millis())
 	{
 		fputs_P(_i("\x1b[2JCrash detection can\x1b[1;0Hbe turned on only in\x1b[2;0HNormal mode"), lcdout);////MSG_CRASH_DET_ONLY_IN_NORMAL c=20 r=4
-		tim = millis();
+		tim = _millis();
 	}
     menu_back_if_clicked();
 }
@@ -4091,10 +4091,10 @@ static void lcd_crash_mode_info2()
 {
 	lcd_update_enable(true);
 	static uint32_t tim = 0;
-	if ((tim + 1000) < millis())
+	if ((tim + 1000) < _millis())
 	{
 		fputs_P(_i("\x1b[2JWARNING:\x1b[1;0HCrash detection\x1b[2;0Hdisabled in\x1b[3;0HStealth mode"), lcdout);////MSG_CRASH_DET_STEALTH_FORCE_OFF c=20 r=4
-		tim = millis();
+		tim = _millis();
 	}
     menu_back_if_clicked();
 }
@@ -4106,10 +4106,10 @@ static void lcd_filament_autoload_info()
 uint8_t nlines;
 	lcd_update_enable(true);
 	static uint32_t tim = 0;
-	if ((tim + 1000) < millis())
+	if ((tim + 1000) < _millis())
 	{
           lcd_display_message_fullscreen_nonBlocking_P(_i("Autoloading filament available only when filament sensor is turned on..."), nlines); ////MSG_AUTOLOADING_ONLY_IF_FSENS_ON c=20 r=4
-		tim = millis();
+		tim = _millis();
 	}
     menu_back_if_clicked();
 }
@@ -4119,10 +4119,10 @@ static void lcd_fsensor_fail()
 uint8_t nlines;
 	lcd_update_enable(true);
 	static uint32_t tim = 0;
-	if ((tim + 1000) < millis())
+	if ((tim + 1000) < _millis())
 	{
           lcd_display_message_fullscreen_nonBlocking_P(_i("ERROR: Filament sensor is not responding, please check connection."), nlines);////MSG_FSENS_NOT_RESPONDING c=20 r=4
-		tim = millis();
+		tim = _millis();
 	}
     menu_back_if_clicked();
 }
@@ -4343,20 +4343,20 @@ void lcd_calibrate_pinda() {
 		st_synchronize();
 
 		lcd_display_message_fullscreen_P(msg_e_cal_knob);
-		msg_millis = millis();
+		msg_millis = _millis();
 		while (!LCD_CLICKED) {
-			if (multi_screen && millis() - msg_millis > 5000) {
+			if (multi_screen && _millis() - msg_millis > 5000) {
 				if (msg_next_e_cal_knob == NULL)
 					msg_next_e_cal_knob = msg_e_cal_knob;
 					msg_next_e_cal_knob = lcd_display_message_fullscreen_P(msg_next_e_cal_knob);
-					msg_millis = millis();
+					msg_millis = _millis();
 			}
 
 			//manage_inactivity(true);
 			manage_heater();
 			if (abs(lcd_encoder_diff) >= ENCODER_PULSES_PER_STEP) {						//adjusting mark by knob rotation
 				delay_keep_alive(50);
-				//previous_millis_cmd = millis();
+				//previous_millis_cmd = _millis();
 				lcd_encoder += (lcd_encoder_diff / ENCODER_PULSES_PER_STEP);
 				lcd_encoder_diff = 0;
 				if (!planner_queue_full()) {
@@ -4467,7 +4467,7 @@ void lcd_language()
 	lcd_draw_update = 2;
 	while ((menu_menu != lcd_status_screen) && (!lang_is_selected()))
 	{
-		delay(50);
+		_delay(50);
 		lcd_update(0);
 		manage_heater();
 		manage_inactivity(true);
@@ -5130,7 +5130,7 @@ void bowden_menu() {
 				lcd_print(">");
 
 				enc_dif = lcd_encoder_diff;
-				delay(100);
+				_delay(100);
 		}
 
 		if (lcd_clicked()) {
@@ -5163,7 +5163,7 @@ void bowden_menu() {
 							enc_dif = lcd_encoder_diff;
 						}
 				}
-				delay(100);
+				_delay(100);
 				if (lcd_clicked()) {
 					EEPROM_save_B(EEPROM_BOWDEN_LENGTH + cursor_pos * 2, &bowden_length[cursor_pos]);
 					if (lcd_show_fullscreen_message_yes_no_and_wait_P(PSTR("Continue with another bowden?"))) {
@@ -5222,7 +5222,7 @@ static char snmm_stop_print_menu() { //menu for choosing which filaments will be
 				lcd_set_cursor(0, cursor_pos);
 				lcd_print(">");
 				enc_dif = lcd_encoder_diff;
-				delay(100);
+				_delay(100);
 			}
 		}
 		if (lcd_clicked()) {
@@ -5323,7 +5323,7 @@ uint8_t choose_menu_P(const char *header, const char *item, const char *last_ite
         lcd_set_cursor(0, cursor_pos);
         lcd_print(">");
 
-        delay(100);
+        _delay(100);
 
 		if (lcd_clicked())
 		{
@@ -5405,7 +5405,7 @@ char reset_menu() {
 				lcd_set_cursor(0, cursor_pos);
 				lcd_print(">");
 				enc_dif = lcd_encoder_diff;
-				delay(100);
+				_delay(100);
 			}
 
 		}
@@ -5528,7 +5528,7 @@ void unload_filament()
 	disable_e0();
 	disable_e1();
 	disable_e2();
-	delay(100);
+	_delay(100);
 
 	Sound_MakeSound(e_SOUND_TYPE_StandardPrompt);
 	uint8_t counterBeep = 0;
@@ -5593,11 +5593,11 @@ static void lcd_farm_no()
 
 		lcd_set_cursor(step, 3);
 		lcd_print("^");
-		delay(100);
+		_delay(100);
 
 		if (lcd_clicked())
 		{
-			delay(200);
+			_delay(200);
 			step++;
 			if(step == 3) {
 				_ret = 1;
@@ -5678,7 +5678,7 @@ unsigned char lcd_choose_color() {
 				lcd_set_cursor(0, cursor_pos);
 				lcd_print(">");
 				enc_dif = lcd_encoder_diff;
-				delay(100);
+				_delay(100);
 
 		}
 
@@ -5732,7 +5732,7 @@ void lcd_confirm_print()
 		lcd_puts_P(_T(MSG_NO));
 		lcd_set_cursor(0, 1 + cursor_pos);
 		lcd_print(">");
-		delay(100);
+		_delay(100);
 
 		_t = _t + 1;
 		if (_t>100)
@@ -5750,7 +5750,7 @@ void lcd_confirm_print()
 				no_response = true; //we need confirmation by recieving PRUSA thx
 				important_status = 4;
 				saved_filament_type = filament_type;
-				NcTime = millis();
+				NcTime = _millis();
 			}
 			if (cursor_pos == 2)
 			{
@@ -5760,7 +5760,7 @@ void lcd_confirm_print()
 				no_response = true; //we need confirmation by recieving PRUSA thx
 				important_status = 5;				
 				saved_filament_type = filament_type;
-				NcTime = millis();
+				NcTime = _millis();
 			}
 		}
 
@@ -5793,7 +5793,7 @@ void lcd_resume_print()
     lcd_setstatuspgm(_T(MSG_RESUMING_PRINT));
     lcd_reset_alert_level(); //for fan speed error
     restore_print_from_ram_and_continue(0.0);
-    pause_time += (millis() - start_pause_print); //accumulate time when print is paused for correct statistics calculation
+    pause_time += (_millis() - start_pause_print); //accumulate time when print is paused for correct statistics calculation
     refresh_cmd_timeout();
     isPrintPaused = false;
 }
@@ -5825,7 +5825,7 @@ static void lcd_main_menu()
     
         int tempScrool = 0;
         if (lcd_draw_update == 0 && LCD_CLICKED == 0)
-            //delay(100);
+            //_delay(100);
             return; // nothing to do (so don't thrash the SD card)
         uint16_t fileCnt = card.getnrfilenames();
         
@@ -5988,7 +5988,7 @@ void stack_error() {
 	SET_OUTPUT(BEEPER);
 if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE)||(eSoundMode==e_SOUND_MODE_SILENT))
 	WRITE(BEEPER, HIGH);
-	delay(1000);
+	_delay(1000);
 	WRITE(BEEPER, LOW);
 	lcd_display_message_fullscreen_P(_i("Error - static memory has been overwritten"));////MSG_STACK_ERROR c=20 r=4
 	//err_triggered = 1;
@@ -6192,7 +6192,7 @@ void lcd_print_stop()
 	lcd_setstatuspgm(_T(MSG_PRINT_ABORTED));
 	card.sdprinting = false;
 	card.closefile();
-	stoptime = millis();
+	stoptime = _millis();
 	unsigned long t = (stoptime - starttime - pause_time) / 1000; //time in s
 	pause_time = 0;
 	save_statistics(total_filament_used, t);
@@ -6247,7 +6247,7 @@ void lcd_sdcard_menu()
 	  card.presort();
   }
   if (lcd_draw_update == 0 && LCD_CLICKED == 0)
-    //delay(100);
+    //_delay(100);
     return; // nothing to do (so don't thrash the SD card)
   uint16_t fileCnt = card.getnrfilenames();
 
@@ -6311,7 +6311,7 @@ bool lcd_selftest()
 	#ifdef TMC2130
 	  FORCE_HIGH_POWER_START;
 	#endif // TMC2130
-	delay(2000);
+	_delay(2000);
 	KEEPALIVE_STATE(IN_HANDLER);
 
 	_progress = lcd_selftest_screen(testScreen::extruderFan, _progress, 3, true, 2000);
@@ -6689,7 +6689,7 @@ static bool lcd_selfcheck_axis(int _axis, int _travel)
 		manage_heater();
 		manage_inactivity(true);
 
-		//delay(100);
+		//_delay(100);
 		(_travel_done <= _travel) ? _travel_done++ : _stepdone = true;
 
 	} while (!_stepdone);
@@ -6762,7 +6762,7 @@ static bool lcd_selfcheck_pulleys(int axis)
 			return(false);
 		}
 	}
-	timeout_counter = millis() + 2500;
+	timeout_counter = _millis() + 2500;
 	endstop_triggered = false;
 	manage_inactivity(true);
 	while (!endstop_triggered) {
@@ -6784,7 +6784,7 @@ static bool lcd_selfcheck_pulleys(int axis)
 			current_position[axis] -= 1;
 			plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[3], manual_feedrate[0] / 60, active_extruder);
 			st_synchronize();
-			if (millis() > timeout_counter) {
+			if (_millis() > timeout_counter) {
 				lcd_selftest_error(8, (axis == 0) ? "X" : "Y", "");
 				return(false);
 			}
@@ -6807,7 +6807,7 @@ static bool lcd_selfcheck_endstops()
 		if ((READ(Z_MIN_PIN) ^ Z_MIN_ENDSTOP_INVERTING) == 1) current_position[2] += 10;
 	}
 	plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], manual_feedrate[0] / 60, active_extruder);
-	delay(500);
+	_delay(500);
 
 	if (((READ(X_MIN_PIN) ^ X_MIN_ENDSTOP_INVERTING) == 1) ||
 		((READ(Y_MIN_PIN) ^ Y_MIN_ENDSTOP_INVERTING) == 1) ||
@@ -7002,11 +7002,11 @@ static void lcd_selftest_error(int _error_no, const char *_error_1, const char *
 		break;
 	}
 
-	delay(1000);
+	_delay(1000);
 	lcd_beeper_quick_feedback();
 
 	do {
-		delay(100);
+		_delay(100);
 		manage_heater();
 		manage_inactivity();
 	} while (!lcd_clicked());
@@ -7119,7 +7119,7 @@ static bool lcd_selftest_manual_fan_check(int _fan, bool check_opposite)
 		analogWrite(FAN_PIN, 255);
 		break;
 	}
-	delay(500);
+	_delay(500);
 
 	lcd_set_cursor(1, 2); lcd_puts_P(_T(MSG_SELFTEST_FAN_YES));
 	lcd_set_cursor(0, 3); lcd_print(">");
@@ -7167,7 +7167,7 @@ static bool lcd_selftest_manual_fan_check(int _fan, bool check_opposite)
 
 
 		manage_heater();
-		delay(100);
+		_delay(100);
 
 	} while (!lcd_clicked());
 	KEEPALIVE_STATE(IN_HANDLER);
@@ -7194,7 +7194,7 @@ static bool lcd_selftest_fan_dialog(int _fan)
 		fanSpeed = 0;
 		manage_heater();			//turn off fan
 		setExtruderAutoFanState(EXTRUDER_0_AUTO_FAN_PIN, 1); //extruder fan
-		delay(2000);				//delay_keep_alive would turn off extruder fan, because temerature is too low
+		_delay(2000);				//delay_keep_alive would turn off extruder fan, because temerature is too low
 		manage_heater();			//count average fan speed from 2s delay and turn off fans
 		if (!fan_speed[0]) _result = false;
 		//SERIAL_ECHOPGM("Extruder fan speed: ");
@@ -7471,10 +7471,10 @@ void lcd_printer_connected() {
 }
 
 static void lcd_send_status() {
-	if (farm_mode && no_response && ((millis() - NcTime) > (NC_TIME * 1000))) {
+	if (farm_mode && no_response && ((_millis() - NcTime) > (NC_TIME * 1000))) {
 		//send important status messages periodicaly
 		prusa_statistics(important_status, saved_filament_type);
-		NcTime = millis();
+		NcTime = _millis();
 #ifdef FARM_CONNECT_MESSAGE
 		lcd_connect_printer();
 #endif //FARM_CONNECT_MESSAGE
@@ -7519,7 +7519,7 @@ static void lcd_connect_printer() {
 void lcd_ping() { //chceck if printer is connected to monitoring when in farm mode
 	if (farm_mode) {
 		bool empty = is_buffer_empty();
-		if ((millis() - PingTime) * 0.001 > (empty ? PING_TIME : PING_TIME_LONG)) { //if commands buffer is empty use shorter time period
+		if ((_millis() - PingTime) * 0.001 > (empty ? PING_TIME : PING_TIME_LONG)) { //if commands buffer is empty use shorter time period
 																							  //if there are comamnds in buffer, some long gcodes can delay execution of ping command
 																							  //therefore longer period is used
 			printer_connected = false;
@@ -7634,7 +7634,7 @@ void menu_lcd_lcdupdate_func(void)
 		}
 	}
 #endif//CARDINSERTED
-	if (lcd_next_update_millis < millis())
+	if (lcd_next_update_millis < _millis())
 	{
 		if (abs(lcd_encoder_diff) >= ENCODER_PULSES_PER_STEP)
 		{
@@ -7666,7 +7666,7 @@ void menu_lcd_lcdupdate_func(void)
 		}
 		if (lcd_draw_update == 2) lcd_clear();
 		if (lcd_draw_update) lcd_draw_update--;
-		lcd_next_update_millis = millis() + LCD_UPDATE_INTERVAL;
+		lcd_next_update_millis = _millis() + LCD_UPDATE_INTERVAL;
 	}
 	if (!SdFatUtil::test_stack_integrity()) stack_error();
 	lcd_ping(); //check that we have received ping command if we are in farm mode

+ 2 - 2
Firmware/xyzcal.cpp

@@ -152,9 +152,9 @@ bool xyzcal_lineXYZ_to(int16_t x, int16_t y, int16_t z, uint16_t delay_us, int8_
 	sm4_set_dir_bits(xyzcal_dm);
 	sm4_stop_cb = check_pinda?((check_pinda<0)?check_pinda_0:check_pinda_1):0;
 	xyzcal_sm4_delay = delay_us;
-//	uint32_t u = micros();
+//	uint32_t u = _micros();
 	bool ret = sm4_line_xyze_ui(abs(x), abs(y), abs(z), 0)?true:false;
-//	u = micros() - u;
+//	u = _micros() - u;
 	return ret;
 }
 

+ 5 - 0
Tests/Timer_test.cpp

@@ -15,6 +15,11 @@ unsigned long millis()
     return now;
 }
 
+unsigned long millis2()
+{
+    return now;
+}
+
 static void basicTimer()
 {
     LongTimer timer;