forked from Duet3D/RepRapFirmware
/
Platform.cpp
2926 lines (2563 loc) · 81.3 KB
/
Platform.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
/****************************************************************************************************
RepRapFirmware - Platform: RepRapPro Ormerod with Duet controller
Platform contains all the code and definitions to deal with machine-dependent things such as control
pins, bed area, number of extruders, tolerable accelerations and speeds and so on.
-----------------------------------------------------------------------------------------------------
Version 0.1
18 November 2012
Adrian Bowyer
RepRap Professional Ltd
http://reprappro.com
Licence: GPL
****************************************************************************************************/
#include "RepRapFirmware.h"
#include "DueFlashStorage.h"
#include "sam/drivers/tc/tc.h"
#include "sam/drivers/hsmci/hsmci.h"
#if defined(DUET_NG) && !defined(PROTOTYPE_1)
# include <TMC2660.h>
#endif
#ifdef DUET_NG
# include "FirmwareUpdater.h"
#endif
extern char _end;
extern "C" char *sbrk(int i);
#ifdef DUET_NG
const uint16_t driverPowerOnAdcReading = (uint16_t)(4096 * 10.0/PowerFailVoltageRange); // minimum voltage at which we initialise the drivers
const uint16_t driverPowerOffAdcReading = (uint16_t)(4096 * 9.5/PowerFailVoltageRange); // voltages below this flag the drivers as unusable
const uint16_t driverOverVoltageAdcReading = (uint16_t)(4096 * 29.0/PowerFailVoltageRange); // voltages above this cause driver shutdown
const uint16_t driverNormalVoltageAdcReading = (uint16_t)(4096 * 25.5/PowerFailVoltageRange); // voltages at or below this are normal
#endif
const uint8_t memPattern = 0xA5;
static uint32_t fanInterruptCount = 0; // accessed only in ISR, so no need to declare it volatile
const uint32_t fanMaxInterruptCount = 32; // number of fan interrupts that we average over
static volatile uint32_t fanLastResetTime = 0; // time (microseconds) at which we last reset the interrupt count, accessed inside and outside ISR
static volatile uint32_t fanInterval = 0; // written by ISR, read outside the ISR
const float minStepPulseTiming = 0.2; // we assume that we always generate step high and low times at least this wide without special action
//#define MOVE_DEBUG
#ifdef MOVE_DEBUG
unsigned int numInterruptsScheduled = 0;
unsigned int numInterruptsExecuted = 0;
uint32_t nextInterruptTime = 0;
uint32_t nextInterruptScheduledAt = 0;
uint32_t lastInterruptTime = 0;
#endif
// Urgent initialisation function
// This is called before general init has been done, and before constructors for C++ static data have been called.
// Therefore, be very careful what you do here!
void UrgentInit()
{
#ifdef DUET_NG
// When the reset button is pressed, if the TMC2660 drivers were previously enabled then we get uncommanded motor movements.
// Try to reduce that by initialising the drivers early here.
// On the production board we will also be able to set the ENN line high here.
for (size_t drive = 0; drive < DRIVES; ++drive)
{
pinMode(STEP_PINS[drive], OUTPUT_LOW);
pinMode(DIRECTION_PINS[drive], OUTPUT_LOW);
pinMode(ENABLE_PINS[drive], OUTPUT_HIGH);
}
#endif
}
// Arduino initialise and loop functions
// Put nothing in these other than calls to the RepRap equivalents
void setup()
{
// Fill the free memory with a pattern so that we can check for stack usage and memory corruption
char* heapend = sbrk(0);
register const char * stack_ptr asm ("sp");
while (heapend + 16 < stack_ptr)
{
*heapend++ = memPattern;
}
reprap.Init();
}
void loop()
{
reprap.Spin();
}
extern "C"
{
// This intercepts the 1ms system tick. It must return 'false', otherwise the Arduino core tick handler will be bypassed.
int sysTickHook()
{
reprap.Tick();
return 0;
}
}
//*************************************************************************************************
// PidParameters class
bool PidParameters::UsePID() const
{
return kP >= 0;
}
float PidParameters::GetThermistorR25() const
{
return thermistorInfR * exp(thermistorBeta / (25.0 - ABS_ZERO));
}
void PidParameters::SetThermistorR25AndBeta(float r25, float beta)
{
thermistorInfR = r25 * exp(-beta / (25.0 - ABS_ZERO));
thermistorBeta = beta;
}
bool PidParameters::operator==(const PidParameters& other) const
{
return kI == other.kI && kD == other.kD && kP == other.kP && kT == other.kT && kS == other.kS
&& fullBand == other.fullBand && pidMin == other.pidMin
&& pidMax == other.pidMax && thermistorBeta == other.thermistorBeta && thermistorInfR == other.thermistorInfR
&& thermistorSeriesR == other.thermistorSeriesR && adcLowOffset == other.adcLowOffset
&& adcHighOffset == other.adcHighOffset;
}
//*************************************************************************************************
// Platform class
/*static*/ const uint8_t Platform::pinAccessAllowed[NUM_PINS_ALLOWED/8] = PINS_ALLOWED;
Platform::Platform() :
autoSaveEnabled(false), board(DEFAULT_BOARD_TYPE), active(false), errorCodeBits(0),
fileStructureInitialised(false), tickState(0), debugCode(0)
{
// Output
auxOutput = new OutputStack();
aux2Output = new OutputStack();
usbOutput = new OutputStack();
// Files
massStorage = new MassStorage(this);
for (size_t i = 0; i < MAX_FILES; i++)
{
files[i] = new FileStore(this);
}
}
//*******************************************************************************************************************
void Platform::Init()
{
// Deal with power first
pinMode(ATX_POWER_PIN, OUTPUT_LOW);
SetBoardType(BoardType::Auto);
// Comms
baudRates[0] = MAIN_BAUD_RATE;
baudRates[1] = AUX_BAUD_RATE;
#if NUM_SERIAL_CHANNELS >= 2
baudRates[2] = AUX2_BAUD_RATE;
#endif
commsParams[0] = 0;
commsParams[1] = 1; // by default we require a checksum on data from the aux port, to guard against overrun errors
#if NUM_SERIAL_CHANNELS >= 2
commsParams[2] = 0;
#endif
SERIAL_MAIN_DEVICE.begin(baudRates[0]);
SERIAL_AUX_DEVICE.begin(baudRates[1]); // this can't be done in the constructor because the Arduino port initialisation isn't complete at that point
#ifdef SERIAL_AUX2_DEVICE
SERIAL_AUX2_DEVICE.begin(baudRates[2]);
#endif
static_assert(sizeof(FlashData) + sizeof(SoftwareResetData) <= FLASH_DATA_LENGTH, "NVData too large");
ResetNvData();
// We need to initialise at least some of the time stuff before we call MassStorage::Init()
addToTime = 0.0;
lastTimeCall = 0;
lastTime = Time();
longWait = lastTime;
// File management
massStorage->Init();
for (size_t file = 0; file < MAX_FILES; file++)
{
files[file]->Init();
}
fileStructureInitialised = true;
#if !defined(DUET_NG) || defined(PROTOTYPE_1)
mcpDuet.begin(); // only call begin once in the entire execution, this begins the I2C comms on that channel for all objects
mcpExpansion.setMCP4461Address(0x2E); // not required for mcpDuet, as this uses the default address
#endif
// Directories
sysDir = SYS_DIR;
macroDir = MACRO_DIR;
webDir = WEB_DIR;
gcodeDir = GCODE_DIR;
configFile = CONFIG_FILE;
defaultFile = DEFAULT_FILE;
// DRIVES
ARRAY_INIT(directions, DIRECTIONS);
ARRAY_INIT(enableValues, ENABLE_VALUES);
ARRAY_INIT(endStopPins, END_STOP_PINS);
ARRAY_INIT(maxFeedrates, MAX_FEEDRATES);
ARRAY_INIT(accelerations, ACCELERATIONS);
ARRAY_INIT(driveStepsPerUnit, DRIVE_STEPS_PER_UNIT);
ARRAY_INIT(instantDvs, INSTANT_DVS);
#if !defined(DUET_NG) || defined(PROTOTYPE_1)
ARRAY_INIT(potWipes, POT_WIPES);
senseResistor = SENSE_RESISTOR;
maxStepperDigipotVoltage = MAX_STEPPER_DIGIPOT_VOLTAGE;
stepperDacVoltageRange = STEPPER_DAC_VOLTAGE_RANGE;
stepperDacVoltageOffset = STEPPER_DAC_VOLTAGE_OFFSET;
#endif
maxAverageAcceleration = 10000.0; // high enough to have no effect until it is changed
// Z PROBE
zProbePin = Z_PROBE_PIN;
zProbeAdcChannel = PinToAdcChannel(zProbePin);
InitZProbe(); // this also sets up zProbeModulationPin
// AXES
ARRAY_INIT(axisMaxima, AXIS_MAXIMA);
ARRAY_INIT(axisMinima, AXIS_MINIMA);
idleCurrentFactor = DEFAULT_IDLE_CURRENT_FACTOR;
// HEATERS - Bed is assumed to be the first
ARRAY_INIT(tempSensePins, TEMP_SENSE_PINS);
ARRAY_INIT(heatOnPins, HEAT_ON_PINS);
ARRAY_INIT(spiTempSenseCsPins, SpiTempSensorCsPins);
configuredHeaters = (BED_HEATER >= 0) ? (1 << BED_HEATER) : 0;
heatSampleTime = HEAT_SAMPLE_TIME;
timeToHot = TIME_TO_HOT;
// Enable pullups on all the SPI CS pins. This is required if we are using more than one device on the SPI bus.
// Otherwise, when we try to initialise the first device, the other devices may respond as well because their CS lines are not high.
for (size_t i = 0; i < MaxSpiTempSensors; ++i)
{
setPullup(SpiTempSensorCsPins[i], true);
}
// Motors
// Disable parallel writes to all pins. We re-enable them for the step pins.
PIOA->PIO_OWDR = 0xFFFFFFFF;
PIOB->PIO_OWDR = 0xFFFFFFFF;
PIOC->PIO_OWDR = 0xFFFFFFFF;
PIOD->PIO_OWDR = 0xFFFFFFFF;
for (size_t drive = 0; drive < DRIVES; drive++)
{
// Map axes and extruders straight through
if (drive < AXES)
{
axisDrivers[drive].numDrivers = 1;
axisDrivers[drive].driverNumbers[0] = (uint8_t)drive;
endStopType[drive] =
#if defined(DUET_NG) || defined(__RADDS__)
EndStopType::lowEndStop; // default to low endstop
#else
(drive == Y_AXIS)
? EndStopType::lowEndStop // for Ormerod 2/Huxley/Mendel compatibility
: EndStopType::noEndStop; // for Ormerod/Huxley/Mendel compatibility
#endif
endStopLogicLevel[drive] = true; // assume all endstops use active high logic e.g. normally-closed switch to ground
}
else
{
extruderDrivers[drive - AXES] = (uint8_t)drive;
SetElasticComp(drive - AXES, 0.0);
}
driveDriverBits[drive] = CalcDriverBitmap(drive);
// Set up the control pins and endstops
pinMode(STEP_PINS[drive], OUTPUT_LOW);
pinMode(DIRECTION_PINS[drive], OUTPUT_LOW);
pinMode(ENABLE_PINS[drive], OUTPUT_HIGH); // this is OK for the TMC2660 CS pins too
if (endStopPins[drive] >= 0)
{
pinMode(endStopPins[drive], INPUT_PULLUP); // enable pullup resistor so that expansion connector pins can be used as trigger inputs
}
const PinDescription& pinDesc = g_APinDescription[STEP_PINS[drive]];
pinDesc.pPort->PIO_OWER = pinDesc.ulPin; // enable parallel writes to the step pin
motorCurrents[drive] = 0.0;
motorCurrentFraction[drive] = 1.0;
driverState[drive] = DriverStatus::disabled;
}
slowDriverStepPulseClocks = 0; // no extended driver timing configured yet
slowDrivers = 0; // assume no drivers need extended step pulse timing
#ifdef DUET_NG
numTMC2660Drivers = DRIVES; // for now assume all drivers are TMC2660 on the Duet NG
driversPowered = false;
TMC2660::Init(ENABLE_PINS);
#endif
extrusionAncilliaryPWM = 0.0;
// HEATERS - Bed is assumed to be index 0
for (size_t heater = 0; heater < HEATERS; heater++)
{
if (heatOnPins[heater] >= 0)
{
pinMode(heatOnPins[heater], (HEAT_ON) ? OUTPUT_LOW : OUTPUT_HIGH);
}
AnalogChannelNumber chan = PinToAdcChannel(tempSensePins[heater]); // translate the Arduino Due Analog pin number to the SAM ADC channel number
pinMode(tempSensePins[heater], AIN);
thermistorAdcChannels[heater] = chan;
AnalogInEnableChannel(chan, true);
SetThermistorNumber(heater, heater); // map the thermistor straight through
thermistorFilters[heater].Init(0);
}
SetTemperatureLimit(DEFAULT_TEMPERATURE_LIMIT);
InitFans();
// Hotend configuration
nozzleDiameter = NOZZLE_DIAMETER;
filamentWidth = FILAMENT_WIDTH;
#if SUPPORT_INKJET
// Inkjet
inkjetBits = INKJET_BITS;
if (inkjetBits >= 0)
{
inkjetFireMicroseconds = INKJET_FIRE_MICROSECONDS;
inkjetDelayMicroseconds = INKJET_DELAY_MICROSECONDS;
inkjetSerialOut = INKJET_SERIAL_OUT;
pinMode(inkjetSerialOut, OUTPUT_LOW);
inkjetShiftClock = INKJET_SHIFT_CLOCK;
pinMode(inkjetShiftClock, OUTPUT_LOW);
inkjetStorageClock = INKJET_STORAGE_CLOCK;
pinMode(inkjetStorageClock, OUTPUT_LOW);
inkjetOutputEnable = INKJET_OUTPUT_ENABLE;
pinMode(inkjetOutputEnable, OUTPUT_HIGH);
inkjetClear = INKJET_CLEAR;
pinMode(inkjetClear, OUTPUT_HIGH);
}
#endif
// MCU temperature and power monitoring
#ifndef __RADDS__
temperatureAdcChannel = GetTemperatureAdcChannel();
AnalogInEnableChannel(temperatureAdcChannel, true);
#endif
currentMcuTemperature = highestMcuTemperature = 0;
lowestMcuTemperature = 4095;
mcuTemperatureAdjust = 0.0;
mcuAlarmTemperature = 80.0; // need to set the quite high here because the sensor is not be calibrated yet
#ifdef DUET_NG
vInMonitorAdcChannel = PinToAdcChannel(PowerMonitorVinDetectPin);
pinMode(PowerMonitorVinDetectPin, AIN);
AnalogInEnableChannel(vInMonitorAdcChannel, true);
currentVin = highestVin = 0;
lowestVin = 9999;
#endif
// Clear the spare pin configuration
memset(pinInitialised, 0, sizeof(pinInitialised));
// Kick everything off
lastTime = Time();
longWait = lastTime;
InitialiseInterrupts(); // also sets 'active' to true
}
void Platform::InvalidateFiles()
{
for (size_t i = 0; i < MAX_FILES; i++)
{
files[i]->Init();
}
}
void Platform::SetTemperatureLimit(float t)
{
temperatureLimit = t;
for (size_t heater = 0; heater < HEATERS; heater++)
{
// Calculate and store the ADC average sum that corresponds to an overheat condition, so that we can check it quickly in the tick ISR
float thermistorOverheatResistance = nvData.pidParams[heater].GetRInf()
* exp(-nvData.pidParams[heater].GetBeta() / (temperatureLimit - ABS_ZERO));
float thermistorOverheatAdcValue = (AD_RANGE_REAL + 1) * thermistorOverheatResistance
/ (thermistorOverheatResistance + nvData.pidParams[heater].thermistorSeriesR);
thermistorOverheatSums[heater] = (uint32_t) (thermistorOverheatAdcValue + 0.9) * THERMISTOR_AVERAGE_READINGS;
}
}
// Specify which thermistor channel a particular heater uses
void Platform::SetThermistorNumber(size_t heater, size_t thermistor)
//pre(heater < HEATERS && thermistor < HEATERS)
{
heaterTempChannels[heater] = thermistor;
// Initialize the associated SPI temperature sensor?
if (thermistor >= FirstThermocoupleChannel && thermistor < FirstThermocoupleChannel + MaxSpiTempSensors)
{
SpiTempSensors[thermistor - FirstThermocoupleChannel].InitThermocouple(SpiTempSensorCsPins[thermistor - FirstThermocoupleChannel]);
}
else if (thermistor >= FirstRtdChannel && thermistor < FirstRtdChannel + MaxSpiTempSensors)
{
SpiTempSensors[thermistor - FirstRtdChannel].InitRtd(spiTempSenseCsPins[thermistor - FirstRtdChannel]);
}
reprap.GetHeat()->ResetFault(heater);
}
int Platform::GetThermistorNumber(size_t heater) const
{
return heaterTempChannels[heater];
}
void Platform::InitZProbe()
{
zProbeOnFilter.Init(0);
zProbeOffFilter.Init(0);
#if defined(DUET_NG) || defined(__RADDS__)
zProbeModulationPin = Z_PROBE_MOD_PIN;
#else
zProbeModulationPin = (board == BoardType::Duet_07 || board == BoardType::Duet_085) ? Z_PROBE_MOD_PIN07 : Z_PROBE_MOD_PIN;
#endif
switch (nvData.zProbeType)
{
case 1:
case 2:
AnalogInEnableChannel(zProbeAdcChannel, true);
pinMode(zProbePin, AIN);
pinMode(zProbeModulationPin, OUTPUT_HIGH); // enable the IR LED
break;
case 3:
AnalogInEnableChannel(zProbeAdcChannel, true);
pinMode(zProbePin, AIN);
pinMode(zProbeModulationPin, OUTPUT_LOW); // enable the alternate sensor
break;
case 4:
AnalogInEnableChannel(zProbeAdcChannel, false);
pinMode(zProbePin, INPUT_PULLUP);
pinMode(endStopPins[E0_AXIS], INPUT_PULLUP);
break;
case 5:
default:
AnalogInEnableChannel(zProbeAdcChannel, false);
pinMode(zProbePin, INPUT_PULLUP);
break;
case 6:
AnalogInEnableChannel(zProbeAdcChannel, false);
pinMode(zProbePin, INPUT_PULLUP);
break; //TODO (DeltaProbe)
}
}
// Return the Z probe data.
// The ADC readings are 12 bits, so we convert them to 10-bit readings for compatibility with the old firmware.
int Platform::ZProbe() const
{
if (zProbeOnFilter.IsValid() && zProbeOffFilter.IsValid())
{
switch (nvData.zProbeType)
{
case 1: // Simple or intelligent IR sensor
case 3: // Alternate sensor
case 4: // Switch connected to E0 endstop input
case 5: // Switch connected to Z probe input
return (int) ((zProbeOnFilter.GetSum() + zProbeOffFilter.GetSum()) / (8 * Z_PROBE_AVERAGE_READINGS));
case 2: // Dumb modulated IR sensor.
// We assume that zProbeOnFilter and zProbeOffFilter average the same number of readings.
// Because of noise, it is possible to get a negative reading, so allow for this.
return (int) (((int32_t) zProbeOnFilter.GetSum() - (int32_t) zProbeOffFilter.GetSum())
/ (int)(4 * Z_PROBE_AVERAGE_READINGS));
case 6:
return (int) ((zProbeOnFilter.GetSum() + zProbeOffFilter.GetSum()) / (8 * Z_PROBE_AVERAGE_READINGS)); //TODO this is temporary
default:
break;
}
}
return 0; // Z probe not turned on or not initialised yet
}
// Return the Z probe secondary values.
int Platform::GetZProbeSecondaryValues(int& v1, int& v2)
{
if (zProbeOnFilter.IsValid() && zProbeOffFilter.IsValid())
{
switch (nvData.zProbeType)
{
case 2: // modulated IR sensor
v1 = (int) (zProbeOnFilter.GetSum() / (4 * Z_PROBE_AVERAGE_READINGS)); // pass back the reading with IR turned on
return 1;
default:
break;
}
}
return 0;
}
int Platform::GetZProbeType() const
{
return nvData.zProbeType;
}
void Platform::SetZProbeAxes(const bool axes[AXES])
{
for (size_t axis=0; axis<AXES; axis++)
{
nvData.zProbeAxes[axis] = axes[axis];
}
if (autoSaveEnabled)
{
WriteNvData();
}
}
void Platform::GetZProbeAxes(bool (&axes)[AXES])
{
for (size_t axis=0; axis<AXES; axis++)
{
axes[axis] = nvData.zProbeAxes[axis];
}
}
float Platform::ZProbeStopHeight()
{
const int8_t bedHeater = reprap.GetHeat()->GetBedHeater();
float temperature = (bedHeater >= 0) ? GetTemperature(bedHeater) : 25.0;
switch (nvData.zProbeType)
{
case 1:
case 2:
return nvData.irZProbeParameters.GetStopHeight(temperature);
case 3:
case 6:
return nvData.alternateZProbeParameters.GetStopHeight(temperature);
case 4:
case 5:
return nvData.switchZProbeParameters.GetStopHeight(temperature);
default:
return 0;
}
}
float Platform::GetZProbeDiveHeight() const
{
switch (nvData.zProbeType)
{
case 1:
case 2:
return nvData.irZProbeParameters.diveHeight;
case 3:
case 6:
return nvData.alternateZProbeParameters.diveHeight;
case 4:
case 5:
return nvData.switchZProbeParameters.diveHeight;
default:
return DEFAULT_Z_DIVE;
}
}
float Platform::GetZProbeTravelSpeed() const
{
switch (nvData.zProbeType)
{
case 1:
case 2:
return nvData.irZProbeParameters.travelSpeed;
case 3:
case 6:
return nvData.alternateZProbeParameters.travelSpeed;
case 4:
case 5:
return nvData.switchZProbeParameters.travelSpeed;
default:
return DEFAULT_TRAVEL_SPEED;
}
}
void Platform::SetZProbeType(int pt)
{
int newZProbeType = (pt >= 0 && pt <= 6) ? pt : 0;
if (newZProbeType != nvData.zProbeType)
{
nvData.zProbeType = newZProbeType;
if (autoSaveEnabled)
{
WriteNvData();
}
}
InitZProbe();
}
const ZProbeParameters& Platform::GetZProbeParameters() const
{
switch (nvData.zProbeType)
{
case 1:
case 2:
return nvData.irZProbeParameters;
case 3:
case 6:
return nvData.alternateZProbeParameters;
case 4:
case 5:
default:
return nvData.switchZProbeParameters;
}
}
bool Platform::SetZProbeParameters(const struct ZProbeParameters& params)
{
switch (nvData.zProbeType)
{
case 1:
case 2:
if (nvData.irZProbeParameters != params)
{
nvData.irZProbeParameters = params;
if (autoSaveEnabled)
{
WriteNvData();
}
}
return true;
case 3:
case 6:
if (nvData.alternateZProbeParameters != params)
{
nvData.alternateZProbeParameters = params;
if (autoSaveEnabled)
{
WriteNvData();
}
}
return true;
case 4:
case 5:
if (nvData.switchZProbeParameters != params)
{
nvData.switchZProbeParameters = params;
if (autoSaveEnabled)
{
WriteNvData();
}
}
return true;
default:
return false;
}
}
// Return true if we must home X and Y before we home Z (i.e. we are using a bed probe)
bool Platform::MustHomeXYBeforeZ() const
{
return nvData.zProbeType != 0 && nvData.zProbeAxes[Z_AXIS];
}
void Platform::ResetNvData()
{
nvData.compatibility = marlin; // default to Marlin because the common host programs expect the "OK" response to commands
ARRAY_INIT(nvData.ipAddress, IP_ADDRESS);
ARRAY_INIT(nvData.netMask, NET_MASK);
ARRAY_INIT(nvData.gateWay, GATE_WAY);
#ifdef DUET_NG
memset(nvData.macAddress, 0xFF, sizeof(nvData.macAddress));
#else
ARRAY_INIT(nvData.macAddress, MAC_ADDRESS);
#endif
nvData.zProbeType = 0; // Default is to use no Z probe switch
ARRAY_INIT(nvData.zProbeAxes, Z_PROBE_AXES);
nvData.switchZProbeParameters.Init(0.0);
nvData.irZProbeParameters.Init(Z_PROBE_STOP_HEIGHT);
nvData.alternateZProbeParameters.Init(Z_PROBE_STOP_HEIGHT);
for (size_t i = 0; i < HEATERS; ++i)
{
PidParameters& pp = nvData.pidParams[i];
pp.thermistorSeriesR = defaultThermistorSeriesRs[i];
pp.SetThermistorR25AndBeta(defaultThermistor25RS[i], defaultThermistorBetas[i]);
pp.kI = defaultPidKis[i];
pp.kD = defaultPidKds[i];
pp.kP = defaultPidKps[i];
pp.kT = defaultPidKts[i];
pp.kS = defaultPidKss[i];
pp.fullBand = defaultFullBands[i];
pp.pidMin = defaultPidMins[i];
pp.pidMax = defaultPidMaxes[i];
pp.adcLowOffset = pp.adcHighOffset = 0.0;
}
#if FLASH_SAVE_ENABLED
nvData.magic = FlashData::magicValue;
nvData.version = FlashData::versionValue;
#endif
}
void Platform::ReadNvData()
{
#if FLASH_SAVE_ENABLED
DueFlashStorage::read(FlashData::nvAddress, &nvData, sizeof(nvData));
if (nvData.magic != FlashData::magicValue || nvData.version != FlashData::versionValue)
{
// Nonvolatile data has not been initialized since the firmware was last written, so set up default values
ResetNvData();
// No point in writing it back here
}
#else
Message(BOTH_ERROR_MESSAGE, "Cannot load non-volatile data, because Flash support has been disabled!\n");
#endif
}
void Platform::WriteNvData()
{
#if FLASH_SAVE_ENABLED
DueFlashStorage::write(FlashData::nvAddress, &nvData, sizeof(nvData));
#else
Message(BOTH_ERROR_MESSAGE, "Cannot write non-volatile data, because Flash support has been disabled!\n");
#endif
}
void Platform::SetAutoSave(bool enabled)
{
#if FLASH_SAVE_ENABLED
autoSaveEnabled = enabled;
#else
Message(BOTH_ERROR_MESSAGE, "Cannot enable auto-save, because Flash support has been disabled!\n");
#endif
}
// Check the prerequisites for updating the main firmware. Return True if satisfied, else print as message and return false.
bool Platform::CheckFirmwareUpdatePrerequisites()
{
if (!GetMassStorage()->FileExists(GetSysDir(), IAP_FIRMWARE_FILE))
{
MessageF(GENERIC_MESSAGE, "Error: Firmware binary \"%s\" not found\n", IAP_FIRMWARE_FILE);
return false;
}
if (!GetMassStorage()->FileExists(GetSysDir(), IAP_UPDATE_FILE))
{
MessageF(GENERIC_MESSAGE, "Error: In-application programming binary \"%s\" not found\n", IAP_UPDATE_FILE);
return false;
}
return true;
}
// Update the firmware. Prerequisites should be checked before calling this.
void Platform::UpdateFirmware()
{
FileStore *iapFile = GetFileStore(GetSysDir(), IAP_UPDATE_FILE, false);
if (iapFile == nullptr)
{
MessageF(FIRMWARE_UPDATE_MESSAGE, "IAP not found\n");
return;
}
// The machine will be unresponsive for a few seconds, don't risk damaging the heaters...
reprap.EmergencyStop();
// Step 1 - Write update binary to Flash and overwrite the remaining space with zeros
// Leave the last 1KB of Flash memory untouched, so we can reuse the NvData after this update
#if !defined(IFLASH_PAGE_SIZE) && defined(IFLASH0_PAGE_SIZE)
# define IFLASH_PAGE_SIZE IFLASH0_PAGE_SIZE
#endif
// Use a 32-bit aligned buffer. This gives us the option of calling the EFC functions directly in future.
uint32_t data32[IFLASH_PAGE_SIZE/4];
char* const data = reinterpret_cast<char *>(data32);
#if (SAM4S || SAM4E)
// The EWP command is not supported for non-8KByte sectors in the SAM4 series.
// So we have to unlock and erase the complete 64Kb sector first.
// TODO save the NVRAM area and restore it later
flash_unlock(IAP_FLASH_START, IAP_FLASH_END, nullptr, nullptr);
flash_erase_sector(IAP_FLASH_START);
for (uint32_t flashAddr = IAP_FLASH_START; flashAddr < IAP_FLASH_END; flashAddr += IFLASH_PAGE_SIZE)
{
const int bytesRead = iapFile->Read(data, IFLASH_PAGE_SIZE);
if (bytesRead > 0)
{
// Do we have to fill up the remaining buffer with zeros?
if (bytesRead != IFLASH_PAGE_SIZE)
{
memset(data + bytesRead, 0, sizeof(data[0]) * (IFLASH_PAGE_SIZE - bytesRead));
}
// Write one page at a time
cpu_irq_disable();
const uint32_t rc = flash_write(flashAddr, data, IFLASH_PAGE_SIZE, 0);
cpu_irq_enable();
if (rc != FLASH_RC_OK)
{
MessageF(FIRMWARE_UPDATE_MESSAGE, "Error: Flash write failed, code=%u, address=0x%08x\n", rc, flashAddr);
return;
}
// Verify written data
if (memcmp(reinterpret_cast<void *>(flashAddr), data, bytesRead) != 0)
{
MessageF(FIRMWARE_UPDATE_MESSAGE, "Error: Verify during flash write failed, address=0x%08x\n", flashAddr);
return;
}
}
else
{
// Fill up the remaining space with zeros
memset(data, 0, sizeof(data[0]) * sizeof(data));
cpu_irq_disable();
flash_write(flashAddr, data, IFLASH_PAGE_SIZE, 0);
cpu_irq_enable();
}
}
// Re-lock the whole area
flash_lock(IAP_FLASH_START, IAP_FLASH_END, nullptr, nullptr);
#else // SAM3X code
for (uint32_t flashAddr = IAP_FLASH_START; flashAddr < IAP_FLASH_END; flashAddr += IFLASH_PAGE_SIZE)
{
const int bytesRead = iapFile->Read(data, IFLASH_PAGE_SIZE);
if (bytesRead > 0)
{
// Do we have to fill up the remaining buffer with zeros?
if (bytesRead != IFLASH_PAGE_SIZE)
{
memset(data + bytesRead, 0, sizeof(data[0]) * (IFLASH_PAGE_SIZE - bytesRead));
}
// Write one page at a time
cpu_irq_disable();
const char* op = "unlock";
uint32_t rc = flash_unlock(flashAddr, flashAddr + IFLASH_PAGE_SIZE - 1, nullptr, nullptr);
if (rc == FLASH_RC_OK)
{
op = "write";
rc = flash_write(flashAddr, data, IFLASH_PAGE_SIZE, 1);
}
if (rc == FLASH_RC_OK)
{
op = "lock";
rc = flash_lock(flashAddr, flashAddr + IFLASH_PAGE_SIZE - 1, nullptr, nullptr);
}
cpu_irq_enable();
if (rc != FLASH_RC_OK)
{
MessageF(FIRMWARE_UPDATE_MESSAGE, "Error: Flash %s failed, code=%u, address=0x%08x\n", op, rc, flashAddr);
return;
}
// Verify written data
if (memcmp(reinterpret_cast<void *>(flashAddr), data, bytesRead) != 0)
{
MessageF(FIRMWARE_UPDATE_MESSAGE, "Error: Verify during flash write failed, address=0x%08x\n", flashAddr);
return;
}
}
else
{
// Fill up the remaining space
memset(data, 0, sizeof(data[0]) * sizeof(data));
cpu_irq_disable();
flash_unlock(flashAddr, flashAddr + IFLASH_PAGE_SIZE - 1, nullptr, nullptr);
flash_write(flashAddr, data, IFLASH_PAGE_SIZE, 1);
flash_lock(flashAddr, flashAddr + IFLASH_PAGE_SIZE - 1, nullptr, nullptr);
cpu_irq_enable();
}
}
#endif
iapFile->Close();
Message(FIRMWARE_UPDATE_MESSAGE, "Updating main firmware\n");
// Allow time for the firmware update message to be sent
uint32_t now = millis();
while (FlushMessages() && millis() - now < 2000) { }
// Step 2 - Let the firmware do whatever is necessary before we exit this program
reprap.Exit();
// Step 3 - Reallocate the vector table and program entry point to the new IAP binary
// This does essentially what the Atmel AT02333 paper suggests (see 3.2.2 ff)
// Disable all IRQs
cpu_irq_disable();
for(size_t i = 0; i < 8; i++)
{
NVIC->ICER[i] = 0xFFFFFFFF; // Disable IRQs
NVIC->ICPR[i] = 0xFFFFFFFF; // Clear pending IRQs
}
// Our SAM3X doesn't support disabling the watchdog, so leave it running.
// The IAP binary will kick it as soon as it's started
// Modify vector table location
__DSB();
__ISB();
SCB->VTOR = ((uint32_t)IAP_FLASH_START & SCB_VTOR_TBLOFF_Msk);
__DSB();
__ISB();
// Reset stack pointer, enable IRQs again and start the new IAP binary
__set_MSP(*(uint32_t *)IAP_FLASH_START);
cpu_irq_enable();
void *entryPoint = (void *)(*(uint32_t *)(IAP_FLASH_START + 4));
goto *entryPoint;
}
// Send the beep command to the aux channel. There is no flow control on this port, so it can't block for long.
void Platform::Beep(int freq, int ms)
{
MessageF(AUX_MESSAGE, "{\"beep_freq\":%d,\"beep_length\":%d}\n", freq, ms);
}
// Send a short message to the aux channel. There is no flow control on this port, so it can't block for long.
void Platform::SendMessage(const char* msg)
{
OutputBuffer *buf;
if (OutputBuffer::Allocate(buf))
{
buf->copy("{\"message\":");
buf->EncodeString(msg, strlen(msg), false, true);
buf->cat("}\n");
Message(AUX_MESSAGE, buf);
}
}
// Note: the use of floating point time will cause the resolution to degrade over time.
// For example, 1ms time resolution will only be available for about half an hour from startup.
// Personally, I (dc42) would rather just maintain and provide the time in milliseconds in a uint32_t.
// This would wrap round after about 49 days, but that isn't difficult to handle.
float Platform::Time()
{
unsigned long now = micros();
if (now < lastTimeCall) // Has timer overflowed?
{
addToTime += ((float) ULONG_MAX) * TIME_FROM_REPRAP;