-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Marlin_main.cpp
7062 lines (6165 loc) · 235 KB
/
Marlin_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- c++ -*- */
/**
* @file
*/
/*
This firmware is a mashup between Sprinter and grbl.
(https://github.com/kliment/Sprinter)
(https://github.com/simen/grbl/tree)
It has preliminary support for Matthew Roberts advance algorithm
http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
*/
#include "Marlin.h"
#ifdef ENABLE_AUTO_BED_LEVELING
#include "vector_3.h"
#ifdef AUTO_BED_LEVELING_GRID
#include "qr_solve.h"
#endif
#endif // ENABLE_AUTO_BED_LEVELING
#ifdef MESH_BED_LEVELING
#include "mesh_bed_leveling.h"
#include "mesh_bed_calibration.h"
#endif
#include "ultralcd.h"
#include "Configuration_prusa.h"
#include "planner.h"
#include "stepper.h"
#include "temperature.h"
#include "motion_control.h"
#include "cardreader.h"
#include "watchdog.h"
#include "ConfigurationStore.h"
#include "language.h"
#include "pins_arduino.h"
#include "math.h"
#include "util.h"
#include <avr/wdt.h>
#ifdef BLINKM
#include "BlinkM.h"
#include "Wire.h"
#endif
#ifdef ULTRALCD
#include "ultralcd.h"
#endif
#if NUM_SERVOS > 0
#include "Servo.h"
#endif
#if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1
#include <SPI.h>
#endif
#define VERSION_STRING "1.0.2"
#include "ultralcd.h"
#include "sound.h"
// Macros for bit masks
#define BIT(b) (1<<(b))
#define TEST(n,b) (((n)&BIT(b))!=0)
#define SET_BIT(n,b,value) (n) ^= ((-value)^(n)) & (BIT(b))
// look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html
// http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
//Implemented Codes
//-------------------
// PRUSA CODES
// P F - Returns FW versions
// P R - Returns revision of printer
// G0 -> G1
// G1 - Coordinated Movement X Y Z E
// G2 - CW ARC
// G3 - CCW ARC
// G4 - Dwell S<seconds> or P<milliseconds>
// G10 - retract filament according to settings of M207
// G11 - retract recover filament according to settings of M208
// G28 - Home all Axis
// G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
// G30 - Single Z Probe, probes bed at current XY location.
// G31 - Dock sled (Z_PROBE_SLED only)
// G32 - Undock sled (Z_PROBE_SLED only)
// G80 - Automatic mesh bed leveling
// G81 - Print bed profile
// G90 - Use Absolute Coordinates
// G91 - Use Relative Coordinates
// G92 - Set current position to coordinates given
// M Codes
// M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
// M1 - Same as M0
// M17 - Enable/Power all stepper motors
// M18 - Disable all stepper motors; same as M84
// M20 - List SD card
// M21 - Init SD card
// M22 - Release SD card
// M23 - Select SD file (M23 filename.g)
// M24 - Start/resume SD print
// M25 - Pause SD print
// M26 - Set SD position in bytes (M26 S12345)
// M27 - Report SD print status
// M28 - Start SD write (M28 filename.g)
// M29 - Stop SD write
// M30 - Delete file from SD (M30 filename.g)
// M31 - Output time since last M109 or SD card start to serial
// M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
// syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
// Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
// The '#' is necessary when calling from within sd files, as it stops buffer prereading
// M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
// M73 - Show percent done and print time remaining
// 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
// M84 - Disable steppers until next move,
// or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
// M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
// M92 - Set axis_steps_per_unit - same syntax as G92
// M104 - Set extruder target temp
// M105 - Read current temp
// M106 - Fan on
// M107 - Fan off
// M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
// Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
// IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
// M112 - Emergency stop
// M113 - Get or set the timeout interval for Host Keepalive "busy" messages
// M114 - Output current position to serial port
// M115 - Capabilities string
// M117 - display message
// M119 - Output Endstop status to serial port
// M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
// M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
// M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
// M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
// M140 - Set bed target temp
// M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
// M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
// Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
// M200 D<millimeters>- set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).
// 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) Unused in Marlin!!
// M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec
// M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) in mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
// M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk
// M206 - set additional homing offset
// M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting
// M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec]
// M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
// M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y>
// M220 S<factor in percent>- set speed factor override percentage
// M221 S<factor in percent>- set extrude factor override percentage
// M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
// M240 - Trigger a camera to take a photograph
// M250 - Set LCD contrast C<contrast value> (value 0..63)
// M280 - set servo position absolute. P: servo index, S: angle or microseconds
// M300 - Play beep sound S<frequency Hz> P<duration ms>
// M301 - Set PID parameters P I and D
// M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
// M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
// M304 - Set bed PID parameters P I and D
// M400 - Finish all moves
// M401 - Lower z-probe if present
// M402 - Raise z-probe if present
// M404 - N<dia in mm> Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters
// M405 - Turn on Filament Sensor extrusion control. Optional D<delay in cm> to set delay in centimeters between sensor and extruder
// M406 - Turn off Filament Sensor extrusion control
// M407 - Displays measured filament diameter
// M500 - stores parameters in EEPROM
// M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily).
// M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
// M503 - print the current settings (from memory not from EEPROM)
// M509 - force language selection on next restart
// M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
// M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
// M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
// M900 - Set LIN_ADVANCE options, if enabled. See Configuration_adv.h for details.
// M907 - Set digital trimpot motor current using axis codes.
// M908 - Control digital trimpot directly.
// M350 - Set microstepping mode.
// M351 - Toggle MS1 MS2 pins directly.
// M928 - Start SD logging (M928 filename.g) - ended by M29
// M999 - Restart after being stopped by error
//Stepper Movement Variables
//===========================================================================
//=============================imported variables============================
//===========================================================================
//===========================================================================
//=============================public variables=============================
//===========================================================================
#ifdef SDSUPPORT
CardReader card;
#endif
unsigned long TimeSent = millis();
unsigned long TimeNow = millis();
unsigned long PingTime = millis();
unsigned long NcTime;
union Data
{
byte b[2];
int value;
};
float homing_feedrate[] = HOMING_FEEDRATE;
// Currently only the extruder axis may be switched to a relative mode.
// Other axes are always absolute or relative based on the common relative_mode flag.
bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
int feedmultiply=100; //100->1 200->2
int saved_feedmultiply;
int extrudemultiply=100; //100->1 200->2
int extruder_multiply[EXTRUDERS] = {100
#if EXTRUDERS > 1
, 100
#if EXTRUDERS > 2
, 100
#endif
#endif
};
int bowden_length[4];
bool is_usb_printing = false;
bool homing_flag = false;
bool temp_cal_active = false;
unsigned long kicktime = millis()+100000;
unsigned int usb_printing_counter;
int lcd_change_fil_state = 0;
int feedmultiplyBckp = 100;
float HotendTempBckp = 0;
int fanSpeedBckp = 0;
float pause_lastpos[4];
unsigned long pause_time = 0;
unsigned long start_pause_print = millis();
unsigned long load_filament_time;
bool mesh_bed_leveling_flag = false;
bool mesh_bed_run_from_menu = false;
unsigned char lang_selected = 0;
bool prusa_sd_card_upload = false;
unsigned int status_number = 0;
unsigned long total_filament_used;
unsigned int heating_status;
unsigned int heating_status_counter;
bool custom_message;
bool loading_flag = false;
unsigned int custom_message_type;
unsigned int custom_message_state;
char snmm_filaments_used = 0;
uint8_t selectedSerialPort;
float distance_from_min[3];
bool sortAlpha = false;
bool volumetric_enabled = false;
float filament_size[EXTRUDERS] = { DEFAULT_NOMINAL_FILAMENT_DIA
#if EXTRUDERS > 1
, DEFAULT_NOMINAL_FILAMENT_DIA
#if EXTRUDERS > 2
, DEFAULT_NOMINAL_FILAMENT_DIA
#endif
#endif
};
float volumetric_multiplier[EXTRUDERS] = {1.0
#if EXTRUDERS > 1
, 1.0
#if EXTRUDERS > 2
, 1.0
#endif
#endif
};
float current_position[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0 };
float add_homing[3]={0,0,0};
float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
bool axis_known_position[3] = {false, false, false};
float zprobe_zoffset;
// Extruder offset
#if EXTRUDERS > 1
#define NUM_EXTRUDER_OFFSETS 2 // only in XY plane
float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = {
#if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y)
EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y
#endif
};
#endif
uint8_t active_extruder = 0;
int fanSpeed=0;
#ifdef FWRETRACT
bool autoretract_enabled=false;
bool retracted[EXTRUDERS]={false
#if EXTRUDERS > 1
, false
#if EXTRUDERS > 2
, false
#endif
#endif
};
bool retracted_swap[EXTRUDERS]={false
#if EXTRUDERS > 1
, false
#if EXTRUDERS > 2
, false
#endif
#endif
};
float retract_length = RETRACT_LENGTH;
float retract_length_swap = RETRACT_LENGTH_SWAP;
float retract_feedrate = RETRACT_FEEDRATE;
float retract_zlift = RETRACT_ZLIFT;
float retract_recover_length = RETRACT_RECOVER_LENGTH;
float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
#endif
#ifdef ULTIPANEL
#ifdef PS_DEFAULT_OFF
bool powersupply = false;
#else
bool powersupply = true;
#endif
#endif
bool cancel_heatup = false ;
#ifdef HOST_KEEPALIVE_FEATURE
MarlinBusyState busy_state = NOT_BUSY;
static long prev_busy_signal_ms = -1;
uint8_t host_keepalive_interval = HOST_KEEPALIVE_INTERVAL;
#else
#define host_keepalive();
#define KEEPALIVE_STATE(n);
#endif
#ifdef FILAMENT_SENSOR
//Variables for Filament Sensor input
float filament_width_nominal=DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
bool filament_sensor=false; //M405 turns on filament_sensor control, M406 turns it off
float filament_width_meas=DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100
int delay_index1=0; //index into ring buffer
int delay_index2=-1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
float delay_dist=0; //delay distance counter
int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
#endif
const char errormagic[] PROGMEM = "Error:";
const char echomagic[] PROGMEM = "echo:";
bool no_response = false;
uint8_t important_status;
uint8_t saved_filament_type;
// storing estimated time to end of print counted by slicer
uint8_t print_percent_done_normal = PRINT_PERCENT_DONE_INIT;
uint16_t print_time_remaining_normal = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
uint8_t print_percent_done_silent = PRINT_PERCENT_DONE_INIT;
uint16_t print_time_remaining_silent = PRINT_TIME_REMAINING_INIT; //estimated remaining print time in minutes
//===========================================================================
//=============================Private Variables=============================
//===========================================================================
const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
float destination[NUM_AXIS] = { 0.0, 0.0, 0.0, 0.0};
// For tracing an arc
static float offset[3] = {0.0, 0.0, 0.0};
static bool home_all_axis = true;
static float feedrate = 1500.0, next_feedrate, saved_feedrate;
static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
// Determines Absolute or Relative Coordinates.
// Also there is bool axis_relative_modes[] per axis flag.
static bool relative_mode = false;
// String circular buffer. Commands may be pushed to the buffer from both sides:
// Chained commands will be pushed to the front, interactive (from LCD menu)
// and printing commands (from serial line or from SD card) are pushed to the tail.
// First character of each entry indicates the type of the entry:
#define CMDBUFFER_CURRENT_TYPE_UNKNOWN 0
// Command in cmdbuffer was sent over USB.
#define CMDBUFFER_CURRENT_TYPE_USB 1
// Command in cmdbuffer was read from SDCARD.
#define CMDBUFFER_CURRENT_TYPE_SDCARD 2
// Command in cmdbuffer was generated by the UI.
#define CMDBUFFER_CURRENT_TYPE_UI 3
// Command in cmdbuffer was generated by another G-code.
#define CMDBUFFER_CURRENT_TYPE_CHAINED 4
// How much space to reserve for the chained commands
// of type CMDBUFFER_CURRENT_TYPE_CHAINED,
// which are pushed to the front of the queue?
// Maximum 5 commands of max length 20 + null terminator.
#define CMDBUFFER_RESERVE_FRONT (5*21)
// Reserve BUFSIZE lines of length MAX_CMD_SIZE plus CMDBUFFER_RESERVE_FRONT.
static char cmdbuffer[BUFSIZE * (MAX_CMD_SIZE + 1) + CMDBUFFER_RESERVE_FRONT];
// Head of the circular buffer, where to read.
static int bufindr = 0;
// Tail of the buffer, where to write.
static int bufindw = 0;
// Number of lines in cmdbuffer.
static int buflen = 0;
// Flag for processing the current command inside the main Arduino loop().
// If a new command was pushed to the front of a command buffer while
// processing another command, this replaces the command on the top.
// Therefore don't remove the command from the queue in the loop() function.
static bool cmdbuffer_front_already_processed = false;
// Type of a command, which is to be executed right now.
#define CMDBUFFER_CURRENT_TYPE (cmdbuffer[bufindr])
// String of a command, which is to be executed right now.
#define CMDBUFFER_CURRENT_STRING (cmdbuffer+bufindr+1)
// Enable debugging of the command buffer.
// Debugging information will be sent to serial line.
// #define CMDBUFFER_DEBUG
static int serial_count = 0; //index of character read from serial line
static boolean comment_mode = false;
static char *strchr_pointer; // just a pointer to find chars in the command string like X, Y, Z, E, etc
const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42
//static float tt = 0;
//static float bt = 0;
//Inactivity shutdown variables
static unsigned long previous_millis_cmd = 0;
unsigned long max_inactive_time = 0;
static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME*1000l;
unsigned long starttime=0;
unsigned long stoptime=0;
unsigned long _usb_timer = 0;
static uint8_t tmp_extruder;
bool Stopped=false;
#if NUM_SERVOS > 0
Servo servos[NUM_SERVOS];
#endif
bool CooldownNoWait = true;
bool target_direction;
//Insert variables if CHDK is defined
#ifdef CHDK
unsigned long chdkHigh = 0;
boolean chdkActive = false;
#endif
static int saved_feedmultiply_mm = 100;
//===========================================================================
//=============================Routines======================================
//===========================================================================
static void print_time_remaining_init();
void get_arc_coordinates();
bool setTargetedHotend(int code);
void serial_echopair_P(const char *s_P, float v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
void serial_echopair_P(const char *s_P, double v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
void serial_echopair_P(const char *s_P, unsigned long v)
{ serialprintPGM(s_P); SERIAL_ECHO(v); }
#ifdef SDSUPPORT
#include "SdFatUtil.h"
int freeMemory() { return SdFatUtil::FreeRam(); }
#else
extern "C" {
extern unsigned int __bss_end;
extern unsigned int __heap_start;
extern void *__brkval;
int freeMemory() {
int free_memory;
if ((int)__brkval == 0)
free_memory = ((int)&free_memory) - ((int)&__bss_end);
else
free_memory = ((int)&free_memory) - ((int)__brkval);
return free_memory;
}
}
#endif //!SDSUPPORT
// Pop the currently processed command from the queue.
// It is expected, that there is at least one command in the queue.
bool cmdqueue_pop_front()
{
if (buflen > 0) {
#ifdef CMDBUFFER_DEBUG
SERIAL_ECHOPGM("Dequeing ");
SERIAL_ECHO(cmdbuffer+bufindr+1);
SERIAL_ECHOLNPGM("");
SERIAL_ECHOPGM("Old indices: buflen ");
SERIAL_ECHO(buflen);
SERIAL_ECHOPGM(", bufindr ");
SERIAL_ECHO(bufindr);
SERIAL_ECHOPGM(", bufindw ");
SERIAL_ECHO(bufindw);
SERIAL_ECHOPGM(", serial_count ");
SERIAL_ECHO(serial_count);
SERIAL_ECHOPGM(", bufsize ");
SERIAL_ECHO(sizeof(cmdbuffer));
SERIAL_ECHOLNPGM("");
#endif /* CMDBUFFER_DEBUG */
if (-- buflen == 0) {
// Empty buffer.
if (serial_count == 0)
// No serial communication is pending. Reset both pointers to zero.
bufindw = 0;
bufindr = bufindw;
} else {
// There is at least one ready line in the buffer.
// First skip the current command ID and iterate up to the end of the string.
for (++ bufindr; cmdbuffer[bufindr] != 0; ++ bufindr) ;
// Second, skip the end of string null character and iterate until a nonzero command ID is found.
for (++ bufindr; (bufindr < (int)sizeof(cmdbuffer)) && (cmdbuffer[bufindr] == 0); ++ bufindr) ;
// If the end of the buffer was empty,
if (bufindr == sizeof(cmdbuffer)) {
// skip to the start and find the nonzero command.
for (bufindr = 0; cmdbuffer[bufindr] == 0; ++ bufindr) ;
}
#ifdef CMDBUFFER_DEBUG
SERIAL_ECHOPGM("New indices: buflen ");
SERIAL_ECHO(buflen);
SERIAL_ECHOPGM(", bufindr ");
SERIAL_ECHO(bufindr);
SERIAL_ECHOPGM(", bufindw ");
SERIAL_ECHO(bufindw);
SERIAL_ECHOPGM(", serial_count ");
SERIAL_ECHO(serial_count);
SERIAL_ECHOPGM(" new command on the top: ");
SERIAL_ECHO(cmdbuffer+bufindr+1);
SERIAL_ECHOLNPGM("");
#endif /* CMDBUFFER_DEBUG */
}
return true;
}
return false;
}
void cmdqueue_reset()
{
while (cmdqueue_pop_front()) ;
}
// How long a string could be pushed to the front of the command queue?
// If yes, adjust bufindr to the new position, where the new command could be enqued.
// len_asked does not contain the zero terminator size.
bool cmdqueue_could_enqueue_front(int len_asked)
{
// MAX_CMD_SIZE has to accommodate the zero terminator.
if (len_asked >= MAX_CMD_SIZE)
return false;
// Remove the currently processed command from the queue.
if (! cmdbuffer_front_already_processed) {
cmdqueue_pop_front();
cmdbuffer_front_already_processed = true;
}
if (bufindr == bufindw && buflen > 0)
// Full buffer.
return false;
// Adjust the end of the write buffer based on whether a partial line is in the receive buffer.
int endw = (serial_count > 0) ? (bufindw + MAX_CMD_SIZE + 1) : bufindw;
if (bufindw < bufindr) {
int bufindr_new = bufindr - len_asked - 2;
// Simple case. There is a contiguous space between the write buffer and the read buffer.
if (endw <= bufindr_new) {
bufindr = bufindr_new;
return true;
}
} else {
// Otherwise the free space is split between the start and end.
if (len_asked + 2 <= bufindr) {
// Could fit at the start.
bufindr -= len_asked + 2;
return true;
}
int bufindr_new = sizeof(cmdbuffer) - len_asked - 2;
if (endw <= bufindr_new) {
memset(cmdbuffer, 0, bufindr);
bufindr = bufindr_new;
return true;
}
}
return false;
}
// Could one enqueue a command of lenthg len_asked into the buffer,
// while leaving CMDBUFFER_RESERVE_FRONT at the start?
// If yes, adjust bufindw to the new position, where the new command could be enqued.
// len_asked does not contain the zero terminator size.
bool cmdqueue_could_enqueue_back(int len_asked)
{
// MAX_CMD_SIZE has to accommodate the zero terminator.
if (len_asked >= MAX_CMD_SIZE)
return false;
if (bufindr == bufindw && buflen > 0)
// Full buffer.
return false;
if (serial_count > 0) {
// If there is some data stored starting at bufindw, len_asked is certainly smaller than
// the allocated data buffer. Try to reserve a new buffer and to move the already received
// serial data.
// How much memory to reserve for the commands pushed to the front?
// End of the queue, when pushing to the end.
int endw = bufindw + len_asked + 2;
if (bufindw < bufindr)
// Simple case. There is a contiguous space between the write buffer and the read buffer.
return ((endw + CMDBUFFER_RESERVE_FRONT) <= bufindr);
// Otherwise the free space is split between the start and end.
if (// Could one fit to the end, including the reserve?
(endw + CMDBUFFER_RESERVE_FRONT <= (int)sizeof(cmdbuffer)) ||
// Could one fit to the end, and the reserve to the start?
((endw <= (int)sizeof(cmdbuffer)) && (CMDBUFFER_RESERVE_FRONT <= bufindr)))
return true;
// Could one fit both to the start?
if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
// Mark the rest of the buffer as used.
memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
// and point to the start.
bufindw = 0;
return true;
}
} else {
// How much memory to reserve for the commands pushed to the front?
// End of the queue, when pushing to the end.
int endw = bufindw + len_asked + 2;
if (bufindw < bufindr)
// Simple case. There is a contiguous space between the write buffer and the read buffer.
return ((endw + CMDBUFFER_RESERVE_FRONT) <= bufindr);
// Otherwise the free space is split between the start and end.
if (// Could one fit to the end, including the reserve?
(endw + CMDBUFFER_RESERVE_FRONT <= (int)sizeof(cmdbuffer)) ||
// Could one fit to the end, and the reserve to the start?
((endw <= (int)sizeof(cmdbuffer)) && (CMDBUFFER_RESERVE_FRONT <= bufindr)))
return true;
// Could one fit both to the start?
if (len_asked + 2 + CMDBUFFER_RESERVE_FRONT <= bufindr) {
// Mark the rest of the buffer as used.
memset(cmdbuffer+bufindw, 0, sizeof(cmdbuffer)-bufindw);
// and point to the start.
bufindw = 0;
return true;
}
}
return false;
}
#ifdef CMDBUFFER_DEBUG
static void cmdqueue_dump_to_serial_single_line(int nr, const char *p)
{
SERIAL_ECHOPGM("Entry nr: ");
SERIAL_ECHO(nr);
SERIAL_ECHOPGM(", type: ");
SERIAL_ECHO(int(*p));
SERIAL_ECHOPGM(", cmd: ");
SERIAL_ECHO(p+1);
SERIAL_ECHOLNPGM("");
}
static void cmdqueue_dump_to_serial()
{
if (buflen == 0) {
SERIAL_ECHOLNPGM("The command buffer is empty.");
} else {
SERIAL_ECHOPGM("Content of the buffer: entries ");
SERIAL_ECHO(buflen);
SERIAL_ECHOPGM(", indr ");
SERIAL_ECHO(bufindr);
SERIAL_ECHOPGM(", indw ");
SERIAL_ECHO(bufindw);
SERIAL_ECHOLNPGM("");
int nr = 0;
if (bufindr < bufindw) {
for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + bufindw; ++ nr) {
cmdqueue_dump_to_serial_single_line(nr, p);
// Skip the command.
for (++p; *p != 0; ++ p);
// Skip the gaps.
for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
}
} else {
for (const char *p = cmdbuffer + bufindr; p < cmdbuffer + sizeof(cmdbuffer); ++ nr) {
cmdqueue_dump_to_serial_single_line(nr, p);
// Skip the command.
for (++p; *p != 0; ++ p);
// Skip the gaps.
for (++p; p < cmdbuffer + sizeof(cmdbuffer) && *p == 0; ++ p);
}
for (const char *p = cmdbuffer; p < cmdbuffer + bufindw; ++ nr) {
cmdqueue_dump_to_serial_single_line(nr, p);
// Skip the command.
for (++p; *p != 0; ++ p);
// Skip the gaps.
for (++p; p < cmdbuffer + bufindw && *p == 0; ++ p);
}
}
SERIAL_ECHOLNPGM("End of the buffer.");
}
}
#endif /* CMDBUFFER_DEBUG */
//adds an command to the main command buffer
//thats really done in a non-safe way.
//needs overworking someday
// Currently the maximum length of a command piped through this function is around 20 characters
void enquecommand(const char *cmd, bool from_progmem)
{
int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
// Does cmd fit the queue while leaving sufficient space at the front for the chained commands?
// If it fits, it may move bufindw, so it points to a contiguous buffer, which fits cmd.
if (cmdqueue_could_enqueue_back(len)) {
// This is dangerous if a mixing of serial and this happens
// This may easily be tested: If serial_count > 0, we have a problem.
cmdbuffer[bufindw] = CMDBUFFER_CURRENT_TYPE_UI;
if (from_progmem)
strcpy_P(cmdbuffer + bufindw + 1, cmd);
else
strcpy(cmdbuffer + bufindw + 1, cmd);
if (!farm_mode) {
SERIAL_ECHO_START;
SERIAL_ECHORPGM(MSG_Enqueing);
SERIAL_ECHO(cmdbuffer + bufindw + 1);
SERIAL_ECHOLNPGM("\"");
}
bufindw += len + 2;
if (bufindw == sizeof(cmdbuffer))
bufindw = 0;
++ buflen;
#ifdef CMDBUFFER_DEBUG
cmdqueue_dump_to_serial();
#endif /* CMDBUFFER_DEBUG */
} else {
SERIAL_ERROR_START;
SERIAL_ECHORPGM(MSG_Enqueing);
if (from_progmem)
SERIAL_PROTOCOLRPGM(cmd);
else
SERIAL_ECHO(cmd);
SERIAL_ECHOLNPGM("\" failed: Buffer full!");
#ifdef CMDBUFFER_DEBUG
cmdqueue_dump_to_serial();
#endif /* CMDBUFFER_DEBUG */
}
}
bool cmd_buffer_empty()
{
return (buflen == 0);
}
void enquecommand_front(const char *cmd, bool from_progmem)
{
int len = from_progmem ? strlen_P(cmd) : strlen(cmd);
// Does cmd fit the queue? This call shall move bufindr, so the command may be copied.
if (cmdqueue_could_enqueue_front(len)) {
cmdbuffer[bufindr] = CMDBUFFER_CURRENT_TYPE_UI;
if (from_progmem)
strcpy_P(cmdbuffer + bufindr + 1, cmd);
else
strcpy(cmdbuffer + bufindr + 1, cmd);
++ buflen;
if (!farm_mode) {
SERIAL_ECHO_START;
SERIAL_ECHOPGM("Enqueing to the front: \"");
SERIAL_ECHO(cmdbuffer + bufindr + 1);
SERIAL_ECHOLNPGM("\"");
}
#ifdef CMDBUFFER_DEBUG
cmdqueue_dump_to_serial();
#endif /* CMDBUFFER_DEBUG */
} else {
SERIAL_ERROR_START;
SERIAL_ECHOPGM("Enqueing to the front: \"");
if (from_progmem)
SERIAL_PROTOCOLRPGM(cmd);
else
SERIAL_ECHO(cmd);
SERIAL_ECHOLNPGM("\" failed: Buffer full!");
#ifdef CMDBUFFER_DEBUG
cmdqueue_dump_to_serial();
#endif /* CMDBUFFER_DEBUG */
}
}
// Mark the command at the top of the command queue as new.
// Therefore it will not be removed from the queue.
void repeatcommand_front()
{
cmdbuffer_front_already_processed = true;
}
bool is_buffer_empty()
{
if (buflen == 0) return true;
else return false;
}
void setup_killpin()
{
#if defined(KILL_PIN) && KILL_PIN > -1
SET_INPUT(KILL_PIN);
WRITE(KILL_PIN,HIGH);
#endif
}
// Set home pin
void setup_homepin(void)
{
#if defined(HOME_PIN) && HOME_PIN > -1
SET_INPUT(HOME_PIN);
WRITE(HOME_PIN,HIGH);
#endif
}
void setup_photpin()
{
#if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1
SET_OUTPUT(PHOTOGRAPH_PIN);
WRITE(PHOTOGRAPH_PIN, LOW);
#endif
}
void setup_powerhold()
{
#if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
SET_OUTPUT(SUICIDE_PIN);
WRITE(SUICIDE_PIN, HIGH);
#endif
#if defined(PS_ON_PIN) && PS_ON_PIN > -1
SET_OUTPUT(PS_ON_PIN);
#if defined(PS_DEFAULT_OFF)
WRITE(PS_ON_PIN, PS_ON_ASLEEP);
#else
WRITE(PS_ON_PIN, PS_ON_AWAKE);
#endif
#endif
}
void suicide()
{
#if defined(SUICIDE_PIN) && SUICIDE_PIN > -1
SET_OUTPUT(SUICIDE_PIN);
WRITE(SUICIDE_PIN, LOW);
#endif
}
void servo_init()
{
#if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1)
servos[0].attach(SERVO0_PIN);
#endif
#if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1)
servos[1].attach(SERVO1_PIN);
#endif
#if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1)
servos[2].attach(SERVO2_PIN);
#endif
#if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1)
servos[3].attach(SERVO3_PIN);
#endif
#if (NUM_SERVOS >= 5)
#error "TODO: enter initalisation code for more servos"
#endif
}
#ifdef MESH_BED_LEVELING
enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet };
#endif
// Factory reset function
// This function is used to erase parts or whole EEPROM memory which is used for storing calibration and and so on.
// Level input parameter sets depth of reset
// Quiet parameter masks all waitings for user interact.
int er_progress = 0;
void factory_reset(char level, bool quiet)
{
lcd_implementation_clear();
switch (level) {
// Level 0: Language reset
case 0:
if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
WRITE(BEEPER, HIGH);
_delay_ms(100);
WRITE(BEEPER, LOW);
lcd_force_language_selection();
break;
//Level 1: Reset statistics
case 1:
if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
WRITE(BEEPER, HIGH);
_delay_ms(100);
WRITE(BEEPER, LOW);
eeprom_update_dword((uint32_t *)EEPROM_TOTALTIME, 0);
eeprom_update_dword((uint32_t *)EEPROM_FILAMENTUSED, 0);
lcd_menu_statistics();
break;
// Level 2: Prepare for shipping
case 2:
//lcd_printPGM(PSTR("Factory RESET"));
//lcd_print_at_PGM(1,2,PSTR("Shipping prep"));
// Force language selection at the next boot up.
lcd_force_language_selection();
// Force the "Follow calibration flow" message at the next boot up.
calibration_status_store(CALIBRATION_STATUS_Z_CALIBRATION);
farm_no = 0;
farm_mode = 0;
eeprom_update_byte((uint8_t*)EEPROM_FARM_MODE, farm_mode);
EEPROM_save_B(EEPROM_FARM_NUMBER, &farm_no);
if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
WRITE(BEEPER, HIGH);
_delay_ms(100);
WRITE(BEEPER, LOW);
//_delay_ms(2000);
break;
// Level 3: erase everything, whole EEPROM will be set to 0xFF
case 3:
lcd_printPGM(PSTR("Factory RESET"));
lcd_print_at_PGM(1, 2, PSTR("ERASING all data"));
if((eSoundMode==e_SOUND_MODE_LOUD)||(eSoundMode==e_SOUND_MODE_ONCE))
WRITE(BEEPER, HIGH);
_delay_ms(100);
WRITE(BEEPER, LOW);
er_progress = 0;
lcd_print_at_PGM(3, 3, PSTR(" "));
lcd_implementation_print_at(3, 3, er_progress);
// Erase EEPROM
for (int i = 0; i < 4096; i++) {
eeprom_write_byte((uint8_t*)i, 0xFF);
if (i % 41 == 0) {
er_progress++;
lcd_print_at_PGM(3, 3, PSTR(" "));
lcd_implementation_print_at(3, 3, er_progress);
lcd_printPGM(PSTR("%"));
}