forked from jinschoi/SphereBot
-
Notifications
You must be signed in to change notification settings - Fork 3
/
SphereBot.ino
1783 lines (1499 loc) · 61 KB
/
SphereBot.ino
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
/*
Copyright 2011 by Eberhard Rensch <http://pleasantsoftware.com/developer/3d>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
Part of this code is based on/inspired by the Helium Frog Delta Robot Firmware
by Martin Price <http://www.HeliumFrog.com>
2015-2016 the code was modified to run on an Adafruit Motor Shield V2
by Jin Choi <jsc@alum.mit.edu>.
2016 code support for the Adafruit Motor Shield V1 was added by GrAndAG.
3/2021 the code was modified with the following improvements
by Terence Golla (tgolla).
- Corrected the naming convention mix of snake_case and camelCase for more
prominent C/C++ Arduino software use of camelCase.
- Restructured the ino software file to follow Arduino styling...
- Begin with a set of comments clearly describing the purpose and
assumptions of the code.
- Import any required library headers.
- Define constants.
- Define global variables.
- Define setup() and loop().
- Define subroutines (functions).
- Expanded in code documentation (comments).
- Modified code to operate servo installed in reverse.
- A true to G-Code specification parser was added. The class was developed using
Visual Studio Community (https://visualstudio.microsoft.com/vs/community/)
and the Microsoft Unit Testing Framework for C++
(https://docs.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2019).
- Added the following new M-Codes to allow for increased flexibility
controlling the pen servo.
M17 - Enable all stepper motors.
M304 - Sets the pen down position needed for new MZ mode.
M305 - Sets the G-Code responsible for operating the pen servo.
P0 - M300 sets the pen height. P1 - G0, G1, G2 & G3 Z parameter
is responsible for setting the pen height. P2 - Automatically
detects which code is responsible for setting the pen height.
M306 - Sets the M300 height adjustment. P0 - Off, P1 - Preset, P2 - Calculated
M307 - Sets the Z height adjustment. P0 - Off, P1 - Preset, P2 - Calculated
M308 - Sets the M300 pen up preset value. S values less than the value
move the pen down.
M309 - Sets the Z pen up preset value. Z values less than the value
move the pen down.
M310 - Sets the XY feedrate preset value. If zero feedrate is initalized with
default value and set through G0, G1, G2 & G3 codes with X or Y values
by Fxxx.
M311 - Sets the pen feedrate preset value. If zero feedrate is initalized with
default value and set through the M300 Fxxx or G0, G1, G2 & G3 codes
with only Z values by Fxxx.
M312 - Sets the pen up feedrate multiplier. One means the pen will go up at the
same speed (degrees/second) as it goes down. Each increase by one will
logarithmically double the pen up speed.
M990 - Sets the g-code output device.
P0 - Neither, P1 - Serial Only, P2 - Display Only, P3 - Both
This command is only relavant for with the touchscreen/SD configuration.
M991 - Disable/Enable percentage completed and time remaining calculation.
P0 - Disabled, P1 - Enabled
This command is only relavant for with the touchscreen/SD configuration.
M999 - Display Mxxx command values. Note: To add define the M999 directive
true in configuration.h. This directive was add as a safety measure for
development as the code is memory intensive with respect to both sketch
(program storage) and global variables (dynamic memory) especially on
the Arduino Uno.
- Added the ability to set the pen feedrate with the M300 Fxxx or G0, G1, G2 & G3
codes with only Z values by Fxxx.
- Corrected pen up/down (feedrate was reversed) and changed feedrate to
degrees/second.
Future feature enhancements are planned to add a touchscreen control, SD card reader
support and audio alerts.
This sketch needs the following non-standard library which can be installed with the
Arduino Library Manager.
G-Code Parser Library
https://github.com/tgolla/GCodeParser
EEPROM Typed Library
https://github.com/tgolla/EEPROMTyped
Adafruit Motor Shield (select appropriate version ):
v1: https://github.com/adafruit/Adafruit-Motor-Shield-library
v2: https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library
Adafruit ILI9341 Arduino Library
https://github.com/adafruit/Adafruit_ILI9341
Adafruit GFX Library
https://github.com/adafruit/Adafruit-GFX-Library
Adafruit ImageReader Arduino Library
https://github.com/adafruit/Adafruit_ImageReader
Adafruit_FT6206 Library
https://github.com/adafruit/Adafruit_FT6206_Library
Be sure to review and make appropriate modification to global constants
in the "Configuration.h" file.
Programming Note:
When I added M17 every case statement after failed. It was not until
Doing some research that I discovered that in C++ it’s illegal to
declare variables (without the additional {} stack frame scoping)
inside a switch/case statement.
https://forum.arduino.cc/t/bug-in-ide-1-8-9-issues-in-the-execution-of-switch-case-default-statements/602420
https://arduinogetstarted.com/faq/switch-case-statement-does-not-work-correctly
https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement
*/
#include "Configuration.h"
#include <GCodeParser.h>
#include <EEPROMTyped.h>
#include <SPI.h>
#include <Wire.h>
#if ADAFRUIT_TFT_TOUCH_SHIELD
// Adafruit 2.8" TFT Touch Shield for Arduino w/Capacitive Touch
#include <Adafruit_GFX.h> // Core Graphics Library
// This contains the low-level code specific to the TFT display.
#include <Adafruit_ILI9341.h>
#include <SdFat.h> // SD card & FAT filesystem library. Adafruit Fork https://github.com/adafruit/SdFat
// Controller library which does all the low level chatting with
// the FT6206 capacitive touch driver chip.
#include <Adafruit_FT6206.h>
#include <Adafruit_ImageReader.h> // Image-reading functions.
#include "TouchscreenButton.h"
#include "TouchscreenGrid.h"
#include "AlphabeticSDFileList.h"
#endif
#include "SerialDisplayPrint.h"
// DualStepper Library for Adafruit Motor Shield
#include "DualStepper.h"
// Servo Library. Adafruit TiCoServo library https://learn.adafruit.com/neopixels-and-servos/the-ticoservo-library
// Eliminates jitter caused by I2C (i.e. touch screen) when using standard Arduino Servo library.
// Also tested/considered Servo Hardware PWM libruary include <Servo_Hardware_PWM.h> https://github.com/dadul96/Arduino-Servo-Hardware-PWM-Library
#include <Adafruit_TiCoServo.h>
#include <EEPROM.h>
#define TONE_FREQUENCY 392
#define FILELISTTEXTSIZE 3
void processCommand(bool noSerialResponse = false);
void touchScreenToContinue(char* message = NULL);
short coordinateRotation;
byte minPenPosition;
byte maxPenPosition;
byte penUpPosition;
byte penDownPosition;
byte currentPenPosition;
byte mzMode;
byte mzActiveMode;
byte mAdjust;
byte zAdjust;
byte mAdjustPreset;
byte zAdjustPreset;
short mAdjustCalculated = -1;
short zAdjustCalculated = -1;
double xyFeedrate;
double penFeedrate;
double presetXyFeedrate;
double presetPenFeedrate;
short penUpFeedrateMultiplier;
byte outputGcodeTo;
bool percentageTimeCalculationEnabled;
SerialDisplayPrint::PrintDevice outputGcodeToPrintDevice;
// EEPROM memory locations.
byte valueSavedEEPROMMemoryLocation = SAVED_EEPROM_BASE_MEMORY_LOCATION;
byte coordinateRotationEEPROMMemoryLocation = 1;
byte minPenEEPROMMemoryLocation =
coordinateRotationEEPROMMemoryLocation + EEPROMTyped.sizeOf(coordinateRotation);
byte maxPenEEPROMMemoryLocation =
minPenEEPROMMemoryLocation + EEPROMTyped.sizeOf(minPenPosition);
byte penUpEEPROMMemoryLocation =
maxPenEEPROMMemoryLocation + EEPROMTyped.sizeOf(maxPenPosition);
byte penDownEEPROMMemoryLocation =
penUpEEPROMMemoryLocation + EEPROMTyped.sizeOf(penUpPosition);
byte mzModeEEPROMMemoryLocation =
penDownEEPROMMemoryLocation + EEPROMTyped.sizeOf(penDownPosition);
byte mAdjustEEPROMMemoryLocation =
mzModeEEPROMMemoryLocation + EEPROMTyped.sizeOf(mzMode);
byte zAdjustEEPROMMemoryLocation =
mAdjustEEPROMMemoryLocation + EEPROMTyped.sizeOf(mAdjust);
byte mAdjustPresetEEPROMMemoryLocation =
zAdjustEEPROMMemoryLocation + EEPROMTyped.sizeOf(zAdjust);
byte zAdjustPresetEEPROMMemoryLocation =
mAdjustPresetEEPROMMemoryLocation + EEPROMTyped.sizeOf(mAdjustPreset);
byte xyFeedrateEEPROMMemoryLocation =
zAdjustPresetEEPROMMemoryLocation + EEPROMTyped.sizeOf(zAdjustPreset);
byte penFeedrateEEPROMMemoryLocation =
xyFeedrateEEPROMMemoryLocation + EEPROMTyped.sizeOf(xyFeedrate);
byte presetXyFeedrateEEPROMMemoryLocation =
penFeedrateEEPROMMemoryLocation + EEPROMTyped.sizeOf(penFeedrate);
byte presetPenFeedrateEEPROMMemoryLocation =
presetXyFeedrateEEPROMMemoryLocation + EEPROMTyped.sizeOf(presetXyFeedrate);
byte penUpFeedrateMultiplierEEPROMMemoryLocation =
presetPenFeedrateEEPROMMemoryLocation + EEPROMTyped.sizeOf(presetPenFeedrate);
byte outputGcodeToEEPROMMemoryLocation =
penUpFeedrateMultiplierEEPROMMemoryLocation + EEPROMTyped.sizeOf(penUpFeedrateMultiplier);
byte percentageTimeCalculationEnabledEEPROMMemoryLocation =
outputGcodeToEEPROMMemoryLocation + EEPROMTyped.sizeOf(outputGcodeTo);
// Number expected to be found in EEPROM memory location 0 that indicates
// pen setting have been stored in memory.
#define EEPROM_MAGIC_NUMBER 23
// Enum used with mzMode.
enum
{
M,
Z,
Auto
};
// Enum used with mAdjust and zAdjust.
enum
{
Off,
Preset,
Calculated
};
// Set up stepper motors and servo.
#if ADAFRUIT_MOTOR_SHIELD_VERSION == 1
SingleStepper *xStepper =
new SingleStepper(new AF_Stepper(STEPS_PER_REVOLUTION, ROTATION_AXIS_PORT));
SingleStepper *yStepper =
new SingleStepper(new AF_Stepper(STEPS_PER_REVOLUTION, PEN_AXIS_PORT));
#else
Adafruit_MotorShield MS = Adafruit_MotorShield();
SingleStepper *xStepper =
new SingleStepper(MS.getStepper(STEPS_PER_REVOLUTION, ROTATION_AXIS_PORT));
SingleStepper *yStepper =
new SingleStepper(MS.getStepper(STEPS_PER_REVOLUTION, PEN_AXIS_PORT));
#endif
DualStepper *steppers =
new DualStepper(xStepper, yStepper, STEPS_PER_REVOLUTION *MICROSTEPS);
Adafruit_TiCoServo servo;
// GCode states.
boolean absoluteMode = true;
double zoom = DEFAULT_ZOOM_FACTOR;
// Defaults to Serial port for GCode if SD and Touchscreen are not present.
boolean serialMode = true;
GCodeParser GCode = GCodeParser();
#if ADAFRUIT_TFT_TOUCH_SHIELD
SdFat SD; // SD card filesystem.
Adafruit_ImageReader reader(SD); // Image-reader object, pass in SD.
// Create an alphebetic gcode file list that rotates forward and backwards through files.
AlphabeticSDFileList alphabeticSDFileList = AlphabeticSDFileList();
// Instantiate class for TFT screen and Touchscreen
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
Adafruit_FT6206 ts = Adafruit_FT6206();
#define DEFAULT_PATH_SIZE 16
char path[DEFAULT_FILE_NAME_SIZE + DEFAULT_PATH_SIZE];
#endif
SerialDisplayPrint SerialDisplay;
void setup()
{
Serial.begin(115200);
loadPenConfiguration();
// Configure Adafruit motor shield.
#if ADAFRUIT_MOTOR_SHIELD_VERSION == 2
MS.begin();
// Change the i2c clock to 400KHz for faster stepping.
TWBR = ((F_CPU / 400000L) - 16) / 2;
#endif
steppers->setMaxSpeed(MAX_XY_FEEDRATE);
// Configure pen servo.
servo.attach(SERVO_PIN);
servoWrite(penUpPosition);
currentPenPosition = penUpPosition;
#if ADAFRUIT_TFT_TOUCH_SHIELD
// Look for SD and Touchscreen.
if (SD.begin(SD_CS))
{
alphabeticSDFileList.Begin(SD, "/gcode", true);
if (ts.begin(FT6206_THRESSHOLD))
{
tft.begin();
SerialDisplay.begin(Serial, tft);
tft.setRotation(TFT_ROTATION);
tft.fillScreen(ILI9341_BLACK);
// Display Splash Screen
ImageReturnCode stat = reader.drawBMP("/controls/splash.bmp", tft, 0, 0);
tft.setCursor(10, 10);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(5);
tft.print("SphereBot");
tft.setCursor(10, 10 + (8 * 5) + 2);
tft.setTextSize(2);
tft.print("An EggBot Clone");
tft.setCursor(10, 10 + (8 * 5) + 2 + (8 * 2) + 4);
tft.setTextSize(1);
tft.print("v1.9.4");
delay(SPLASH_SCREEN_DELAY);
tft.fillScreen(ILI9341_WHITE);
// Prompt for operation mode (Serial/USB or SD Card)
TouchscreenButton usb = TouchscreenButton(18, 20, 120, 200, 320, 240, TFT_ROTATION, "/controls/USB.bmp", "");
TouchscreenButton sdcard = TouchscreenButton(155, 20, 148, 200, 320, 240, TFT_ROTATION, "/controls/SDCard.bmp", "");
usb.Display(reader, tft);
sdcard.Display(reader, tft);
bool waitingOnButtomPress = true;
while (waitingOnButtomPress)
{
if (ts.touched())
{
TS_Point p = ts.getPoint();
if (sdcard.Touched(p.x, p.y))
serialMode = false;
waitingOnButtomPress = !(usb.Touched(p.x, p.y) || sdcard.Touched(p.x, p.y));
}
}
}
}
#else
SerialDisplay.begin(Serial);
#endif
if (serialMode)
{
loadPenConfiguration(); // Adjust for serial mode.
#if ADAFRUIT_TFT_TOUCH_SHIELD
SerialDisplay.SetTextDisplay();
#endif
SerialDisplay.println("Ready", SerialDisplay.SerialOnly);
delay(100);
}
// Lock stepper motors. Prevents drift especially in the x-axis should
// the first Gxx command move only the y-axis.
GCode.ParseLine("G00 X1 Y 1");
processCommand(true);
GCode.ParseLine("G00 X0 Y0");
processCommand(true);
}
void loop()
{
#if ADAFRUIT_TFT_TOUCH_SHIELD
if (serialMode)
{
#endif
// Check serial port for character.
if (Serial.available() > 0)
{
if (GCode.AddCharToLine(Serial.read()))
{
GCode.ParseLine();
processCommand();
}
}
#if ADAFRUIT_TFT_TOUCH_SHIELD
}
else
{
// Start at first file.
if (strcmp(alphabeticSDFileList.Current(), "") == 0)
alphabeticSDFileList.Next();
char *filename;
// Create menu buttons.
TouchscreenButton previousButton = TouchscreenButton(0, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/previous.bmp", "");
TouchscreenButton rewindButton = TouchscreenButton(40, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/rewind.bmp", "");
TouchscreenButton informationButton = TouchscreenButton(90, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/information.bmp", "/controls/camera.bmp");
TouchscreenButton printButton = TouchscreenButton(140, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/print.bmp", "");
TouchscreenButton abcButton = TouchscreenButton(190, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/abc.bmp", "");
TouchscreenButton forwardButton = TouchscreenButton(240, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/forward.bmp", "");
TouchscreenButton nextButton = TouchscreenButton(280, 200, 40, 40, 320, 240, TFT_ROTATION, "/controls/next.bmp", "");
bool displayInfo = false;
bool infoOnly = false;
bool waitingOnFileSelection = true;
while (waitingOnFileSelection)
{
filename = alphabeticSDFileList.Current();
if (displayInfo)
displayFileInfo(filename);
else
{
// Paint screen with design image.
tft.fillScreen(ILI9341_BLACK);
ImageReturnCode imageReturnCode = reader.drawBMP(createFilenamePath(filename, "/images", "bmp"), tft, 0, 0);
if (imageReturnCode != IMAGE_SUCCESS)
{
displayFileInfo(filename);
infoOnly = true;
}
}
// Display menu bar.
tft.fillRect(0, 200, 320, 40, ILI9341_WHITE);
previousButton.Display(reader, tft);
rewindButton.Display(reader, tft);
if (!infoOnly)
{
if (displayInfo)
informationButton.DisplayAlternate(reader, tft);
else
informationButton.Display(reader, tft);
}
printButton.Display(reader, tft);
abcButton.Display(reader, tft);
forwardButton.Display(reader, tft);
nextButton.Display(reader, tft);
// Select gcode file from SD to print.
bool waitingOnButtonPress = true;
while (waitingOnButtonPress)
{
if (ts.touched())
{
TS_Point p = ts.getPoint();
// Move to previous file.
if (previousButton.Touched(p.x, p.y))
{
alphabeticSDFileList.Previous();
infoOnly = false;
waitingOnButtonPress = false;
}
// Move backwards several (FORWARD_REWIND_COUNT) files.
if (rewindButton.Touched(p.x, p.y))
{
for (int i = 0; i < FORWARD_REWIND_COUNT; i++)
{
alphabeticSDFileList.Previous();
}
infoOnly = false;
waitingOnButtonPress = false;
}
// Display information on file.
if (!infoOnly)
{
if (informationButton.Touched(p.x, p.y))
{
displayInfo = !displayInfo;
waitingOnButtonPress = false;
}
}
// Print file.
if (printButton.Touched(p.x, p.y))
{
waitingOnFileSelection = false;
waitingOnButtonPress = false;
}
// Move to next file.
if (nextButton.Touched(p.x, p.y))
{
alphabeticSDFileList.Next();
infoOnly = false;
waitingOnButtonPress = false;
}
// Move forward several (FORWARD_REWIND_COUNT) files.
if (forwardButton.Touched(p.x, p.y))
{
for (int i = 0; i < FORWARD_REWIND_COUNT; i++)
{
alphabeticSDFileList.Next();
}
infoOnly = false;
waitingOnButtonPress = false;
}
// Display alphabetic file selection. Note: The ABC button test must be placed last in the
// button pressed if statements to prevent the button bar button from accidentally executing.
if (abcButton.Touched(p.x, p.y))
{
// Display ABC Screen
ImageReturnCode stat = reader.drawBMP("/controls/a~z.bmp", tft, 0, 0);
TouchscreenGrid abcGrid = TouchscreenGrid(7, 32, 7, 4, 44, 44, 320, 240, TFT_ROTATION);
char characterPressed;
bool waitingOnLetterPress = true;
while (waitingOnLetterPress)
{
if (ts.touched())
{
//Math to determine letter touched.
p = ts.getPoint();
int row = abcGrid.Row(p.x, p.y);
int column = abcGrid.Column(p.x, p.y);
if (row != 0 && column != 0)
{
characterPressed = 64 + (7 * (row - 1)) + column;
if (characterPressed <= 91)
{
if (characterPressed == 91)
characterPressed = '~';
char findFilename[2];
findFilename[0] = characterPressed;
findFilename[1] = '\0';
alphabeticSDFileList.Find(findFilename);
// If displayInfo then display file Title/Subtitle list.
if (displayInfo)
{
TouchscreenGrid fileListGrid = TouchscreenGrid(0, 0, 1, (int)(200/(FILELISTTEXTSIZE * 8)), 320, FILELISTTEXTSIZE * 8, 320, 240, TFT_ROTATION);
bool waitingOnFileSelection = true;
while (waitingOnFileSelection)
{
SerialDisplay.SetTextDisplay();
SerialDisplay.SetTextSize(FILELISTTEXTSIZE);
// List files.
for (int i = 0; i < (int)(200/(FILELISTTEXTSIZE * 8)); i++)
{
displayFileTitleSubtitle(alphabeticSDFileList.Current());
SerialDisplay.println("", SerialDisplay.DisplayOnly);
alphabeticSDFileList.Next();
}
// Display menu bar.
tft.fillRect(0, 200, 320, 40, ILI9341_WHITE);
previousButton.Display(reader, tft);
nextButton.Display(reader, tft);
bool waitingOnScreenTouch = true;
while (waitingOnScreenTouch)
{
if (ts.touched())
{
p = ts.getPoint();
if (nextButton.Touched(p.x, p.y))
{
waitingOnScreenTouch = false;
}
if (previousButton.Touched(p.x, p.y))
{
// Go back...
for (int i = 0; i < ((int)(200/(FILELISTTEXTSIZE * 8))) * 2; i++)
{
alphabeticSDFileList.Previous();
}
waitingOnScreenTouch = false;
}
int row = fileListGrid.Row(p.x, p.y);
if (row != 0)
{
for (int i = 0; i < ((int)(200/(FILELISTTEXTSIZE * 8))) - row + 1; i++)
{
alphabeticSDFileList.Previous();
}
waitingOnScreenTouch = false;
waitingOnFileSelection = false;
}
}
}
}
}
waitingOnLetterPress = false;
}
}
}
}
waitingOnButtonPress = false;
}
}
}
}
// Print File
SerialDisplay.SetTextDisplay();
loadPenConfiguration();
char *gCodeFilenamePath = createFilenamePath(filename, "/gcode", "");
double currentLine = 0;
int previousPercentage = 0;
unsigned long totalLines;
if (percentageTimeCalculationEnabled)
{
SerialDisplay.print("Calculating total number of lines: ", SerialDisplay.DisplayOnly);
totalLines = calculatefileTotalLineCount(gCodeFilenamePath);
SerialDisplay.println(totalLines, SerialDisplay.DisplayOnly);
}
GCode.Initialize();
File gCodeFile = SD.open(gCodeFilenamePath);
if (gCodeFile)
{
unsigned long startTime = millis();
while (gCodeFile.available())
{
if (GCode.AddCharToLine(gCodeFile.read()))
{
GCode.ParseLine();
processCommand();
if (percentageTimeCalculationEnabled)
{
currentLine = currentLine + 1;
int percentage = (currentLine / totalLines) * 100;
// Display percentage done and estimated time remaining (MM:SS).
if (percentage > previousPercentage)
{
unsigned long timePassed = millis() - startTime;
unsigned long secondsPassed = timePassed/1000;
unsigned long secondsRemaining = (secondsPassed / percentage) * (100 - percentage);
SerialDisplay.print("(", SerialDisplay.DisplayOnly);
SerialDisplay.print(percentage, SerialDisplay.DisplayOnly);
SerialDisplay.print("% ", SerialDisplay.DisplayOnly);
SerialDisplay.print(secondsRemaining / 60, SerialDisplay.DisplayOnly);
SerialDisplay.print(":", SerialDisplay.DisplayOnly);
secondsRemaining = secondsRemaining % 60;
if (secondsRemaining < 10)
SerialDisplay.print("0", SerialDisplay.DisplayOnly);
SerialDisplay.print(secondsRemaining, SerialDisplay.DisplayOnly);
SerialDisplay.println(")", SerialDisplay.DisplayOnly);
previousPercentage = percentage;
}
}
}
}
gCodeFile.close();
if (!GCode.completeLineIsAvailableToParse)
{
GCode.ParseLine();
processCommand();
}
}
touchScreenToContinue();
}
#endif
}
#if ADAFRUIT_TFT_TOUCH_SHIELD
char* createFilenamePath(char *filename, char *directory, char *extension)
{
path[0] = '\0';
// Start with directory.
strcat(path, directory);
if (path[strlen(path) -1] != '/')
strcat(path, "/");
// Add the filename.
strcat(path, filename);
// If the extension is not blank, add extension.
if (extension[0])
{
// Remove existing filename extension.
char *ext = strrchr(path, '.');
if (ext != nullptr)
ext[0] = '\0';
// Add file extension.
strcat(path, ".");
strcat(path, extension);
}
return path;
}
unsigned long calculatefileTotalLineCount(char *path)
{
unsigned long lineCount = 0;
char c;
File gCodeFile = SD.open(path);
if (gCodeFile)
{
while (gCodeFile.available())
{
c = gCodeFile.read();
if (c == '\n')
{
lineCount = lineCount + 1;
}
}
gCodeFile.close();
}
if (c != '\n')
{
lineCount = lineCount + 1;
}
return lineCount;
}
void displayFileInfo(char *filename)
{
SerialDisplay.SetTextDisplay();
SerialDisplay.SetTextSize(2);
char* filenamePath = createFilenamePath(filename, "/gcode", "");
GCode.Initialize();
File gCodeFile = SD.open(filenamePath);
if (gCodeFile)
{
bool firstCommentFound = false;
bool hasWord = false;
while (gCodeFile.available() > 0 && !hasWord)
{
if (GCode.AddCharToLine(gCodeFile.read()))
{
GCode.ParseLine();
if (GCode.comments[0])
firstCommentFound = true;
if (firstCommentFound)
{
hasWord = !GCode.NoWords();
if (!hasWord)
{
GCode.RemoveCommentSeparators();
SerialDisplay.println(GCode.comments, SerialDisplay.DisplayOnly);
SerialDisplay.SetTextSize(1);
}
}
}
}
gCodeFile.close();
if (!hasWord && !GCode.completeLineIsAvailableToParse)
{
GCode.RemoveCommentSeparators();
SerialDisplay.println(GCode.comments, SerialDisplay.DisplayOnly);
SerialDisplay.SetTextSize(1);
}
SerialDisplay.SetTextSize(1);
SerialDisplay.println("", SerialDisplay.DisplayOnly);
SerialDisplay.println(filename, SerialDisplay.DisplayOnly);
}
}
void displayFileTitleSubtitle(char *filename)
{
char* filenamePath = createFilenamePath(filename, "/gcode", "");
GCode.Initialize();
File gCodeFile = SD.open(filenamePath);
if (gCodeFile)
{
bool firstCommentFound = false;
bool hasWord = false;
int commentsRead = 0;
while (gCodeFile.available() > 0 && !hasWord && commentsRead < 2)
{
if (GCode.AddCharToLine(gCodeFile.read()))
{
GCode.ParseLine();
if (GCode.comments[0])
firstCommentFound = true;
if (firstCommentFound)
{
bool hasWord = !GCode.NoWords();
if (!hasWord)
{
GCode.RemoveCommentSeparators();
SerialDisplay.print(GCode.comments, SerialDisplay.DisplayOnly);
SerialDisplay.print(" ", SerialDisplay.DisplayOnly);
commentsRead++;
}
}
}
}
gCodeFile.close();
}
}
void touchScreenToContinue(char* message)
{
SerialDisplay.println("", SerialDisplay.DisplayOnly);
if (message != NULL)
SerialDisplay.println(message, SerialDisplay.DisplayOnly);
SerialDisplay.println("Touch screen to continue...", SerialDisplay.DisplayOnly);
#if PIEZO_PIN < 0
while (true)
{
if (ts.touched()) return;
}
#else
unsigned long expiresAt = millis();
int alertXTimes = 1;
while (true)
{
int alertedXTimes = 0;
while (alertedXTimes < alertXTimes)
{
int beepedXTimes = 0;
while (beepedXTimes < 3)
{
tone(PIEZO_PIN, TONE_FREQUENCY);
expiresAt = expiresAt + 1000;
while (millis() < expiresAt)
{
if (ts.touched())
{
noTone(PIEZO_PIN);
return;
}
}
noTone(PIEZO_PIN);
expiresAt = expiresAt + 500;
while (millis() < expiresAt)
{
if (ts.touched()) return;
}
beepedXTimes++;
}
expiresAt = expiresAt + 3000;
while (millis() < expiresAt)
{
if (ts.touched()) return;
}
alertedXTimes++;
}
expiresAt = expiresAt + 60000;
while (millis() < expiresAt)
{
if (ts.touched()) return;
}
alertXTimes++;
}
#endif
}
#endif
// Loads the pen configuration from memory.
void loadPenConfiguration()
{
// Check EEPROM location 0 for presence of a magic number.
// If it's there, we have saved pen settings.
if (EEPROM.read(valueSavedEEPROMMemoryLocation) == EEPROM_MAGIC_NUMBER)
{
EEPROMTyped.read(coordinateRotationEEPROMMemoryLocation, coordinateRotation);
EEPROMTyped.read(minPenEEPROMMemoryLocation, minPenPosition);
EEPROMTyped.read(maxPenEEPROMMemoryLocation, maxPenPosition);
EEPROMTyped.read(penUpEEPROMMemoryLocation, penUpPosition);
EEPROMTyped.read(penDownEEPROMMemoryLocation, penDownPosition);
EEPROMTyped.read(mzModeEEPROMMemoryLocation, mzMode);
EEPROMTyped.read(mAdjustEEPROMMemoryLocation, mAdjust);
EEPROMTyped.read(zAdjustEEPROMMemoryLocation, zAdjust);
EEPROMTyped.read(mAdjustPresetEEPROMMemoryLocation, mAdjustPreset);
EEPROMTyped.read(zAdjustPresetEEPROMMemoryLocation, zAdjustPreset);
EEPROMTyped.read(xyFeedrateEEPROMMemoryLocation, xyFeedrate);
EEPROMTyped.read(penFeedrateEEPROMMemoryLocation, penFeedrate);
EEPROMTyped.read(presetXyFeedrateEEPROMMemoryLocation, presetXyFeedrate);
EEPROMTyped.read(presetPenFeedrateEEPROMMemoryLocation, presetPenFeedrate);
EEPROMTyped.read(penUpFeedrateMultiplierEEPROMMemoryLocation, penUpFeedrateMultiplier);
EEPROMTyped.read(outputGcodeToEEPROMMemoryLocation, outputGcodeTo);
EEPROMTyped.read(percentageTimeCalculationEnabledEEPROMMemoryLocation, percentageTimeCalculationEnabled);
}
else
{
coordinateRotation = COORDINATE_ROTATION;
minPenPosition = MIN_PEN_POSITION;
maxPenPosition = MAX_PEN_POSITION;
penUpPosition = DEFAULT_PEN_UP_POSITION;
penDownPosition = DEFAULT_PEN_DOWN_POSITION;
mzMode = DEFAULT_MZ_MODE;
mAdjust = DEFAULT_M_ADJUST;
zAdjust = DEFAULT_Z_ADJUST;
mAdjustPreset = DEFAULT_M_ADJUST_PRESET;
zAdjustPreset = DEFAULT_Z_ADJUST_PRESET;
xyFeedrate = DEFAULT_XY_FEEDRATE;
penFeedrate = DEFAULT_PEN_FEEDRATE;
presetXyFeedrate = DEFAULT_PRESET_XY_FEEDRATE;
presetPenFeedrate = DEFAULT_PRESET_PEN_FEEDRATE;
penUpFeedrateMultiplier = DEFAULT_PEN_UP_FEEDRATE_MULTIPLIER;
outputGcodeTo = OUTPUT_GCODE_TO;
percentageTimeCalculationEnabled = PERCENTAGE_TIME_CALCULATION_ENABLED;
}
// Used to determine the MZ mode when set to Auto.
mzActiveMode = mzMode;
// Negative 1 indicates the calculated value has not been set.
short mAdjustCalculated = -1;
short zAdjustCalculated = -1;
// If preset values are not zero use to set feedrates.
if (presetXyFeedrate > 0)
xyFeedrate = presetXyFeedrate;
if (presetPenFeedrate > 0)
penFeedrate = presetPenFeedrate;
#if ADAFRUIT_TFT_TOUCH_SHIELD
outputGcodeToPrintDevice = static_cast<SerialDisplayPrint::PrintDevice>(outputGcodeTo);
if (serialMode)
{
if (outputGcodeTo = SerialDisplay.Neither)