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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
|
/****************************************************************************************************
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 "Platform.h"
#include "Heating/Heat.h"
#include "Movement/DDA.h"
#include "Movement/Move.h"
#include "Movement/StepTimer.h"
#include "Tools/Tool.h"
#include "Endstops/ZProbe.h"
#include "Network.h"
#include "PrintMonitor.h"
#include "FilamentMonitors/FilamentMonitor.h"
#include "RepRap.h"
#include "Scanner.h"
#include "Version.h"
#include "Logger.h"
#include "Tasks.h"
#include "Hardware/DmacManager.h"
#include "Hardware/Cache.h"
#include "Math/Isqrt.h"
#include "Hardware/I2C.h"
#ifndef __LPC17xx__
# include "sam/drivers/tc/tc.h"
# include "sam/drivers/hsmci/hsmci.h"
#else
# include "LPC/BoardConfig.h"
#endif
#include "sd_mmc.h"
#if SUPPORT_TMC2660
# include "Movement/StepperDrivers/TMC2660.h"
#endif
#if SUPPORT_TMC22xx
# include "Movement/StepperDrivers/TMC22xx.h"
#endif
#if SUPPORT_TMC51xx
# include "Movement/StepperDrivers/TMC51xx.h"
#endif
#if HAS_WIFI_NETWORKING
# include "FirmwareUpdater.h"
#endif
#if SUPPORT_12864_LCD
# include "Display/Display.h"
#endif
#if HAS_LINUX_INTERFACE
# include "Linux/LinuxInterface.h"
#endif
#if HAS_NETWORKING && !HAS_LEGACY_NETWORKING
# include "Networking/HttpResponder.h"
# include "Networking/FtpResponder.h"
# include "Networking/TelnetResponder.h"
#endif
#if SUPPORT_CAN_EXPANSION
# include "CAN/CanMessageGenericConstructor.h"
# include "CAN/CanInterface.h"
#endif
#include <climits>
#include <utility> // for std::swap
#if !defined(HAS_LWIP_NETWORKING) || !defined(HAS_WIFI_NETWORKING) || !defined(HAS_CPU_TEMP_SENSOR) || !defined(HAS_HIGH_SPEED_SD) \
|| !defined(HAS_SMART_DRIVERS) || !defined(HAS_STALL_DETECT) || !defined(HAS_VOLTAGE_MONITOR) || !defined(HAS_12V_MONITOR) || !defined(HAS_VREF_MONITOR) \
|| !defined(SUPPORT_NONLINEAR_EXTRUSION) || !defined(SUPPORT_ASYNC_MOVES) || !defined(HAS_MASS_STORAGE)
# error Missing feature definition
#endif
#if HAS_VOLTAGE_MONITOR
inline constexpr float AdcReadingToPowerVoltage(uint16_t adcVal)
{
return adcVal * (PowerMonitorVoltageRange/(1u << AdcBits));
}
inline constexpr uint16_t PowerVoltageToAdcReading(float voltage)
{
return (uint16_t)(voltage * ((1u << AdcBits)/PowerMonitorVoltageRange));
}
constexpr uint16_t driverPowerOnAdcReading = PowerVoltageToAdcReading(10.0); // minimum voltage at which we initialise the drivers
constexpr uint16_t driverPowerOffAdcReading = PowerVoltageToAdcReading(9.5); // voltages below this flag the drivers as unusable
# if ENFORCE_MAX_VIN
constexpr uint16_t driverOverVoltageAdcReading = PowerVoltageToAdcReading(29.0); // voltages above this cause driver shutdown
constexpr uint16_t driverNormalVoltageAdcReading = PowerVoltageToAdcReading(27.5); // voltages at or below this are normal
# endif
#endif
#if HAS_12V_MONITOR
inline constexpr float AdcReadingToV12Voltage(uint16_t adcVal)
{
return adcVal * (V12MonitorVoltageRange/(1u << AdcBits));
}
inline constexpr uint16_t V12VoltageToAdcReading(float voltage)
{
return (uint16_t)(voltage * ((1u << AdcBits)/V12MonitorVoltageRange));
}
constexpr uint16_t driverV12OnAdcReading = V12VoltageToAdcReading(10.0); // minimum voltage at which we initialise the drivers
constexpr uint16_t driverV12OffAdcReading = V12VoltageToAdcReading(9.5); // voltages below this flag the drivers as unusable
#endif
const float MinStepPulseTiming = 0.2; // we assume that we always generate step high and low times at least this wide without special action
// Global variable for debugging in tricky situations e.g. within ISRs
int debugLine = 0;
// Global functions
// 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!
extern "C" void UrgentInit()
{
#if defined(DUET_NG)
// When the reset button is pressed on pre-production Duet WiFi boards, if the TMC2660 drivers were previously enabled then we get
// uncommanded motor movements if the STEP lines pick up any noise. Try to reduce that by initialising the pins that control the drivers early here.
// On the production boards the ENN line is pulled high by an external pullup resistor and that prevents motor movements.
for (size_t drive = 0; drive < NumDirectDrivers; ++drive)
{
pinMode(STEP_PINS[drive], OUTPUT_LOW);
pinMode(DIRECTION_PINS[drive], OUTPUT_LOW);
pinMode(ENABLE_PINS[drive], OUTPUT_HIGH);
}
#endif
#if defined(DUET_M)
// The prototype boards don't have a pulldown on LCD_BEEP, which causes a hissing sound from the beeper on the 12864 display until the pin is initialised
pinMode(LcdBeepPin, OUTPUT_LOW);
// Set the 12864 display CS pin low to prevent it from receiving garbage due to other SPI traffic
pinMode(LcdCSPin, OUTPUT_LOW);
// On the prototype boards the stepper driver expansion ports don't have external pullup resistors on their enable pins
pinMode(ENABLE_PINS[5], OUTPUT_HIGH);
pinMode(ENABLE_PINS[6], OUTPUT_HIGH);
#endif
}
DriversBitmap AxisDriversConfig::GetDriversBitmap() const noexcept
{
DriversBitmap rslt = 0;
for (size_t i = 0; i < numDrivers; ++i)
{
#if SUPPORT_CAN_EXPANSION
if (driverNumbers[i].IsLocal())
#endif
{
SetBit(rslt, driverNumbers[i].localDriver);
}
}
return rslt;
}
//*************************************************************************************************
// Platform class
#if SUPPORT_OBJECT_MODEL
// Object model table and functions
// Note: if using GCC version 7.3.1 20180622 and lambda functions are used in this table, you must compile this file with option -std=gnu++17.
// Otherwise the table will be allocate in RAM instead of flash, which wastes too much RAM.
// Macro to build a standard lambda function that includes the necessary type conversions
#define OBJECT_MODEL_FUNC(...) OBJECT_MODEL_FUNC_BODY(Platform, __VA_ARGS__)
constexpr ObjectModelTableEntry Platform::objectModelTable[] =
{
// 0. boards[] members
{ "firmwareFileName", OBJECT_MODEL_FUNC_NOSELF(IAP_FIRMWARE_FILE), ObjectModelEntryFlags::none },
#if HAS_LINUX_INTERFACE
{ "iapFileNameSBC", OBJECT_MODEL_FUNC_NOSELF(IAP_UPDATE_FILE_SBC), ObjectModelEntryFlags::none },
#endif
{ "iapFileNameSD", OBJECT_MODEL_FUNC_NOSELF(IAP_UPDATE_FILE), ObjectModelEntryFlags::none },
{ "maxHeaters", OBJECT_MODEL_FUNC_NOSELF((int32_t)MaxHeaters), ObjectModelEntryFlags::verbose },
{ "maxMotors", OBJECT_MODEL_FUNC_NOSELF((int32_t)NumDirectDrivers), ObjectModelEntryFlags::verbose },
{ "mcuTemp", OBJECT_MODEL_FUNC(self, 1), ObjectModelEntryFlags::live },
# ifdef DUET_NG
{ "name", OBJECT_MODEL_FUNC(self->GetBoardName()), ObjectModelEntryFlags::none },
{ "shortName", OBJECT_MODEL_FUNC(self->GetBoardShortName()), ObjectModelEntryFlags::none },
# else
{ "name", OBJECT_MODEL_FUNC_NOSELF(BOARD_NAME), ObjectModelEntryFlags::none },
{ "shortName", OBJECT_MODEL_FUNC_NOSELF(BOARD_SHORT_NAME), ObjectModelEntryFlags::none },
# endif
#if HAS_12V_MONITOR
{ "v12", OBJECT_MODEL_FUNC(self, 3), ObjectModelEntryFlags::live },
#endif
{ "vIn", OBJECT_MODEL_FUNC(self, 2), ObjectModelEntryFlags::live },
// 1. mcuTemp members
{ "current", OBJECT_MODEL_FUNC(self->GetMcuTemperatures().current), ObjectModelEntryFlags::live },
{ "max", OBJECT_MODEL_FUNC(self->GetMcuTemperatures().max), ObjectModelEntryFlags::none },
{ "min", OBJECT_MODEL_FUNC(self->GetMcuTemperatures().min), ObjectModelEntryFlags::none },
// 2. vIn members
{ "current", OBJECT_MODEL_FUNC(self->GetCurrentPowerVoltage()), ObjectModelEntryFlags::live },
{ "max", OBJECT_MODEL_FUNC(self->GetPowerVoltages().max), ObjectModelEntryFlags::none },
{ "min", OBJECT_MODEL_FUNC(self->GetPowerVoltages().min), ObjectModelEntryFlags::none },
#if HAS_12V_MONITOR
// 3. v12 members
{ "current", OBJECT_MODEL_FUNC(self->GetV12Voltages().current), ObjectModelEntryFlags::live },
{ "max", OBJECT_MODEL_FUNC(self->GetV12Voltages().max), ObjectModelEntryFlags::none },
{ "min", OBJECT_MODEL_FUNC(self->GetV12Voltages().min), ObjectModelEntryFlags::none },
#endif
};
constexpr uint8_t Platform::objectModelTableDescriptor[] =
{
3 + HAS_12V_MONITOR,
8 + HAS_LINUX_INTERFACE + HAS_12V_MONITOR,
3,
3,
#if HAS_12V_MONITOR
3
#endif
};
DEFINE_GET_OBJECT_MODEL_TABLE(Platform)
// This is called by the OMT in class RepRap to get the size of the Boards array
// For now only main board data is returned
size_t Platform::GetNumBoards() const noexcept
{
return 1;
}
#endif
Platform::Platform() noexcept :
#if HAS_MASS_STORAGE
logger(nullptr),
#endif
board(DEFAULT_BOARD_TYPE), active(false), errorCodeBits(0),
#if HAS_SMART_DRIVERS
nextDriveToPoll(0),
#endif
lastFanCheckTime(0), auxGCodeReply(nullptr),
#if HAS_MASS_STORAGE
sysDir(nullptr),
#endif
tickState(0), debugCode(0),
lastWarningMillis(0), lastLaserPwm(0.0), deferredPowerDown(false), deliberateError(false)
{
}
// Initialise the Platform. Note: this is the first module to be initialised, so don't call other modules from here!
void Platform::Init() noexcept
{
pinMode(DiagPin, OUTPUT_LOW); // set up diag LED for debugging and turn it off
#if defined(DUET3)
pinMode(PhyResetPin, OUTPUT_LOW); // hold the Ethernet Phy chip in reset, hopefully this will prevent it being too noisy if Ethernet is not enabled
#endif
// Deal with power first (we assume this doesn't depend on identifying the board type)
pinMode(ATX_POWER_PIN, OUTPUT_LOW);
SetBoardType(BoardType::Auto);
#if defined(DUET_NG) || defined(PCCB_10) || defined(PCCB_08_X5)
pinMode(GlobalTmc2660EnablePin, OUTPUT_HIGH);
#endif
#if defined(DUET_M) || defined(PCCB_08) || defined(PCCB_08_X5)
// Make sure the on-board TMC22xx drivers are disabled
pinMode(GlobalTmc22xxEnablePin, OUTPUT_HIGH);
#endif
#if SAME70
DmacManager::Init();
#endif
// Read the unique ID of the MCU, if it has one
#if SAM4E || SAM4S || SAME70
memset(uniqueId, 0, sizeof(uniqueId));
Cache::Disable();
cpu_irq_disable();
const uint32_t rc = flash_read_unique_id(uniqueId, 4);
cpu_irq_enable();
Cache::Enable();
if (rc == 0)
{
// Put the checksum at the end
// We only print 30 5-bit characters = 128 data bits + 22 checksum bits. So compress the 32 checksum bits into 22.
uniqueId[4] = uniqueId[0] ^ uniqueId[1] ^ uniqueId[2] ^ uniqueId[3];
uniqueId[4] ^= (uniqueId[4] >> 10);
// On the Duet Ethernet and SAM E70, use the unique chip ID as most of the MAC address.
// The unique ID is 128 bits long whereas the whole MAC address is only 48 bits,
// so we can't guarantee that each Duet will get a unique MAC address this way.
memset(defaultMacAddress, 0, sizeof(defaultMacAddress));
defaultMacAddress[0] = 0xBE; // use a fixed first byte with the locally-administered bit set
const uint8_t * const idBytes = reinterpret_cast<const uint8_t *>(uniqueId);
for (size_t i = 0; i < 15; ++i)
{
defaultMacAddress[(i % 5) + 1] ^= idBytes[i];
}
}
else
{
ARRAY_INIT(defaultMacAddress, DefaultMacAddress);
}
#endif
// Real-time clock
realTime = 0;
// Comms
baudRates[0] = MAIN_BAUD_RATE;
commsParams[0] = 0;
usbMutex.Create("USB");
#if defined(__LPC17xx__)
SERIAL_MAIN_DEVICE.begin(baudRates[0]);
#else
SERIAL_MAIN_DEVICE.Start(UsbVBusPin);
#endif
#ifdef SERIAL_AUX_DEVICE
baudRates[1] = AUX_BAUD_RATE;
commsParams[1] = 1; // by default we require a checksum on data from the aux port, to guard against overrun errors
auxMutex.Create("Aux");
auxDetected = false;
auxSeq = 0;
SERIAL_AUX_DEVICE.begin(baudRates[1]); // this can't be done in the constructor because the port initialisation in CoreNG isn't complete at that point
#endif
#ifdef SERIAL_AUX2_DEVICE
baudRates[2] = AUX2_BAUD_RATE;
commsParams[2] = 0;
aux2Mutex.Create("Aux2");
SERIAL_AUX2_DEVICE.begin(baudRates[2]);
#endif
// Initialise the IO port subsystem
IoPort::Init();
// File management and SD card interfaces
for (size_t i = 0; i < NumSdCards; ++i)
{
setPullup(SdCardDetectPins[i], true); // setPullup is safe to call with a NoPin argument
}
#if HAS_MASS_STORAGE
MassStorage::Init();
#endif
#ifdef __LPC17xx__
// Load HW pin assignments from sdcard
BoardConfig::Init();
pinMode(ATX_POWER_PIN,(ATX_POWER_INVERTED==false)?OUTPUT_LOW:OUTPUT_HIGH);
#else
// Deal with power first (we assume this doesn't depend on identifying the board type)
pinMode(ATX_POWER_PIN,OUTPUT_LOW);
#endif
// Ethernet networking defaults
ipAddress = DefaultIpAddress;
netMask = DefaultNetMask;
gateWay = DefaultGateway;
// Do hardware dependent initialisation
#if HAS_SMART_DRIVERS
# if defined(DUET_NG)
// Test for presence of a DueX2 or DueX5 expansion board and work out how many TMC2660 drivers we have
expansionBoard = DuetExpansion::DueXnInit();
switch (expansionBoard)
{
case ExpansionBoardType::DueX2:
numSmartDrivers = 7;
break;
case ExpansionBoardType::DueX5:
numSmartDrivers = 10;
break;
case ExpansionBoardType::none:
case ExpansionBoardType::DueX0:
default:
numSmartDrivers = 5; // assume that any additional drivers are dumb enable/step/dir ones
break;
}
DuetExpansion::AdditionalOutputInit();
# elif defined(DUET_M)
numSmartDrivers = MaxSmartDrivers; // for now we assume that expansion drivers are smart too
# elif defined(PCCB)
numSmartDrivers = MaxSmartDrivers;
# elif defined(DUET3)
numSmartDrivers = MaxSmartDrivers;
# endif
#endif
#if defined(DUET_06_085)
ARRAY_INIT(defaultMacAddress, DefaultMacAddress);
// Motor current setting on Duet 0.6 and 0.8.5
I2C::Init();
mcpExpansion.setMCP4461Address(0x2E); // not required for mcpDuet, as this uses the default address
ARRAY_INIT(potWipes, POT_WIPES);
senseResistor = SENSE_RESISTOR;
maxStepperDigipotVoltage = MAX_STEPPER_DIGIPOT_VOLTAGE;
stepperDacVoltageRange = STEPPER_DAC_VOLTAGE_RANGE;
stepperDacVoltageOffset = STEPPER_DAC_VOLTAGE_OFFSET;
#elif defined(__ALLIGATOR__)
pinMode(EthernetPhyResetPin, INPUT); // Init Ethernet Phy Reset Pin
// Alligator Init DAC for motor current vref
ARRAY_INIT(spiDacCS, SPI_DAC_CS);
dacAlligator.Init(spiDacCS[0]);
dacPiggy.Init(spiDacCS[1]);
// Get macaddress from EUI48 eeprom
eui48MacAddress.Init(Eui48csPin);
if (!eui48MacAddress.getEUI48(defaultMacAddress))
{
ARRAY_INIT(defaultMacAddress, DefaultMacAddress);
}
Microstepping::Init(); // Init Motor FAULT detect Pin
pinMode(ExpansionVoltageLevelPin, ExpansionVoltageLevel==3 ? OUTPUT_LOW : OUTPUT_HIGH); // Init Expansion Voltage Level Pin
pinMode(MotorFaultDetectPin,INPUT); // Init Motor FAULT detect Pin
pinMode(ExpansionPiggyDetectPin,INPUT); // Init Expansion Piggy module presence Pin
pinMode(FTDIconverterResetPin,INPUT); // Init FTDI Serial Converter Reset Pin
pinMode(SpiEEPROMcsPin,OUTPUT_HIGH); // Init Spi EEPROM Cs pin, not implemented, default unselected
pinMode(SpiFLASHcsPin,OUTPUT_HIGH); // Init Spi FLASH Cs pin, not implemented, default unselected
#endif
#if defined(__LPC17xx__)
if (hasDriverCurrentControl)
{
mcp4451.begin();
}
Microstepping::Init(); // basic class to remember the Microstepping.
#endif
// Initialise endstops. On Duet 2 this must be done after testing for an expansion board.
endstops.Init();
// Axes
for (size_t axis = 0; axis < MaxAxes; ++axis)
{
axisMinima[axis] = DefaultAxisMinimum;
axisMaxima[axis] = DefaultAxisMaximum;
maxFeedrates[axis] = DefaultXYMaxFeedrate;
accelerations[axis] = DefaultXYAcceleration;
driveStepsPerUnit[axis] = DefaultXYDriveStepsPerUnit;
instantDvs[axis] = DefaultXYInstantDv;
}
// We use different defaults for the Z axis
maxFeedrates[Z_AXIS] = DefaultZMaxFeedrate;
accelerations[Z_AXIS] = DefaultZAcceleration;
driveStepsPerUnit[Z_AXIS] = DefaultZDriveStepsPerUnit;
instantDvs[Z_AXIS] = DefaultZInstantDv;
// Extruders
for (size_t drive = MaxAxes; drive < MaxAxesPlusExtruders; ++drive)
{
maxFeedrates[drive] = DefaultEMaxFeedrate;
accelerations[drive] = DefaultEAcceleration;
driveStepsPerUnit[drive] = DefaultEDriveStepsPerUnit;
instantDvs[drive] = DefaultEInstantDv;
}
minimumMovementSpeed = DefaultMinFeedrate;
axisMaximaProbed = axisMinimaProbed = 0;
idleCurrentFactor = DefaultIdleCurrentFactor;
// Motors
#ifndef __LPC17xx__
// 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;
# ifdef PIOD
PIOD->PIO_OWDR = 0xFFFFFFFF;
# endif
# ifdef PIOE
PIOE->PIO_OWDR = 0xFFFFFFFF;
# endif
#endif
// Clear out the axis and extruder driver bitmaps
for (size_t i = 0; i < MaxAxesPlusExtruders; ++i)
{
driveDriverBits[i] = 0;
}
// Set up the bitmaps for direct driver access
for (size_t driver = 0; driver < NumDirectDrivers; ++driver)
{
driveDriverBits[driver + MaxAxesPlusExtruders] = StepPins::CalcDriverBitmap(driver);
}
// Set up the local drivers
for (size_t driver = 0; driver < NumDirectDrivers; ++driver)
{
directions[driver] = true; // drive moves forwards by default
enableValues[driver] = 0; // assume active low enable signal
// Set up the control pins
pinMode(STEP_PINS[driver], OUTPUT_LOW);
pinMode(DIRECTION_PINS[driver], OUTPUT_LOW);
#if !defined(DUET3)
pinMode(ENABLE_PINS[driver], OUTPUT_HIGH); // this is OK for the TMC2660 CS pins too
#endif
#ifndef __LPC17xx__
const PinDescription& pinDesc = g_APinDescription[STEP_PINS[driver]];
pinDesc.pPort->PIO_OWER = pinDesc.ulPin; // enable parallel writes to the step pins
#endif
}
// Set up the axis+extruder arrays
for (size_t drive = 0; drive < MaxAxesPlusExtruders; drive++)
{
driverState[drive] = DriverStatus::disabled;
driveDriverBits[drive] = 0;
motorCurrents[drive] = 0.0;
motorCurrentFraction[drive] = 1.0;
standstillCurrentPercent[drive] = DefaultStandstillCurrentPercent;
microstepping[drive] = 16 | 0x8000; // x16 with interpolation
}
// Set up default axis mapping
for (size_t axis = 0; axis < MinAxes; ++axis)
{
#ifdef PCCB
const size_t driver = (axis + 1) % 3; // on PCCB we map axes X Y Z to drivers 1 2 0
#else
const size_t driver = axis; // on most boards we map axes straight through to drives
#endif
axisDrivers[axis].numDrivers = 1;
axisDrivers[axis].driverNumbers[0].SetLocal(driver);
driveDriverBits[axis] = StepPins::CalcDriverBitmap(driver); // overwrite the default value set up earlier
}
for (size_t axis = MinAxes; axis < MaxAxes; ++axis)
{
axisDrivers[axis].numDrivers = 0;
}
// Set up default extruders
for (size_t extr = 0; extr < MaxExtruders; ++extr)
{
extruderDrivers[extr].SetLocal(extr + MinAxes); // set up default extruder drive mapping
driveDriverBits[ExtruderToLogicalDrive(extr)] = StepPins::CalcDriverBitmap(extr + MinAxes);
pressureAdvance[extr] = 0.0;
#if SUPPORT_NONLINEAR_EXTRUSION
nonlinearExtrusionA[extr] = nonlinearExtrusionB[extr] = 0.0;
nonlinearExtrusionLimit[extr] = DefaultNonlinearExtrusionLimit;
#endif
}
for (uint32_t& entry : slowDriverStepTimingClocks)
{
entry = 0; // reset all to zero as we have no known slow drivers yet
}
slowDriversBitmap = 0; // assume no drivers need extended step pulse timing
EnableAllSteppingDrivers(); // no drivers disabled
driversPowered = false;
#if HAS_SMART_DRIVERS
// Initialise TMC driver module
# if SUPPORT_TMC51xx
SmartDrivers::Init();
# else
SmartDrivers::Init(ENABLE_PINS, numSmartDrivers);
# endif
temperatureShutdownDrivers = temperatureWarningDrivers = shortToGroundDrivers = openLoadADrivers = openLoadBDrivers = notOpenLoadADrivers = notOpenLoadBDrivers = 0;
#endif
#if HAS_STALL_DETECT
stalledDrivers = 0;
logOnStallDrivers = pauseOnStallDrivers = rehomeOnStallDrivers = 0;
stalledDriversToLog = stalledDriversToPause = stalledDriversToRehome = 0;
#endif
#if HAS_VOLTAGE_MONITOR
autoSaveEnabled = false;
autoSaveState = AutoSaveState::starting;
#endif
#if HAS_SMART_DRIVERS && (HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR)
warnDriversNotPowered = false;
#endif
extrusionAncilliaryPwmValue = 0.0;
// Initialise the configured heaters to just the default bed heater (there are no default chamber heaters)
configuredHeaters = 0;
#ifndef DUET3
if (DefaultBedHeater >= 0)
{
SetBit(configuredHeaters, DefaultBedHeater);
}
#endif
// 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 (Pin p : SpiTempSensorCsPins)
{
pinMode(p, INPUT_PULLUP);
}
// If MISO from a MAX31856 board breaks after initialising the MAX31856 then if MISO floats low and reads as all zeros, this looks like a temperature of 0C and no error.
// Enable the pullup resistor, with luck this will make it float high instead.
#if SAM3XA
pinMode(APIN_SHARED_SPI_MISO, INPUT_PULLUP);
#elif defined(__LPC17xx__)
// nothing to do here
#else
pinMode(APIN_USART_SSPI_MISO, INPUT_PULLUP);
#endif
#ifdef PCCB
// Setup the LED ports as GPIO ports
for (size_t i = 0; i < ARRAY_SIZE(DefaultGpioPinNames); ++i)
{
String<1> dummy;
gpioPorts[i].port.AssignPort(DefaultGpioPinNames[i], dummy.GetRef(), PinUsedBy::gpio, PinAccess::pwm);
}
#endif
for (size_t thermistor = 0; thermistor < NumThermistorInputs; thermistor++)
{
// TODO use ports for these?
pinMode(TEMP_SENSE_PINS[thermistor], AIN);
filteredAdcChannels[thermistor] = PinToAdcChannel(TEMP_SENSE_PINS[thermistor]); // translate the pin number to the SAM ADC channel number;
}
#if HAS_VREF_MONITOR
// Set up the VSSA and VREF measurement channels
pinMode(VssaSensePin, AIN);
filteredAdcChannels[VssaFilterIndex] = PinToAdcChannel(VssaSensePin); // translate the pin number to the SAM ADC channel number
pinMode(VrefSensePin, AIN);
filteredAdcChannels[VrefFilterIndex] = PinToAdcChannel(VrefSensePin); // translate the pin number to the SAM ADC channel number
#endif
#if HAS_CPU_TEMP_SENSOR
filteredAdcChannels[CpuTempFilterIndex] = GetTemperatureAdcChannel();
#endif
// Initialise all the ADC filters and enable the corresponding ADC channels
for (size_t filter = 0; filter < NumAdcFilters; ++filter)
{
adcFilters[filter].Init(0);
AnalogInEnableChannel(filteredAdcChannels[filter], true);
}
// Hotend configuration
nozzleDiameter = NOZZLE_DIAMETER;
filamentWidth = FILAMENT_WIDTH;
#if HAS_CPU_TEMP_SENSOR
// MCU temperature monitoring
highestMcuTemperature = 0; // the highest output we have seen from the ADC filter
lowestMcuTemperature = 4095 * ThermistorAverageReadings; // the lowest output we have seen from the ADC filter
mcuTemperatureAdjust = 0.0;
#endif
#if HAS_VOLTAGE_MONITOR
// Power monitoring
vInMonitorAdcChannel = PinToAdcChannel(PowerMonitorVinDetectPin);
pinMode(PowerMonitorVinDetectPin, AIN);
AnalogInEnableChannel(vInMonitorAdcChannel, true);
currentVin = highestVin = 0;
lowestVin = 9999;
numVinUnderVoltageEvents = previousVinUnderVoltageEvents = numVinOverVoltageEvents = previousVinOverVoltageEvents = 0;
#endif
#if HAS_12V_MONITOR
// Power monitoring
v12MonitorAdcChannel = PinToAdcChannel(PowerMonitorV12DetectPin);
pinMode(PowerMonitorV12DetectPin, AIN);
AnalogInEnableChannel(v12MonitorAdcChannel, true);
currentV12 = highestV12 = 0;
lowestV12 = 9999;
numV12UnderVoltageEvents = previousV12UnderVoltageEvents = 0;
#endif
// Kick everything off
InitialiseInterrupts();
#ifdef DUET_NG
DuetExpansion::DueXnTaskInit(); // must initialise interrupt priorities before calling this
#endif
active = true;
}
// 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) noexcept
{
MessageF(AuxMessage, "{\"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::SendAuxMessage(const char* msg) noexcept
{
#ifdef SERIAL_AUX_DEVICE
OutputBuffer *buf;
if (OutputBuffer::Allocate(buf))
{
buf->copy("{\"message\":");
buf->EncodeString(msg, false);
buf->cat("}\n");
auxOutput.Push(buf);
FlushAuxMessages();
}
#endif
}
void Platform::Exit() noexcept
{
StopLogging();
#if HAS_MASS_STORAGE
MassStorage::CloseAllFiles();
#endif
#if HAS_SMART_DRIVERS
SmartDrivers::Exit();
#endif
// Release the aux output stack (should release the others too!)
while (auxGCodeReply != nullptr)
{
auxGCodeReply = OutputBuffer::Release(auxGCodeReply);
}
// Stop processing data. Don't try to send a message because it will probably never get there.
active = false;
// Close down USB and serial ports
SERIAL_MAIN_DEVICE.end();
#ifdef SERIAL_AUX_DEVICE
SERIAL_AUX_DEVICE.end();
#endif
#ifdef SERIAL_AUX2_DEVICE
SERIAL_AUX2_DEVICE.end();
#endif
}
void Platform::SetIPAddress(IPAddress ip) noexcept
{
ipAddress = ip;
reprap.GetNetwork().SetEthernetIPAddress(ipAddress, gateWay, netMask);
}
void Platform::SetGateWay(IPAddress gw) noexcept
{
gateWay = gw;
reprap.GetNetwork().SetEthernetIPAddress(ipAddress, gateWay, netMask);
}
void Platform::SetNetMask(IPAddress nm) noexcept
{
netMask = nm;
reprap.GetNetwork().SetEthernetIPAddress(ipAddress, gateWay, netMask);
}
// Flush messages to aux, returning true if there is more to send
bool Platform::FlushAuxMessages() noexcept
{
#ifdef SERIAL_AUX_DEVICE
// Write non-blocking data to the AUX line
MutexLocker lock(auxMutex);
OutputBuffer *auxOutputBuffer = auxOutput.GetFirstItem();
if (auxOutputBuffer != nullptr)
{
const size_t bytesToWrite = min<size_t>(SERIAL_AUX_DEVICE.canWrite(), auxOutputBuffer->BytesLeft());
if (bytesToWrite > 0)
{
SERIAL_AUX_DEVICE.write(auxOutputBuffer->Read(bytesToWrite), bytesToWrite);
}
if (auxOutputBuffer->BytesLeft() == 0)
{
auxOutput.ReleaseFirstItem();
}
}
return auxOutput.GetFirstItem() != nullptr;
#else
return false;
#endif
}
// Flush messages to USB and aux, returning true if there is more to send
bool Platform::FlushMessages() noexcept
{
const bool auxHasMore = FlushAuxMessages();
#ifdef SERIAL_AUX2_DEVICE
// Write non-blocking data to the second AUX line
bool aux2HasMore;
{
MutexLocker lock(aux2Mutex);
OutputBuffer *aux2OutputBuffer = aux2Output.GetFirstItem();
if (aux2OutputBuffer != nullptr)
{
const size_t bytesToWrite = min<size_t>(SERIAL_AUX2_DEVICE.canWrite(), aux2OutputBuffer->BytesLeft());
if (bytesToWrite > 0)
{
SERIAL_AUX2_DEVICE.write(aux2OutputBuffer->Read(bytesToWrite), bytesToWrite);
}
if (aux2OutputBuffer->BytesLeft() == 0)
{
aux2Output.ReleaseFirstItem();
}
}
aux2HasMore = (aux2Output.GetFirstItem() != nullptr);
}
#endif
// Write non-blocking data to the USB line
bool usbHasMore = !usbOutput.IsEmpty(); // test first to see if we can avoid getting the mutex
if (usbHasMore)
{
MutexLocker lock(usbMutex);
OutputBuffer *usbOutputBuffer = usbOutput.GetFirstItem();
if (usbOutputBuffer == nullptr)
{
(void) usbOutput.Pop();
}
else if (!SERIAL_MAIN_DEVICE.IsConnected())
{
// If the USB port is not opened, free the data left for writing
OutputBuffer::ReleaseAll(usbOutputBuffer);
(void) usbOutput.Pop();
}
else
{
// Write as much data as we can...
const size_t bytesToWrite = min<size_t>(SERIAL_MAIN_DEVICE.canWrite(), usbOutputBuffer->BytesLeft());
if (bytesToWrite != 0)
{
SERIAL_MAIN_DEVICE.write(usbOutputBuffer->Read(bytesToWrite), bytesToWrite);
}
if (usbOutputBuffer->BytesLeft() == 0)
{
usbOutput.ReleaseFirstItem();
}
else
{
usbOutput.ApplyTimeout(SERIAL_MAIN_TIMEOUT);
}
}
usbHasMore = !usbOutput.IsEmpty();
}
return auxHasMore
#ifdef SERIAL_AUX2_DEVICE
|| aux2HasMore
#endif
|| usbHasMore;
}
void Platform::Spin() noexcept
{
if (!active)
{
return;
}
#if defined(DUET3) || defined(__LPC17xx__)
// Blink the LED at about 2Hz. Duet 3 expansion boards will blink in sync when they have established clock sync with us.
digitalWrite(DiagPin, (StepTimer::GetTimerTicks() & (1u << 19)) != 0);
#endif
#if HAS_MASS_STORAGE
MassStorage::Spin();
#endif
// Try to flush messages to serial ports
(void)FlushMessages();
// Check the MCU max and min temperatures
#if HAS_CPU_TEMP_SENSOR
if (adcFilters[CpuTempFilterIndex].IsValid())
{
const uint32_t currentMcuTemperature = adcFilters[CpuTempFilterIndex].GetSum();
if (currentMcuTemperature > highestMcuTemperature)
{
highestMcuTemperature= currentMcuTemperature;
}
if (currentMcuTemperature < lowestMcuTemperature)
{
lowestMcuTemperature = currentMcuTemperature;
}
}
#endif
// Diagnostics test
if (debugCode == (unsigned int)DiagnosticTestType::TestSpinLockup)
{
for (;;) {}
}
// Check whether the TMC drivers need to be initialised.
// The tick ISR also looks for over-voltage events, but it just disables the driver without changing driversPowerd or numVinOverVoltageEvents
if (driversPowered)
{
#if HAS_VOLTAGE_MONITOR
if (currentVin < driverPowerOffAdcReading)
{
driversPowered = false;
++numVinUnderVoltageEvents;
lastVinUnderVoltageValue = currentVin; // save this because the voltage may have changed by the time we report it
}
# if ENFORCE_MAX_VIN
else if (currentVin > driverOverVoltageAdcReading)
{
driversPowered = false;
++numVinOverVoltageEvents;
lastVinOverVoltageValue = currentVin; // save this because the voltage may have changed by the time we report it
}
# endif
else
#endif
#if HAS_12V_MONITOR
if (currentV12 < driverV12OffAdcReading)
{
driversPowered = false;
++numV12UnderVoltageEvents;
lastV12UnderVoltageValue = currentV12; // save this because the voltage may have changed by the time we report it
}
else
#endif
{
#if HAS_SMART_DRIVERS
// Check one TMC2660 or TMC2224 for temperature warning or temperature shutdown
if (enableValues[nextDriveToPoll] >= 0) // don't poll driver if it is flagged "no poll"
{
const uint32_t stat = SmartDrivers::GetAccumulatedStatus(nextDriveToPoll, 0);
const DriversBitmap mask = MakeBitmap<DriversBitmap>(nextDriveToPoll);
if (stat & TMC_RR_OT)
{
temperatureShutdownDrivers |= mask;
}
else if (stat & TMC_RR_OTPW)
{
temperatureWarningDrivers |= mask;
}
if (stat & TMC_RR_S2G)
{
shortToGroundDrivers |= mask;
}
else
{
shortToGroundDrivers &= ~mask;
}
// The driver often produces a transient open-load error, especially in stealthchop mode, so we require the condition to persist before we report it.
// Also, false open load indications persist when in standstill, if the phase has zero current in that position
if ((stat & TMC_RR_OLA) != 0)
{
if (!openLoadATimer.IsRunning())
{
openLoadATimer.Start();
openLoadADrivers = notOpenLoadADrivers = 0;
}
openLoadADrivers |= mask;
}
else if (openLoadATimer.IsRunning())
{
notOpenLoadADrivers |= mask;
if ((openLoadADrivers & ~notOpenLoadADrivers) == 0)
{
openLoadATimer.Stop();
}
}
if ((stat & TMC_RR_OLB) != 0)
{
if (!openLoadBTimer.IsRunning())
{
openLoadBTimer.Start();
openLoadBDrivers = notOpenLoadBDrivers = 0;
}
openLoadBDrivers |= mask;
}
else if (openLoadBTimer.IsRunning())
{
notOpenLoadBDrivers |= mask;
if ((openLoadBDrivers & ~notOpenLoadBDrivers) == 0)
{
openLoadBTimer.Stop();
}
}
# if HAS_STALL_DETECT
if ((stat & TMC_RR_SG) != 0)
{
if ((stalledDrivers & mask) == 0)
{
// This stall is new so check whether we need to perform some action in response to the stall
if ((rehomeOnStallDrivers & mask) != 0)
{
stalledDriversToRehome |= mask;
}
else if ((pauseOnStallDrivers & mask) != 0)
{
stalledDriversToPause |= mask;
}
else if ((logOnStallDrivers & mask) != 0)
{
stalledDriversToLog |= mask;
}
}
stalledDrivers |= mask;
}
else
{
stalledDrivers &= ~mask;
}
# endif
}
# if HAS_STALL_DETECT
// Action any pause or rehome actions due to motor stalls. This may have to be done more than once.
if (stalledDriversToRehome != 0)
{
if (reprap.GetGCodes().ReHomeOnStall(stalledDriversToRehome))
{
stalledDriversToRehome = 0;
}
}
else if (stalledDriversToPause != 0)
{
if (reprap.GetGCodes().PauseOnStall(stalledDriversToPause))
{
stalledDriversToPause = 0;
}
}
# endif
// Advance drive number ready for next time
++nextDriveToPoll;
if (nextDriveToPoll == numSmartDrivers)
{
nextDriveToPoll = 0;
}
#endif // HAS_SMART_DRIVERS
}
}
#if HAS_VOLTAGE_MONITOR && HAS_12V_MONITOR
else if (currentVin >= driverPowerOnAdcReading && currentV12 >= driverV12OnAdcReading
# if ENFORCE_MAX_VIN
&& currentVin <= driverNormalVoltageAdcReading
# endif
)
#elif HAS_VOLTAGE_MONITOR
else if (currentVin >= driverPowerOnAdcReading
# if ENFORCE_MAX_VIN
&& currentVin <= driverNormalVoltageAdcReading
# endif
)
#elif HAS_12V_MONITOR
else if (currentV12 >= driverV12OnAdcReading)
#else
else
#endif
{
driversPowered = true;
#if HAS_SMART_DRIVERS
openLoadATimer.Stop();
openLoadBTimer.Stop();
temperatureShutdownDrivers = temperatureWarningDrivers = shortToGroundDrivers = openLoadADrivers = openLoadBDrivers = notOpenLoadADrivers = notOpenLoadBDrivers = 0;
#endif
}
#if HAS_SMART_DRIVERS
SmartDrivers::Spin(driversPowered);
#endif
const uint32_t now = millis();
// Update the time
if (IsDateTimeSet() && now - timeLastUpdatedMillis >= 1000)
{
++realTime; // this assumes that time_t is a seconds-since-epoch counter, which is not guaranteed by the C standard
timeLastUpdatedMillis += 1000;
}
// Thermostatically-controlled fans (do this after getting TMC driver status)
if (now - lastFanCheckTime >= FanCheckInterval)
{
lastFanCheckTime = now;
bool thermostaticFanRunning = reprap.GetFansManager().CheckFans();
if (deferredPowerDown && !thermostaticFanRunning)
{
AtxPowerOff(false);
}
// Check whether it is time to report any faults (do this after checking fans in case driver cooling fans are turned on)
if (now - lastWarningMillis > MinimumWarningInterval)
{
bool reported = false;
#if HAS_SMART_DRIVERS
ReportDrivers(ErrorMessage, shortToGroundDrivers, "short-to-ground", reported);
ReportDrivers(ErrorMessage, temperatureShutdownDrivers, "over temperature shutdown", reported);
if (openLoadATimer.CheckAndStop(OpenLoadTimeout))
{
ReportDrivers(WarningMessage, openLoadADrivers, "motor phase A may be disconnected", reported);
}
if (openLoadBTimer.CheckAndStop(OpenLoadTimeout))
{
ReportDrivers(WarningMessage, openLoadBDrivers, "motor phase B may be disconnected", reported);
}
// Don't warn about a hot driver if we recently turned on a fan to cool it
if (temperatureWarningDrivers != 0)
{
const DriversBitmap driversMonitored[NumTmcDriversSenseChannels] =
# ifdef DUET_NG
{ LowestNBits<DriversBitmap>(5), LowestNBits<DriversBitmap>(5) << 5 }; // first channel is Duet, second is DueX5
# elif defined(DUET_M)
{ LowestNBits<DriversBitmap>(5), LowestNBits<DriversBitmap>(2) << 5 }; // first channel is Duet, second is daughter board
# else
{ LowestNBits<DriversBitmap>(NumDirectDrivers) };
# endif
for (unsigned int i = 0; i < NumTmcDriversSenseChannels; ++i)
{
if (driversFanTimers[i].IsRunning())
{
const bool timedOut = driversFanTimers[i].CheckAndStop(DriverCoolingTimeout);
if (!timedOut)
{
temperatureWarningDrivers &= ~driversMonitored[i];
}
}
}
ReportDrivers(WarningMessage, temperatureWarningDrivers, "high temperature", reported);
}
#endif
#if HAS_STALL_DETECT
// Check for stalled drivers that need to be reported and logged
if (stalledDriversToLog != 0 && reprap.GetGCodes().IsReallyPrinting())
{
String<StringLength100> scratchString;
ListDrivers(scratchString.GetRef(), stalledDriversToLog);
stalledDriversToLog = 0;
float liveCoordinates[MaxAxesPlusExtruders];
reprap.GetMove().LiveCoordinates(liveCoordinates, reprap.GetCurrentTool());
MessageF(WarningMessage, "Driver(s)%s stalled at Z height %.2f", scratchString.c_str(), (double)liveCoordinates[Z_AXIS]);
reported = true;
}
#endif
#if HAS_VOLTAGE_MONITOR
if (numVinOverVoltageEvents != previousVinOverVoltageEvents)
{
MessageF(WarningMessage, "VIN over-voltage event (%.1fV)", (double)AdcReadingToPowerVoltage(lastVinOverVoltageValue));
previousVinOverVoltageEvents = numVinOverVoltageEvents;
reported = true;
}
if (numVinUnderVoltageEvents != previousVinUnderVoltageEvents)
{
MessageF(WarningMessage, "VIN under-voltage event (%.1fV)", (double)AdcReadingToPowerVoltage(lastVinUnderVoltageValue));
previousVinUnderVoltageEvents = numVinUnderVoltageEvents;
reported = true;
}
#endif
#if HAS_12V_MONITOR
if (numV12UnderVoltageEvents != previousV12UnderVoltageEvents)
{
MessageF(WarningMessage, "12V under-voltage event (%.1fV)", (double)AdcReadingToPowerVoltage(lastV12UnderVoltageValue));
previousV12UnderVoltageEvents = numV12UnderVoltageEvents;
reported = true;
}
#endif
// Check for a VSSA fault
#if HAS_VREF_MONITOR
constexpr uint32_t MaxVssaFilterSum = (15 * (1u << AdcBits) * ThermistorAverageReadings * 4)/2200; // VSSA fuse should have <= 15 ohms resistance
if (adcFilters[VssaFilterIndex].GetSum() > MaxVssaFilterSum)
{
Message(ErrorMessage, "VSSA fault, check thermistor wiring\n");
reported = true;
}
#elif defined(DUET_NG)
if ( (board == BoardType::DuetWiFi_102 || board == BoardType::DuetEthernet_102)
&& digitalRead(VssaSensePin)
)
{
Message(ErrorMessage, "VSSA fault, check thermistor wiring\n");
reported = true;
}
#endif
#if HAS_SMART_DRIVERS && (HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR)
// Check for attempts to move motors when not powered
if (warnDriversNotPowered)
{
Message(ErrorMessage, "Attempt to move motors when VIN is not in range\n");
warnDriversNotPowered = false;
reported = true;
}
#endif
if (reported)
{
lastWarningMillis = now;
}
}
}
#if HAS_VOLTAGE_MONITOR
// Check for auto-pause, shutdown or resume
if (autoSaveEnabled)
{
switch (autoSaveState)
{
case AutoSaveState::starting:
// Some users set the auto resume threshold high to disable auto resume, so prime auto save at the auto save threshold plus half a volt
if (currentVin >= autoResumeReading || currentVin > autoPauseReading + PowerVoltageToAdcReading(0.5))
{
autoSaveState = AutoSaveState::normal;
}
break;
case AutoSaveState::normal:
if (currentVin < autoPauseReading)
{
if (reprap.GetGCodes().LowVoltagePause())
{
autoSaveState = AutoSaveState::autoPaused;
}
}
break;
case AutoSaveState::autoPaused:
if (currentVin >= autoResumeReading)
{
if (reprap.GetGCodes().LowVoltageResume())
{
autoSaveState = AutoSaveState::normal;
}
}
break;
default:
break;
}
}
#endif
#if HAS_MASS_STORAGE
// Flush the log file it it is time. This may take some time, so do it last.
if (logger != nullptr)
{
logger->Flush(false);
}
#endif
}
#if HAS_SMART_DRIVERS
// Report driver status conditions that require attention.
// Sets 'reported' if we reported anything, else leaves 'reported' alone.
void Platform::ReportDrivers(MessageType mt, DriversBitmap& whichDrivers, const char* text, bool& reported) noexcept
{
if (whichDrivers != 0)
{
String<StringLength100> scratchString;
scratchString.printf("%s reported by driver(s)", text);
DriversBitmap wd = whichDrivers;
for (unsigned int drive = 0; wd != 0; ++drive)
{
if ((wd & 1) != 0)
{
scratchString.catf(" %u", drive);
}
wd >>= 1;
}
MessageF(mt, "%s\n", scratchString.c_str());
reported = true;
whichDrivers = 0;
}
}
#endif
#if HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR
bool Platform::HasVinPower() const noexcept
{
return driversPowered; // not quite right because drivers are disabled if we get over-voltage too, or if the 12V rail is low, but OK for the status report
}
#endif
#if HAS_VOLTAGE_MONITOR
void Platform::DisableAutoSave() noexcept
{
autoSaveEnabled = false;
}
bool Platform::IsPowerOk() const noexcept
{
return !autoSaveEnabled || currentVin > autoPauseReading;
}
void Platform::EnableAutoSave(float saveVoltage, float resumeVoltage) noexcept
{
autoPauseReading = PowerVoltageToAdcReading(saveVoltage);
autoResumeReading = PowerVoltageToAdcReading(resumeVoltage);
autoSaveEnabled = true;
}
bool Platform::GetAutoSaveSettings(float& saveVoltage, float&resumeVoltage) noexcept
{
if (autoSaveEnabled)
{
saveVoltage = AdcReadingToPowerVoltage(autoPauseReading);
resumeVoltage = AdcReadingToPowerVoltage(autoResumeReading);
}
return autoSaveEnabled;
}
#endif
#if HAS_CPU_TEMP_SENSOR
float Platform::AdcReadingToCpuTemperature(uint32_t adcVal) const noexcept
{
const float voltage = (float)adcVal * (3.3/(float)((1u << AdcBits) * ThermistorAverageReadings));
#if SAM4E || SAM4S
return (voltage - 1.44) * (1000.0/4.7) + 27.0 + mcuTemperatureAdjust; // accuracy at 27C is +/-13C
#elif SAM3XA
return (voltage - 0.8) * (1000.0/2.65) + 27.0 + mcuTemperatureAdjust; // accuracy at 27C is +/-45C
#elif SAME70
return (voltage - 0.72) * (1000.0/2.33) + 25.0 + mcuTemperatureAdjust; // accuracy at 25C is +/-34C
#else
# error undefined CPU temp conversion
#endif
}
#endif
//*****************************************************************************************************************
// Interrupts
void Platform::InitialiseInterrupts() noexcept
{
#if SAM4E || SAME70 || defined(__LPC17xx__)
NVIC_SetPriority(WDT_IRQn, NvicPriorityWatchdog); // set priority for watchdog interrupts
#endif
#if HAS_HIGH_SPEED_SD
NVIC_SetPriority(HSMCI_IRQn, NvicPriorityHSMCI); // set priority for SD interface interrupts
#endif
// Set PanelDue UART interrupt priority
#ifdef SERIAL_AUX_DEVICE
SERIAL_AUX_DEVICE.setInterruptPriority(NvicPriorityPanelDueUart);
#endif
#ifdef SERIAL_AUX2_DEVICE
SERIAL_AUX2_DEVICE.setInterruptPriority(NvicPriorityPanelDueUart);
#endif
#if HAS_WIFI_NETWORKING
NVIC_SetPriority(UART1_IRQn, NvicPriorityWiFiUart); // set priority for WiFi UART interrupt
#endif
#if SUPPORT_TMC22xx
# if TMC22xx_HAS_MUX
NVIC_SetPriority(TMC22xx_UART_IRQn, NvicPriorityDriversSerialTMC); // set priority for TMC2660 SPI interrupt
# else
NVIC_SetPriority(TMC22xxUartIRQns[0], NvicPriorityDriversSerialTMC);
NVIC_SetPriority(TMC22xxUartIRQns[1], NvicPriorityDriversSerialTMC);
# endif
#endif
#if SUPPORT_TMC2660
NVIC_SetPriority(TMC2660_SPI_IRQn, NvicPriorityDriversSerialTMC); // set priority for TMC2660 SPI interrupt
#endif
StepTimer::Init(); // initialise the step pulse timer
#if HAS_LWIP_NETWORKING
// Set up the Ethernet interface priority here to because we have access to the priority definitions
# if SAME70
NVIC_SetPriority(GMAC_IRQn, NvicPriorityEthernet);
NVIC_SetPriority(XDMAC_IRQn, NvicPriorityDMA);
# else
NVIC_SetPriority(EMAC_IRQn, NvicPriorityEthernet);
# endif
#endif
#ifdef __LPC17xx__
// Interrupt for GPIO pins. Only port 0 and 2 support interrupts and both share EINT3
NVIC_SetPriority(EINT3_IRQn, NvicPriorityPins);
#else
NVIC_SetPriority(PIOA_IRQn, NvicPriorityPins);
NVIC_SetPriority(PIOB_IRQn, NvicPriorityPins);
NVIC_SetPriority(PIOC_IRQn, NvicPriorityPins);
# ifdef ID_PIOD
NVIC_SetPriority(PIOD_IRQn, NvicPriorityPins);
# endif
# ifdef ID_PIOE
NVIC_SetPriority(PIOE_IRQn, NvicPriorityPins);
# endif
#endif
#if SAME70
NVIC_SetPriority(USBHS_IRQn, NvicPriorityUSB);
#elif SAM4E || SAM4S
NVIC_SetPriority(UDP_IRQn, NvicPriorityUSB);
#elif SAM3XA
NVIC_SetPriority(UOTGHS_IRQn, NvicPriorityUSB);
#elif defined(__LPC17xx__)
NVIC_SetPriority(USB_IRQn, NvicPriorityUSB);
#else
# error
#endif
#if defined(DUET_NG) || defined(DUET_M) || defined(DUET_06_085)
NVIC_SetPriority(I2C_IRQn, NvicPriorityTwi);
#elif defined(__LPC17xx__)
NVIC_SetPriority(I2C0_IRQn, NvicPriorityTwi);
NVIC_SetPriority(I2C1_IRQn, NvicPriorityTwi);
#endif
#if defined(__LPC17xx__)
// set rest of the Timer Interrupt priorities
// Timer 0 is used for step generation (set elsewhere)
NVIC_SetPriority(TIMER1_IRQn, 8); //Timer 1 is currently unused
NVIC_SetPriority(TIMER2_IRQn, NvicPriorityTimerServo); //Timer 2 runs the PWM for Servos at 50hz
NVIC_SetPriority(TIMER3_IRQn, NvicPriorityTimerPWM); //Timer 3 runs the microsecond free running timer to generate heater/fan PWM
#endif
// Tick interrupt for ADC conversions
tickState = 0;
currentFilterNumber = 0;
}
//*************************************************************************************************
// Debugging variables
//extern "C" uint32_t longestWriteWaitTime, shortestWriteWaitTime, longestReadWaitTime, shortestReadWaitTime;
//extern uint32_t maxRead, maxWrite;
#if SAM4E || SAM4S || SAME70
// Print the unique processor ID
void Platform::PrintUniqueId(MessageType mtype) noexcept
{
// Print the unique ID and checksum as 30 base5 alphanumeric digits
char digits[30 + 5 + 1]; // 30 characters, 5 separators, 1 null terminator
char *digitPtr = digits;
for (size_t i = 0; i < 30; ++i)
{
if ((i % 5) == 0 && i != 0)
{
*digitPtr++ = '-';
}
const size_t index = (i * 5) / 32;
const size_t shift = (i * 5) % 32;
uint32_t val = uniqueId[index] >> shift;
if (shift > 32 - 5)
{
// We need some bits from the next dword too
val |= uniqueId[index + 1] << (32 - shift);
}
val &= 31;
char c;
if (val < 10)
{
c = val + '0';
}
else
{
c = val + ('A' - 10);
// We have 26 letters in the usual A-Z alphabet and we only need 22 of them plus 0-9.
// So avoid using letters C, E, I and O which are easily mistaken for G, F, 1 and 0.
if (c >= 'C')
{
++c;
}
if (c >= 'E')
{
++c;
}
if (c >= 'I')
{
++c;
}
if (c >= 'O')
{
++c;
}
}
*digitPtr++ = c;
}
*digitPtr = 0;
MessageF(mtype, "Board ID: %s\n", digits);
}
#endif
// Return diagnostic information
void Platform::Diagnostics(MessageType mtype) noexcept
{
#if USE_CACHE && SAM4E
// Get the cache statistics before we start messing around with the cache
const uint32_t cacheCount = Cache::GetHitCount();
#endif
Message(mtype, "=== Platform ===\n");
// Debugging support
if (debugLine != 0)
{
MessageF(mtype, "Debug line %d\n", debugLine);
}
// Show the up time and reason for the last reset
const uint32_t now = (uint32_t)(millis64()/1000u); // get up time in seconds
#ifndef __LPC17xx__
const char* resetReasons[8] = { "power up", "backup", "watchdog", "software",
# ifdef DUET_NG
// On the SAM4E a watchdog reset may be reported as a user reset because of the capacitor on the NRST pin.
// The SAM4S is the same but the Duet M has a diode in the reset circuit to avoid this problem.
"reset button or watchdog",
# else
"reset button",
# endif
"?", "?", "?" };
MessageF(mtype, "Last reset %02d:%02d:%02d ago, cause: %s\n",
(unsigned int)(now/3600), (unsigned int)((now % 3600)/60), (unsigned int)(now % 60),
resetReasons[(REG_RSTC_SR & RSTC_SR_RSTTYP_Msk) >> RSTC_SR_RSTTYP_Pos]);
#endif //end ifndef __LPC17xx__
// Show the reset code stored at the last software reset
{
#ifdef __LPC17xx__
// Reset Reason
MessageF(mtype, "Last reset %02d:%02d:%02d ago, cause: ",
(unsigned int)(now/3600), (unsigned int)((now % 3600)/60), (unsigned int)(now % 60));
if (LPC_SYSCTL->RSID & RSID_POR) { MessageF(mtype, "[power up]"); }
if (LPC_SYSCTL->RSID & RSID_EXTR) { MessageF(mtype, "[reset button]"); }
if (LPC_SYSCTL->RSID & RSID_WDTR) { MessageF(mtype, "[watchdog]"); }
if (LPC_SYSCTL->RSID & RSID_BODR) { MessageF(mtype, "[brownout]"); }
if (LPC_SYSCTL->RSID & RSID_SYSRESET) { MessageF(mtype, "[software]"); }
if (LPC_SYSCTL->RSID & RSID_LOCKUP) { MessageF(mtype, "[lockup]"); }
MessageF(mtype, "\n");
SoftwareResetData srdBuf[1];
int slot = -1;
for (int s = SoftwareResetData::numberOfSlots - 1; s >= 0; s--)
{
SoftwareResetData *sptr = reinterpret_cast<SoftwareResetData *>(LPC_GetSoftwareResetDataSlotPtr(s));
if (sptr->magic != 0xFFFF)
{
//slot = s;
MessageF(mtype, "LPC Flash Slot[%d]: \n", s);
slot = 0; // we only have 1 slot in the array, set this to zero to be compatible with existing code below
//copy the data into srdBuff
LPC_ReadSoftwareResetDataSlot(s, &srdBuf[0], sizeof(srdBuf[0]));
break;
}
}
#else
SoftwareResetData srdBuf[SoftwareResetData::numberOfSlots];
memset(srdBuf, 0, sizeof(srdBuf));
int slot = -1;
# if SAM4E || SAM4S || SAME70
// Work around bug in ASF flash library: flash_read_user_signature calls a RAMFUNC without disabling interrupts first.
// This caused a crash (watchdog timeout) sometimes if we run M122 while a print is in progress
const irqflags_t flags = cpu_irq_save();
Cache::Disable();
const uint32_t rc = flash_read_user_signature(reinterpret_cast<uint32_t*>(srdBuf), sizeof(srdBuf)/sizeof(uint32_t));
Cache::Enable();
cpu_irq_restore(flags);
if (rc == FLASH_RC_OK)
# else
DueFlashStorage::read(SoftwareResetData::nvAddress, srdBuf, sizeof(srdBuf));
# endif
{
// Find the last slot written
slot = SoftwareResetData::numberOfSlots;
do
{
--slot;
}
while (slot >= 0 && srdBuf[slot].magic == 0xFFFF);
}
#endif
if (slot >= 0 && srdBuf[slot].magic == SoftwareResetData::magicValue)
{
const char* const reasonText = SoftwareResetData::ReasonText[(srdBuf[slot].resetReason >> 5) & 0x0F];
String<StringLength100> scratchString;
if (srdBuf[slot].when != 0)
{
const time_t when = (time_t)srdBuf[slot].when;
tm timeInfo;
gmtime_r(&when, &timeInfo);
scratchString.printf("at %04u-%02u-%02u %02u:%02u",
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday, timeInfo.tm_hour, timeInfo.tm_min);
}
else
{
scratchString.copy("time unknown");
}
MessageF(mtype, "Last software reset %s, reason: %s%s, spinning module %s, available RAM %" PRIu32 " bytes (slot %d)\n",
scratchString.c_str(),
(srdBuf[slot].resetReason & (uint32_t)SoftwareResetReason::deliberate) ? "deliberate " : "",
reasonText,
GetModuleName(srdBuf[slot].resetReason & 0x1F), srdBuf[slot].neverUsedRam, slot);
// Our format buffer is only 256 characters long, so the next 2 lines must be written separately
MessageF(mtype,
"Software reset code 0x%04x HFSR 0x%08" PRIx32 " CFSR 0x%08" PRIx32 " ICSR 0x%08" PRIx32 " BFAR 0x%08" PRIx32 " SP 0x%08" PRIx32 " Task 0x%08" PRIx32 "\n",
srdBuf[slot].resetReason, srdBuf[slot].hfsr, srdBuf[slot].cfsr, srdBuf[slot].icsr, srdBuf[slot].bfar, srdBuf[slot].sp, srdBuf[slot].taskName
);
if (srdBuf[slot].sp != 0xFFFFFFFF)
{
// We saved a stack dump, so print it
scratchString.Clear();
for (uint32_t stval : srdBuf[slot].stack)
{
scratchString.catf(" %08" PRIx32, stval);
}
MessageF(mtype, "Stack:%s\n", scratchString.c_str());
}
}
else
{
Message(mtype, "Last software reset details not available\n");
}
}
// Show the current error codes
MessageF(mtype, "Error status: %" PRIx32 "\n", errorCodeBits);
#if HAS_MASS_STORAGE
// Show the number of free entries in the file table
MessageF(mtype, "Free file entries: %u\n", MassStorage::GetNumFreeFiles());
# if HAS_HIGH_SPEED_SD
// Show the HSMCI CD pin and speed
MessageF(mtype, "SD card 0 %s, interface speed: %.1fMBytes/sec\n", (MassStorage::IsCardDetected(0) ? "detected" : "not detected"), (double)((float)hsmci_get_speed() * 0.000001));
# else
MessageF(mtype, "SD card 0 %s\n", (MassStorage::IsCardDetected(0) ? "detected" : "not detected"));
# endif
// Show the longest SD card write time
MessageF(mtype, "SD card longest block write time: %.1fms, max retries %u\n", (double)FileStore::GetAndClearLongestWriteTime(), FileStore::GetAndClearMaxRetryCount());
#endif
#if HAS_CPU_TEMP_SENSOR
// Show the MCU temperatures
const uint32_t currentMcuTemperature = adcFilters[CpuTempFilterIndex].GetSum();
MessageF(mtype, "MCU temperature: min %.1f, current %.1f, max %.1f\n",
(double)AdcReadingToCpuTemperature(lowestMcuTemperature), (double)AdcReadingToCpuTemperature(currentMcuTemperature), (double)AdcReadingToCpuTemperature(highestMcuTemperature));
lowestMcuTemperature = highestMcuTemperature = currentMcuTemperature;
#endif
#if HAS_VOLTAGE_MONITOR
// Show the supply voltage
MessageF(mtype, "Supply voltage: min %.1f, current %.1f, max %.1f, under voltage events: %" PRIu32 ", over voltage events: %" PRIu32 ", power good: %s\n",
(double)AdcReadingToPowerVoltage(lowestVin), (double)AdcReadingToPowerVoltage(currentVin), (double)AdcReadingToPowerVoltage(highestVin),
numVinUnderVoltageEvents, numVinOverVoltageEvents,
(driversPowered) ? "yes" : "no");
lowestVin = highestVin = currentVin;
#endif
#if HAS_12V_MONITOR
// Show the 12V rail voltage
MessageF(mtype, "12V rail voltage: min %.1f, current %.1f, max %.1f, under voltage events: %" PRIu32 "\n",
(double)AdcReadingToPowerVoltage(lowestV12), (double)AdcReadingToPowerVoltage(currentV12), (double)AdcReadingToPowerVoltage(highestV12), numV12UnderVoltageEvents);
lowestV12 = highestV12 = currentV12;
#endif
#if HAS_SMART_DRIVERS
// Show the motor stall status
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
String<MediumStringLength> driverStatus;
SmartDrivers::AppendDriverStatus(drive, driverStatus.GetRef());
MessageF(mtype, "Driver %u:%s\n", drive, driverStatus.c_str());
}
#endif
// Show current RTC time
Message(mtype, "Date/time: ");
struct tm timeInfo;
if (gmtime_r(&realTime, &timeInfo) != nullptr)
{
MessageF(mtype, "%04u-%02u-%02u %02u:%02u:%02u\n",
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);
}
else
{
Message(mtype, "not set\n");
}
#if USE_CACHE && SAM4E
MessageF(mtype, "Cache data hit count %" PRIu32 "\n", cacheCount);
#endif
reprap.Timing(mtype);
#if 0
// Debugging temperature readings
const uint32_t div = ThermistorAveragingFilter::NumAveraged() >> 2; // 2 oversample bits
MessageF(mtype, "Vssa %" PRIu32 " Vref %" PRIu32 " Temp0 %" PRIu32 " Temp1 %" PRIu32 "\n",
adcFilters[VssaFilterIndex].GetSum()/div, adcFilters[VrefFilterIndex].GetSum()/div, adcFilters[0].GetSum()/div, adcFilters[1].GetSum()/div);
#endif
#ifdef SOFT_TIMER_DEBUG
MessageF(mtype, "Soft timer interrupts executed %u, next %u scheduled at %u, now %u\n",
numSoftTimerInterruptsExecuted, STEP_TC->TC_CHANNEL[STEP_TC_CHAN].TC_RB, lastSoftTimerInterruptScheduledAt, GetTimerTicks());
#endif
#ifdef I2C_IFACE
const TwoWire::ErrorCounts errs = I2C_IFACE.GetErrorCounts(true);
MessageF(mtype, "I2C nak errors %" PRIu32 ", send timeouts %" PRIu32 ", receive timeouts %" PRIu32 ", finishTimeouts %" PRIu32 ", resets %" PRIu32 "\n",
errs.naks, errs.sendTimeouts, errs.recvTimeouts, errs.finishTimeouts, errs.resets);
#endif
}
GCodeResult Platform::DiagnosticTest(GCodeBuffer& gb, const StringRef& reply, unsigned int d)
{
static const uint32_t dummy[2] = { 0, 0 };
switch (d)
{
case (unsigned int)DiagnosticTestType::PrintTestReport:
{
const MessageType mtype = gb.GetResponseMessageType();
bool testFailed = false;
#if HAS_MASS_STORAGE
// Check the SD card detect and speed
if (!MassStorage::IsCardDetected(0))
{
Message(AddError(mtype), "SD card 0 not detected\n");
testFailed = true;
}
# if HAS_HIGH_SPEED_SD
else if (hsmci_get_speed() != ExpectedSdCardSpeed)
{
MessageF(AddError(mtype), "SD card speed %.2fMbytes/sec is unexpected\n", (double)((float)hsmci_get_speed() * 0.000001));
testFailed = true;
}
# endif
else
{
Message(mtype, "SD card interface OK\n");
}
#endif
#if HAS_CPU_TEMP_SENSOR
// Check the MCU temperature
{
float tempMinMax[2];
size_t numTemps = 2;
bool seen = false;
if (gb.TryGetFloatArray('T', numTemps, tempMinMax, reply, seen, false))
{
return GCodeResult::error;
}
if (!seen)
{
reply.copy("Missing T parameter");
return GCodeResult::error;
}
const float currentMcuTemperature = AdcReadingToCpuTemperature(adcFilters[CpuTempFilterIndex].GetSum());
if (currentMcuTemperature < tempMinMax[0])
{
MessageF(AddError(mtype), "MCU temperature %.1f is lower than expected\n", (double)currentMcuTemperature);
testFailed = true;
}
else if (currentMcuTemperature > tempMinMax[1])
{
MessageF(AddError(mtype), "MCU temperature %.1f is higher than expected\n", (double)currentMcuTemperature);
testFailed = true;
}
else
{
Message(mtype, "MCU temperature reading OK\n");
}
}
#endif
#if HAS_VOLTAGE_MONITOR
// Check the supply voltage
{
float voltageMinMax[2];
size_t numVoltages = 2;
bool seen = false;
if (gb.TryGetFloatArray('V', numVoltages, voltageMinMax, reply, seen, false))
{
return GCodeResult::error;
}
if (!seen)
{
reply.copy("Missing V parameter (VIN voltage range)");
return GCodeResult::error;
}
const float voltage = AdcReadingToPowerVoltage(currentVin);
if (voltage < voltageMinMax[0])
{
MessageF(AddError(mtype), "VIN voltage reading %.1f is lower than expected\n", (double)voltage);
testFailed = true;
}
else if (voltage > voltageMinMax[1])
{
MessageF(AddError(mtype), "VIN voltage reading %.1f is higher than expected\n", (double)voltage);
testFailed = true;
}
else
{
Message(mtype, "VIN voltage reading OK\n");
}
}
#endif
#if HAS_12V_MONITOR
// Check the 12V rail voltage
{
float voltageMinMax[2];
size_t numVoltages = 2;
bool seen = false;
if (gb.TryGetFloatArray('W', numVoltages, voltageMinMax, reply, seen, false))
{
return GCodeResult::error;
}
if (!seen)
{
reply.copy("Missing W parameter (12V rail voltage range)");
return GCodeResult::error;
}
const float voltage = AdcReadingToPowerVoltage(currentV12);
if (voltage < voltageMinMax[0])
{
MessageF(AddError(mtype), "12V voltage reading %.1f is lower than expected\n", (double)voltage);
testFailed = true;
}
else if (voltage > voltageMinMax[1])
{
MessageF(AddError(mtype), "12V voltage reading %.1f is higher than expected\n", (double)voltage);
testFailed = true;
}
else
{
Message(mtype, "12V voltage reading OK\n");
}
}
#endif
#if HAS_SMART_DRIVERS
// Check the stepper driver status
bool driversOK = true;
for (size_t driver = 0; driver < numSmartDrivers; ++driver)
{
const uint32_t stat = SmartDrivers::GetAccumulatedStatus(driver, 0xFFFFFFFF);
if ((stat & (TMC_RR_OT || TMC_RR_OTPW)) != 0)
{
MessageF(AddError(mtype), "Driver %u reports over temperature\n", driver);
driversOK = false;
}
if ((stat & TMC_RR_S2G) != 0)
{
MessageF(AddError(mtype), "Driver %u reports short-to-ground\n", driver);
driversOK = false;
}
}
if (driversOK)
{
Message(mtype, "Driver status OK\n");
}
else
{
testFailed = true;
}
#endif
Message(mtype, (testFailed) ? "***** ONE OR MORE CHECKS FAILED *****\n" : "All checks passed\n");
#if SAM4E || SAM4S || SAME70
if (!testFailed)
{
PrintUniqueId(mtype);
}
#endif
}
break;
case (unsigned int)DiagnosticTestType::TestWatchdog:
deliberateError = true;
SysTick->CTRL &= ~(SysTick_CTRL_TICKINT_Msk); // disable the system tick interrupt so that we get a watchdog timeout reset
break;
case (unsigned int)DiagnosticTestType::TestSpinLockup:
deliberateError = true;
debugCode = d; // tell the Spin function to loop
break;
case (unsigned int)DiagnosticTestType::TestSerialBlock: // write an arbitrary message via debugPrintf()
deliberateError = true;
debugPrintf("Diagnostic Test\n");
break;
case (unsigned int)DiagnosticTestType::DivideByZero: // do an integer divide by zero to test exception handling
deliberateError = true;
(void)RepRap::DoDivide(1, 0); // call function in another module so it can't be optimised away
break;
case (unsigned int)DiagnosticTestType::UnalignedMemoryAccess: // do an unaligned memory access to test exception handling
deliberateError = true;
SCB->CCR |= SCB_CCR_UNALIGN_TRP_Msk; // by default, unaligned memory accesses are allowed, so change that
__DSB(); // make sure that instruction completes
__DMB(); // don't allow prefetch
(void)*(reinterpret_cast<const volatile char*>(dummy) + 1);
break;
case (unsigned int)DiagnosticTestType::BusFault:
// Read from the "Undefined (Abort)" area
#if SAME70
# if USE_MPU
deliberateError = true;
(void)*(reinterpret_cast<const volatile char*>(0x30000000));
# else
Message(WarningMessage, "There is no abort area on the SAME70 with MPU disabled");
# endif
#elif SAM4E || SAM4S
deliberateError = true;
(void)*(reinterpret_cast<const volatile char*>(0x20800000));
#elif SAM3XA
deliberateError = true;
(void)*(reinterpret_cast<const volatile char*>(0x20200000));
#elif defined(__LPC17xx__)
deliberateError = true;
// The LPC176x/5x generates Bus Fault exception when accessing a reserved memory address
(void)*(reinterpret_cast<const volatile char*>(0x00080000));
#else
# error
#endif
break;
case (unsigned int)DiagnosticTestType::PrintMoves:
DDA::PrintMoves();
break;
case (unsigned int)DiagnosticTestType::TimeSquareRoot: // Show the square root calculation time. Caution: may disable interrupt for several tens of microseconds.
{
bool ok1 = true;
uint32_t tim1 = 0;
for (uint32_t i = 0; i < 100; ++i)
{
const uint32_t num1 = 0x7265ac3d + i;
const uint64_t sq = (uint64_t)num1 * num1;
cpu_irq_disable();
const uint32_t now1 = StepTimer::GetTimerTicks();
const uint32_t num1a = isqrt64(sq);
tim1 += StepTimer::GetTimerTicks() - now1;
cpu_irq_enable();
if (num1a != num1)
{
ok1 = false;
}
}
bool ok2 = true;
uint32_t tim2 = 0;
for (uint32_t i = 0; i < 100; ++i)
{
const uint32_t num2 = 0x0000a4c5 + i;
const uint64_t sq = (uint64_t)num2 * num2;
cpu_irq_disable();
const uint32_t now2 = StepTimer::GetTimerTicks();
const uint32_t num2a = isqrt64(sq);
tim2 += StepTimer::GetTimerTicks() - now2;
cpu_irq_enable();
if (num2a != num2)
{
ok2 = false;
}
}
reply.printf("Square roots: 62-bit %.2fus %s, 32-bit %.2fus %s",
(double)(tim1 * 10000)/StepTimer::StepClockRate, (ok1) ? "ok" : "ERROR",
(double)(tim2 * 10000)/StepTimer::StepClockRate, (ok2) ? "ok" : "ERROR");
}
break;
case (unsigned int)DiagnosticTestType::TimeSinCos: // Show the sin/cosine calculation time. Caution: may disable interrupt for several tens of microseconds.
{
bool ok = true;
uint32_t tim1 = 0;
for (unsigned int i = 0; i < 100; ++i)
{
const float angle = 0.01 * i;
cpu_irq_disable();
const uint32_t now1 = StepTimer::GetTimerTicks();
const float f1 = RepRap::SinfCosf(angle);
tim1 += StepTimer::GetTimerTicks() - now1;
cpu_irq_enable();
if (f1 >= 1.5)
{
ok = false; // need to use f1 to prevent the calculations being omitted
}
}
uint32_t tim2 = 0;
for (unsigned int i = 0; i < 100; ++i)
{
const double angle = (double)0.01 * i;
cpu_irq_disable();
const uint32_t now2 = StepTimer::GetTimerTicks();
const double d1 = RepRap::SinCos(angle);
tim2 += StepTimer::GetTimerTicks() - now2;
cpu_irq_enable();
if (d1 >= (double)1.5)
{
ok = false; // need to use f1 to prevent the calculations being omitted
}
}
if (ok) // should always be true
{
reply.printf("Sine + cosine: float %.2fus, double %.2fus", (double)(tim1 * 10000)/StepTimer::StepClockRate, (double)(tim2 * 10000)/StepTimer::StepClockRate);
}
}
break;
case (unsigned int)DiagnosticTestType::TimeSDWrite:
#if HAS_MASS_STORAGE
return reprap.GetGCodes().StartSDTiming(gb, reply);
#else
reply.copy("No SD card interface available");
return GCodeResult::errorNotSupported;
#endif
case (unsigned int)DiagnosticTestType::PrintObjectSizes:
reply.printf(
"DDA %u, DM %u, Tool %u, GCodeBuffer %u, heater %u"
#if HAS_NETWORKING && !HAS_LEGACY_NETWORKING
", HTTP resp %u, FTP resp %u, Telnet resp %u"
#endif
, sizeof(DDA), sizeof(DriveMovement), sizeof(Tool), sizeof(GCodeBuffer), sizeof(Heater)
#if HAS_NETWORKING && !HAS_LEGACY_NETWORKING
, sizeof(HttpResponder), sizeof(FtpResponder), sizeof(TelnetResponder)
#endif
);
break;
case (unsigned int)DiagnosticTestType::PrintObjectAddresses:
reply.printf
("Platform %08" PRIx32 "-%08" PRIx32 "\nGCodes %08" PRIx32 "-%08" PRIx32,
reinterpret_cast<uint32_t>(this), reinterpret_cast<uint32_t>(this) + sizeof(Platform) - 1,
reinterpret_cast<uint32_t>(&reprap.GetGCodes()), reinterpret_cast<uint32_t>(&reprap.GetGCodes()) + sizeof(GCodes) - 1
);
break;
#ifdef DUET_NG
case (unsigned int)DiagnosticTestType::PrintExpanderStatus:
reply.printf("Expander status %04X\n", DuetExpansion::DiagnosticRead());
break;
#endif
#ifdef __LPC17xx__
// Diagnostic for LPC board configuration
case (int)DiagnosticTestType::PrintBoardConfiguration:
BoardConfig::Diagnostics(gb.GetResponseMessageType());
break;
#endif
default:
break;
}
return GCodeResult::ok;
}
#if HAS_SMART_DRIVERS
// This is called when a fan that monitors driver temperatures is turned on when it was off
void Platform::DriverCoolingFansOnOff(uint32_t driverChannelsMonitored, bool on) noexcept
{
for (unsigned int i = 0; i < NumTmcDriversSenseChannels; ++i)
{
if ((driverChannelsMonitored & (1 << i)) != 0)
{
if (on)
{
driversFanTimers[i].Start();
}
else
{
driversFanTimers[i].Stop();
}
}
}
}
#endif
// Get the index of the averaging filter for an analog port
int Platform::GetAveragingFilterIndex(const IoPort& port) const noexcept
{
for (size_t i = 0; i < NumAdcFilters; ++i)
{
if (port.GetAnalogChannel() == filteredAdcChannels[i])
{
return (int)i;
}
}
return -1;
}
void Platform::UpdateConfiguredHeaters() noexcept
{
configuredHeaters = 0;
// Check bed heaters
for (size_t i = 0; i < MaxBedHeaters; i++)
{
const int8_t bedHeater = reprap.GetHeat().GetBedHeater(i);
if (bedHeater >= 0)
{
SetBit(configuredHeaters, bedHeater);
}
}
// Check chamber heaters
for (size_t i = 0; i < MaxChamberHeaters; i++)
{
const int8_t chamberHeater = reprap.GetHeat().GetChamberHeater(i);
if (chamberHeater >= 0)
{
SetBit(configuredHeaters, chamberHeater);
}
}
// Check tool heaters
for (size_t heater = 0; heater < MaxHeaters; heater++)
{
if (reprap.IsHeaterAssignedToTool(heater))
{
SetBit(configuredHeaters, heater);
}
}
}
#if HAS_MASS_STORAGE
// Write the platform parameters to file
bool Platform::WritePlatformParameters(FileStore *f, bool includingG31) const noexcept
{
bool ok;
if (axisMinimaProbed != 0 || axisMaximaProbed != 0)
{
ok = f->Write("; Probed axis limits\n");
if (ok)
{
ok = WriteAxisLimits(f, axisMinimaProbed, axisMinima, 1);
}
if (ok)
{
ok = WriteAxisLimits(f, axisMaximaProbed, axisMaxima, 0);
}
}
else
{
ok = true;
}
if (ok && includingG31)
{
ok = endstops.WriteZProbeParameters(f, includingG31);
}
return ok;
}
bool Platform::WriteAxisLimits(FileStore *f, AxesBitmap axesProbed, const float limits[MaxAxes], int sParam) noexcept
{
if (axesProbed == 0)
{
return true;
}
String<StringLength100> scratchString;
scratchString.printf("M208 S%d", sParam);
for (size_t axis = 0; axis < reprap.GetGCodes().GetTotalAxes(); ++axis)
{
if (IsBitSet(axesProbed, axis))
{
scratchString.catf(" %c%.2f", reprap.GetGCodes().GetAxisLetters()[axis], (double)limits[axis]);
}
}
scratchString.cat('\n');
return f->Write(scratchString.c_str());
}
#endif
#if SUPPORT_CAN_EXPANSION
// Function to identify and iterate through all drivers attached to an axis or extruder
void Platform::IterateDrivers(size_t axisOrExtruder, std::function<void(uint8_t)> localFunc, std::function<void(DriverId)> remoteFunc) noexcept
{
if (axisOrExtruder < reprap.GetGCodes().GetTotalAxes())
{
for (size_t i = 0; i < axisDrivers[axisOrExtruder].numDrivers; ++i)
{
const DriverId id = axisDrivers[axisOrExtruder].driverNumbers[i];
if (id.IsLocal())
{
localFunc(id.localDriver);
}
else
{
remoteFunc(id);
}
}
}
else if (axisOrExtruder < MaxAxesPlusExtruders)
{
const DriverId id = extruderDrivers[LogicalDriveToExtruder(axisOrExtruder)];
if (id.IsLocal())
{
localFunc(id.localDriver);
}
else
{
remoteFunc(id);
}
}
}
#else
// Function to identify and iterate through all drivers attached to an axis or extruder
void Platform::IterateDrivers(size_t axisOrExtruder, std::function<void(uint8_t)> localFunc) noexcept
{
if (axisOrExtruder < reprap.GetGCodes().GetTotalAxes())
{
for (size_t i = 0; i < axisDrivers[axisOrExtruder].numDrivers; ++i)
{
const DriverId id = axisDrivers[axisOrExtruder].driverNumbers[i];
localFunc(id.localDriver);
}
}
else if (axisOrExtruder < MaxAxesPlusExtruders)
{
const DriverId id = extruderDrivers[LogicalDriveToExtruder(axisOrExtruder)];
localFunc(id.localDriver);
}
}
#endif
// This is called from the step ISR as well as other places, so keep it fast
// If drive >= DRIVES then we are setting an individual motor direction
void Platform::SetDirection(size_t axisOrExtruder, bool direction) noexcept
{
const bool isSlowDriver = (GetDriversBitmap(axisOrExtruder) & GetSlowDriversBitmap()) != 0;
if (isSlowDriver)
{
while (StepTimer::GetTimerTicks() - DDA::lastStepLowTime < GetSlowDriverDirHoldClocks()) { }
}
if (axisOrExtruder < MaxAxesPlusExtruders)
{
IterateLocalDrivers(axisOrExtruder, [this, direction](uint8_t driver) { this->SetDriverDirection(driver, direction); });
}
else if (axisOrExtruder < MaxAxesPlusExtruders + NumDirectDrivers)
{
SetDriverDirection(axisOrExtruder - MaxAxesPlusExtruders, direction);
}
if (isSlowDriver)
{
DDA::lastDirChangeTime = StepTimer::GetTimerTicks();
}
}
// Enable a driver. Must not be called from an ISR, or with interrupts disabled.
void Platform::EnableOneLocalDriver(size_t driver, float requiredCurrent) noexcept
{
#if HAS_SMART_DRIVERS && (HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR)
if (driver < numSmartDrivers && !driversPowered)
{
warnDriversNotPowered = true;
}
else
{
#endif
UpdateMotorCurrent(driver, requiredCurrent);
#if defined(DUET3) && HAS_SMART_DRIVERS
SmartDrivers::EnableDrive(driver, true); // all drivers driven directly by the main board are smart
#elif HAS_SMART_DRIVERS
if (driver < numSmartDrivers)
{
SmartDrivers::EnableDrive(driver, true);
}
else
{
digitalWrite(ENABLE_PINS[driver], enableValues[driver] > 0);
}
#else
digitalWrite(ENABLE_PINS[driver], enableValues[driver] > 0);
#endif
#if HAS_SMART_DRIVERS && (HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR)
}
#endif
}
// Disable a driver
void Platform::DisableOneLocalDriver(size_t driver) noexcept
{
if (driver < NumDirectDrivers)
{
#if defined(DUET3) && HAS_SMART_DRIVERS
SmartDrivers::EnableDrive(driver, false); // all drivers driven directly by the main board are smart
#elif HAS_SMART_DRIVERS
if (driver < numSmartDrivers)
{
SmartDrivers::EnableDrive(driver, false);
}
else
{
digitalWrite(ENABLE_PINS[driver], enableValues[driver] <= 0);
}
#else
digitalWrite(ENABLE_PINS[driver], enableValues[driver] <= 0);
#endif
}
}
// Enable the local drivers for a drive. Must not be called from an ISR, or with interrupts disabled.
void Platform::EnableLocalDrivers(size_t axisOrExtruder) noexcept
{
if (driverState[axisOrExtruder] != DriverStatus::enabled)
{
driverState[axisOrExtruder] = DriverStatus::enabled;
const float requiredCurrent = motorCurrents[axisOrExtruder] * motorCurrentFraction[axisOrExtruder];
IterateLocalDrivers(axisOrExtruder, [this, requiredCurrent](uint8_t driver) { EnableOneLocalDriver(driver, requiredCurrent); });
}
}
// Disable the drivers for a drive
void Platform::DisableDrivers(size_t axisOrExtruder) noexcept
{
#if SUPPORT_CAN_EXPANSION
CanDriversList canDriversToDisable;
IterateDrivers(axisOrExtruder,
[this](uint8_t driver) { DisableOneLocalDriver(driver); },
[&canDriversToDisable](DriverId driver) { canDriversToDisable.AddEntry(driver); }
);
CanInterface::DisableRemoteDrivers(canDriversToDisable);
#else
IterateDrivers(axisOrExtruder,
[this](uint8_t driver) { DisableOneLocalDriver(driver); }
);
#endif
driverState[axisOrExtruder] = DriverStatus::disabled;
}
// Disable all drives in an emergency. Called from emergency stop and the tick ISR.
// This is only called in an emergency, so we don't update the driver status
void Platform::EmergencyDisableDrivers() noexcept
{
for (size_t drive = 0; drive < NumDirectDrivers; drive++)
{
if (!inInterrupt()) // on the Duet 06/085 we need interrupts running to send the I2C commands to set motor currents
{
UpdateMotorCurrent(drive, 0.0);
}
DisableOneLocalDriver(drive);
}
}
void Platform::DisableAllDrivers() noexcept
{
for (size_t axisOrExtruder = 0; axisOrExtruder < MaxAxesPlusExtruders; axisOrExtruder++)
{
DisableDrivers(axisOrExtruder);
}
}
// Set drives to idle hold if they are enabled. If a drive is disabled, leave it alone.
// Must not be called from an ISR, or with interrupts disabled.
void Platform::SetDriversIdle() noexcept
{
if (idleCurrentFactor == 0)
{
DisableAllDrivers();
reprap.GetGCodes().SetAllAxesNotHomed();
}
else
{
#if SUPPORT_CAN_EXPANSION
CanDriversList canDriversToSetIdle;
#endif
for (size_t axisOrExtruder = 0; axisOrExtruder < MaxAxesPlusExtruders; ++axisOrExtruder)
{
if (driverState[axisOrExtruder] == DriverStatus::enabled)
{
driverState[axisOrExtruder] = DriverStatus::idle;
const float current = motorCurrents[axisOrExtruder] * idleCurrentFactor;
IterateDrivers(axisOrExtruder,
[this, current](uint8_t driver) { UpdateMotorCurrent(driver, current); }
#if SUPPORT_CAN_EXPANSION
, [&canDriversToSetIdle](DriverId driver) { canDriversToSetIdle.AddEntry(driver); }
#endif
);
}
}
#if SUPPORT_CAN_EXPANSION
CanInterface::SetRemoteDriversIdle(canDriversToSetIdle);
#endif
}
}
// Set the current for all drivers on an axis or extruder. Current is in mA.
bool Platform::SetMotorCurrent(size_t axisOrExtruder, float currentOrPercent, int code, const StringRef& reply) noexcept
{
switch (code)
{
case 906:
motorCurrents[axisOrExtruder] = currentOrPercent;
break;
case 913:
motorCurrentFraction[axisOrExtruder] = constrain<float>(0.01 * currentOrPercent, 0.0, 1.0);
break;
#if HAS_SMART_DRIVERS
case 917:
standstillCurrentPercent[axisOrExtruder] = constrain<float>(currentOrPercent, 0.0, 100.0);
break;
#endif
default:
return false;
}
#if SUPPORT_CAN_EXPANSION
CanDriversData canDriversToUpdate;
IterateDrivers(axisOrExtruder,
[this, axisOrExtruder, code](uint8_t driver)
{
if (code == 917)
{
# if HAS_SMART_DRIVERS
SmartDrivers::SetStandstillCurrentPercent(driver, standstillCurrentPercent[axisOrExtruder]);
# endif
}
else
{
UpdateMotorCurrent(driver, motorCurrents[axisOrExtruder] * motorCurrentFraction[axisOrExtruder]);
}
},
[this, axisOrExtruder, code, &canDriversToUpdate](DriverId driver)
{
if (code == 917)
{
canDriversToUpdate.AddEntry(driver, (uint16_t)(standstillCurrentPercent[axisOrExtruder]));
}
else
{
canDriversToUpdate.AddEntry(driver, (uint16_t)(motorCurrents[axisOrExtruder] * motorCurrentFraction[axisOrExtruder]));
}
}
);
if (code == 917)
{
return CanInterface::SetRemoteStandstillCurrentPercent(canDriversToUpdate, reply);
}
else
{
return CanInterface::SetRemoteDriverCurrents(canDriversToUpdate, reply);
}
#else
IterateDrivers(axisOrExtruder,
[this, axisOrExtruder, code](uint8_t driver)
{
if (code == 917)
{
# if HAS_SMART_DRIVERS
SmartDrivers::SetStandstillCurrentPercent(driver, standstillCurrentPercent[axisOrExtruder]);
# endif
}
else
{
UpdateMotorCurrent(driver, motorCurrents[axisOrExtruder] * motorCurrentFraction[axisOrExtruder]);
}
}
);
return true;
#endif
}
// This must not be called from an ISR, or with interrupts disabled.
void Platform::UpdateMotorCurrent(size_t driver, float current) noexcept
{
if (driver < NumDirectDrivers)
{
#if HAS_SMART_DRIVERS
if (driver < numSmartDrivers)
{
SmartDrivers::SetCurrent(driver, current);
}
#elif defined (DUET_06_085)
const uint16_t pot = (unsigned short)((0.256*current*8.0*senseResistor + maxStepperDigipotVoltage/2)/maxStepperDigipotVoltage);
if (driver < 4)
{
mcpDuet.setNonVolatileWiper(potWipes[driver], pot);
mcpDuet.setVolatileWiper(potWipes[driver], pot);
}
else
{
if (board == BoardType::Duet_085)
{
// Extruder 0 is on DAC channel 0
if (driver == 4)
{
const float dacVoltage = max<float>(current * 0.008 * senseResistor + stepperDacVoltageOffset, 0.0); // the voltage we want from the DAC relative to its minimum
const float dac = dacVoltage/stepperDacVoltageRange;
AnalogOut(DAC0, dac);
}
else
{
mcpExpansion.setNonVolatileWiper(potWipes[driver-1], pot);
mcpExpansion.setVolatileWiper(potWipes[driver-1], pot);
}
}
else if (driver < 8) // on a Duet 0.6 we have a maximum of 8 drives
{
mcpExpansion.setNonVolatileWiper(potWipes[driver], pot);
mcpExpansion.setVolatileWiper(potWipes[driver], pot);
}
}
#elif defined(__ALLIGATOR__)
// Alligator SPI DAC current
if (driver < 4) // Onboard DAC
{
dacAlligator.setChannel(3-driver, current * 0.102);
}
else // Piggy module DAC
{
dacPiggy.setChannel(7-driver, current * 0.102);
}
#elif defined(__LPC17xx__)
if (hasDriverCurrentControl)
{
//Has digipots to set current control for drivers
//Current is in mA
const uint16_t pot = (unsigned short) (current * digipotFactor / 1000);
if (driver < 4)
{
mcp4451.setMCP4461Address(0x2C); //A0 and A1 Grounded. (001011 00)
mcp4451.setVolatileWiper(POT_WIPES[driver], pot);
}
else
mcp4451.setMCP4461Address(0x2D); //A0 Vcc, A1 Grounded. (001011 01)
mcp4451.setVolatileWiper(POT_WIPES[driver-4], pot);
}
}
#else
// otherwise we can't set the motor current
#endif
}
}
// Get the configured motor current for an axis or extruder
float Platform::GetMotorCurrent(size_t drive, int code) const noexcept
{
switch (code)
{
case 906:
return motorCurrents[drive];
case 913:
return motorCurrentFraction[drive] * 100.0;
#if HAS_SMART_DRIVERS
case 917:
return standstillCurrentPercent[drive];
#endif
default:
return 0.0;
}
}
// Set the motor idle current factor
void Platform::SetIdleCurrentFactor(float f) noexcept
{
idleCurrentFactor = constrain<float>(f, 0.0, 1.0);
#if SUPPORT_CAN_EXPANSION
CanDriversData canDriversToUpdate;
#endif
for (size_t axisOrExtruder = 0; axisOrExtruder < MaxAxesPlusExtruders; ++axisOrExtruder)
{
if (driverState[axisOrExtruder] == DriverStatus::idle)
{
const float requiredCurrent = motorCurrents[axisOrExtruder] * idleCurrentFactor;
IterateDrivers(axisOrExtruder,
[this, requiredCurrent](uint8_t driver){ UpdateMotorCurrent(driver, requiredCurrent); }
#if SUPPORT_CAN_EXPANSION
, [this, requiredCurrent, &canDriversToUpdate](DriverId driver) { canDriversToUpdate.AddEntry(driver, (uint16_t)requiredCurrent); }
#endif
);
}
}
#if SUPPORT_CAN_EXPANSION
String<1> dummy;
(void)CanInterface::SetRemoteDriverCurrents(canDriversToUpdate, dummy.GetRef());
#endif
}
void Platform::SetDriveStepsPerUnit(size_t axisOrExtruder, float value, uint32_t requestedMicrostepping) noexcept
{
if (requestedMicrostepping != 0)
{
const uint32_t currentMicrostepping = microstepping[axisOrExtruder] & 0x7FFF;
if (currentMicrostepping != requestedMicrostepping)
{
value = value * (float)currentMicrostepping / (float)requestedMicrostepping;
}
}
driveStepsPerUnit[axisOrExtruder] = max<float>(value, 1.0); // don't allow zero or negative
}
// Set the microstepping for a driver, returning true if successful
bool Platform::SetDriverMicrostepping(size_t driver, unsigned int microsteps, int mode) noexcept
{
if (driver < NumDirectDrivers)
{
#if HAS_SMART_DRIVERS
if (driver < numSmartDrivers)
{
return SmartDrivers::SetMicrostepping(driver, microsteps, mode);
}
else
{
// Other drivers only support x16 microstepping.
// We ignore the interpolation on/off parameter so that e.g. M350 I1 E16:128 won't give an error if E1 supports interpolation but E0 doesn't.
return microsteps == 16;
}
#elif defined(__ALLIGATOR__)
return Microstepping::Set(driver, microsteps); // no mode in Alligator board
#elif defined(__LPC17xx__)
return Microstepping::Set(driver, microsteps);
#else
// Assume only x16 microstepping supported
return microsteps == 16;
#endif
}
return false;
}
// Set the microstepping, returning true if successful. All drivers for the same axis must use the same microstepping.
bool Platform::SetMicrostepping(size_t axisOrExtruder, int microsteps, bool interp, const StringRef& reply) noexcept
{
//TODO check that it is a valid microstep setting
microstepping[axisOrExtruder] = (interp) ? microsteps | 0x8000 : microsteps;
bool ok = true;
#if SUPPORT_CAN_EXPANSION
CanDriversData canDriversToUpdate;
IterateDrivers(axisOrExtruder,
[this, microsteps, interp, &ok, reply](uint8_t driver)
{
if (!SetDriverMicrostepping(driver, microsteps, interp))
{
reply.lcatf("Driver %u does not support x%u microstepping", driver, microsteps);
if (interp)
{
reply.cat(" with interpolation");
}
ok = false;
}
},
[microsteps, interp, &canDriversToUpdate](DriverId driver)
{
canDriversToUpdate.AddEntry(driver, (interp) ? microsteps | 0x8000 : microsteps);
}
);
return CanInterface::SetRemoteDriverMicrostepping(canDriversToUpdate, reply) && ok;
#else
IterateDrivers(axisOrExtruder,
[this, microsteps, interp, &ok, reply](uint8_t driver)
{
if (!SetDriverMicrostepping(driver, microsteps, interp))
{
reply.lcatf("Driver %u does not support x%u microstepping", driver, microsteps);
if (interp)
{
reply.cat(" with interpolation");
}
ok = false;
}
}
);
return ok;
#endif
}
// Get the microstepping for an axis or extruder
unsigned int Platform::GetMicrostepping(size_t drive, bool& interpolation) const noexcept
{
interpolation = (microstepping[drive] & 0x8000) != 0;
return microstepping[drive] & 0x7FFF;
}
void Platform::SetEnableValue(size_t driver, int8_t eVal) noexcept
{
if (driver < NumDirectDrivers)
{
enableValues[driver] = eVal;
DisableOneLocalDriver(driver); // disable the drive, because the enable polarity may have been wrong before
#if HAS_SMART_DRIVERS
if (eVal == -1)
{
// User has asked to disable status monitoring for this driver, so clear its error bits
DriversBitmap mask = ~MakeBitmap<DriversBitmap>(driver);
temperatureShutdownDrivers &= mask;
temperatureWarningDrivers &= mask;
shortToGroundDrivers &= mask;
openLoadADrivers &= mask;
openLoadBDrivers &= mask;
}
#endif
}
}
void Platform::SetAxisDriversConfig(size_t axis, size_t numValues, const DriverId driverNumbers[]) noexcept
{
AxisDriversConfig& cfg = axisDrivers[axis];
cfg.numDrivers = numValues;
uint32_t bitmap = 0;
for (size_t i = 0; i < numValues; ++i)
{
const DriverId id = driverNumbers[i];
cfg.driverNumbers[i] = id;
if (id.IsLocal())
{
bitmap |= StepPins::CalcDriverBitmap(id.localDriver);
#if HAS_SMART_DRIVERS
SmartDrivers::SetAxisNumber(id.localDriver, axis);
#endif
}
}
driveDriverBits[axis] = bitmap;
}
// Map an extruder to a driver
void Platform::SetExtruderDriver(size_t extruder, DriverId driver) noexcept
{
extruderDrivers[extruder] = driver;
if (driver.IsLocal())
{
#if HAS_SMART_DRIVERS
SmartDrivers::SetAxisNumber(driver.localDriver, ExtruderToLogicalDrive(extruder));
#endif
driveDriverBits[ExtruderToLogicalDrive(extruder)] = StepPins::CalcDriverBitmap(driver.localDriver);
}
else
{
driveDriverBits[ExtruderToLogicalDrive(extruder)] = 0;
}
}
void Platform::SetDriverStepTiming(size_t driver, const float microseconds[4]) noexcept
{
const uint32_t bitmap = StepPins::CalcDriverBitmap(driver);
slowDriversBitmap &= ~bitmap; // start by assuming this drive does not need extended timing
if (slowDriversBitmap == 0)
{
for (uint32_t& entry : slowDriverStepTimingClocks)
{
entry = 0; // reset all to zero if we have no known slow drivers
}
}
for (size_t i = 0; i < ARRAY_SIZE(slowDriverStepTimingClocks); ++i)
{
if (microseconds[i] > MinStepPulseTiming)
{
slowDriversBitmap |= StepPins::CalcDriverBitmap(driver); // this drive does need extended timing
const uint32_t clocks = (uint32_t)(((float)StepTimer::StepClockRate * microseconds[i] * 0.000001) + 0.99); // convert microseconds to step clocks, rounding up
if (clocks > slowDriverStepTimingClocks[i])
{
slowDriverStepTimingClocks[i] = clocks;
}
}
}
}
// Get the driver step timing, returning true if we are using slower timing than standard
bool Platform::GetDriverStepTiming(size_t driver, float microseconds[4]) const noexcept
{
const bool isSlowDriver = ((slowDriversBitmap & StepPins::CalcDriverBitmap(driver)) != 0);
for (size_t i = 0; i < 4; ++i)
{
microseconds[i] = (isSlowDriver)
? (float)slowDriverStepTimingClocks[i] * 1000000.0/(float)StepTimer::StepClockRate
: 0.0;
}
return isSlowDriver;
}
//-----------------------------------------------------------------------------------------------------
void Platform::AppendAuxReply(const char *msg, bool rawMessage) noexcept
{
#ifdef SERIAL_AUX_DEVICE
// Discard this response if either no aux device is attached or if the response is empty
if (msg[0] != 0 && HaveAux())
{
MutexLocker lock(auxMutex);
if (rawMessage)
{
// Raw responses are sent directly to the AUX device
OutputBuffer *buf;
if (OutputBuffer::Allocate(buf))
{
buf->copy(msg);
auxOutput.Push(buf);
}
}
else
{
// Regular text-based responses for AUX are currently stored and processed by M105/M408
if (auxGCodeReply != nullptr || OutputBuffer::Allocate(auxGCodeReply))
{
auxSeq++;
auxGCodeReply->cat(msg);
}
}
}
#endif
}
void Platform::AppendAuxReply(OutputBuffer *reply, bool rawMessage) noexcept
{
#ifdef SERIAL_AUX_DEVICE
// Discard this response if either no aux device is attached or if the response is empty
if (reply == nullptr || reply->Length() == 0 || !HaveAux())
{
OutputBuffer::ReleaseAll(reply);
}
else
{
MutexLocker lock(auxMutex);
if (rawMessage)
{
// JSON responses are always sent directly to the AUX device
// For big responses it makes sense to write big chunks of data in portions. Store this data here
auxOutput.Push(reply);
}
else
{
// Other responses are stored for M105/M408
auxSeq++;
if (auxGCodeReply == nullptr)
{
auxGCodeReply = reply;
}
else
{
auxGCodeReply->Append(reply);
}
}
}
#else
OutputBuffer::ReleaseAll(reply);
#endif
}
// Send the specified message to the specified destinations. The Error and Warning flags have already been handled.
void Platform::RawMessage(MessageType type, const char *message) noexcept
{
#if HAS_MASS_STORAGE
// Deal with logging
if ((type & LogMessage) != 0 && logger != nullptr)
{
logger->LogMessage(realTime, message);
}
#endif
// Send the message to the destinations
if ((type & ImmediateAuxMessage) != 0)
{
SendAuxMessage(message);
}
else if ((type & AuxMessage) != 0)
{
AppendAuxReply(message, message[0] == '{' || (type & RawMessageFlag) != 0);
}
if ((type & HttpMessage) != 0)
{
reprap.GetNetwork().HandleHttpGCodeReply(message);
}
if ((type & TelnetMessage) != 0)
{
reprap.GetNetwork().HandleTelnetGCodeReply(message);
}
if ((type & AuxMessage) != 0)
{
#ifdef SERIAL_AUX2_DEVICE
MutexLocker lock(aux2Mutex);
// Message that is to be sent to the second auxiliary device (blocking)
if (!aux2Output.IsEmpty())
{
// If we're still busy sending a response to the USART device, append this message to the output buffer
aux2Output.GetLastItem()->cat(message);
}
else
{
// Send short strings immediately through the aux channel. There is no flow control on this port, so it can't block for long
SERIAL_AUX2_DEVICE.write(message);
SERIAL_AUX2_DEVICE.flush();
}
#endif
}
if ((type & BlockingUsbMessage) != 0)
{
// Debug output sends messages in blocking mode. We now give up sending if we are close to software watchdog timeout.
MutexLocker lock(usbMutex);
const char *p = message;
size_t len = strlen(p);
while (SERIAL_MAIN_DEVICE.IsConnected() && len != 0 && !reprap.SpinTimeoutImminent())
{
const size_t written = SERIAL_MAIN_DEVICE.write(p, len);
len -= written;
p += written;
}
// We no longer flush afterwards
}
else if ((type & UsbMessage) != 0)
{
// Message that is to be sent via the USB line (non-blocking)
MutexLocker lock(usbMutex);
#if SUPPORT_SCANNER
if (!reprap.GetScanner().IsRegistered() || reprap.GetScanner().DoingGCodes())
#endif
{
// Ensure we have a valid buffer to write to that isn't referenced for other destinations
OutputBuffer *usbOutputBuffer = usbOutput.GetLastItem();
if (usbOutputBuffer == nullptr || usbOutputBuffer->IsReferenced())
{
if (OutputBuffer::Allocate(usbOutputBuffer))
{
if (usbOutput.Push(usbOutputBuffer))
{
usbOutputBuffer->cat(message);
}
// else the message buffer has been released, so discard the message
}
}
else
{
usbOutputBuffer->cat(message); // append the message
}
}
}
}
// Note: this overload of Platform::Message does not process the special action flags in the MessageType.
// Also it treats calls to send a blocking USB message the same as ordinary USB messages,
// and calls to send an immediate LCD message the same as ordinary LCD messages
void Platform::Message(const MessageType type, OutputBuffer *buffer) noexcept
{
#if HAS_MASS_STORAGE
// First deal with logging because it doesn't hang on to the buffer
if ((type & LogMessage) != 0 && logger != nullptr)
{
logger->LogMessage(realTime, buffer);
}
#endif
// Now send the message to all the destinations
size_t numDestinations = 0;
if ((type & (AuxMessage | ImmediateAuxMessage)) != 0)
{
++numDestinations;
}
if ((type & (UsbMessage | BlockingUsbMessage)) != 0)
{
++numDestinations;
}
if ((type & HttpMessage) != 0)
{
++numDestinations;
}
if ((type & TelnetMessage) != 0)
{
++numDestinations;
}
#if HAS_LINUX_INTERFACE
if ((type & GenericMessage) == GenericMessage || (type & BinaryCodeReplyFlag) != 0)
{
++numDestinations;
}
#endif
#ifdef SERIAL_AUX2_DEVICE
if ((type & LcdMessage) != 0)
{
++numDestinations;
}
#endif
if (numDestinations == 0)
{
OutputBuffer::ReleaseAll(buffer);
}
else
{
buffer->IncreaseReferences(numDestinations - 1);
if ((type & (AuxMessage | ImmediateAuxMessage)) != 0)
{
AppendAuxReply(buffer, ((*buffer)[0] == '{') || (type & RawMessageFlag) != 0);
}
if ((type & HttpMessage) != 0)
{
reprap.GetNetwork().HandleHttpGCodeReply(buffer);
}
if ((type & TelnetMessage) != 0)
{
reprap.GetNetwork().HandleTelnetGCodeReply(buffer);
}
#ifdef SERIAL_AUX2_DEVICE
if ((type & LcdMessage) != 0)
{
// Send this message to the second UART device
MutexLocker lock(aux2Mutex);
aux2Output.Push(buffer);
}
#endif
if ((type & (UsbMessage | BlockingUsbMessage)) != 0)
{
MutexLocker lock(usbMutex);
if ( !SERIAL_MAIN_DEVICE.IsConnected()
#if SUPPORT_SCANNER
|| (reprap.GetScanner().IsRegistered() && !reprap.GetScanner().DoingGCodes())
#endif
)
{
// If the serial USB line is not open, discard the message right away
OutputBuffer::ReleaseAll(buffer);
}
else
{
// Else append incoming data to the stack
usbOutput.Push(buffer);
}
}
#if HAS_LINUX_INTERFACE
if ((type & GenericMessage) == GenericMessage || (type & BinaryCodeReplyFlag) != 0)
{
reprap.GetLinuxInterface().HandleGCodeReply(type, buffer);
}
#endif
}
}
void Platform::MessageF(MessageType type, const char *fmt, va_list vargs) noexcept
{
String<FormatStringLength> formatString;
#if HAS_LINUX_INTERFACE
if ((type & GenericMessage) == GenericMessage || (type & BinaryCodeReplyFlag) != 0)
{
formatString.vprintf(fmt, vargs);
reprap.GetLinuxInterface().HandleGCodeReply(type, formatString.c_str());
if ((type & BinaryCodeReplyFlag) != 0)
{
return;
}
}
#endif
if ((type & ErrorMessageFlag) != 0)
{
formatString.copy("Error: ");
formatString.vcatf(fmt, vargs);
}
else if ((type & WarningMessageFlag) != 0)
{
formatString.copy("Warning: ");
formatString.vcatf(fmt, vargs);
}
else
{
formatString.vprintf(fmt, vargs);
}
RawMessage((MessageType)(type & ~(ErrorMessageFlag | WarningMessageFlag)), formatString.c_str());
}
void Platform::MessageF(MessageType type, const char *fmt, ...) noexcept
{
va_list vargs;
va_start(vargs, fmt);
MessageF(type, fmt, vargs);
va_end(vargs);
}
void Platform::Message(MessageType type, const char *message) noexcept
{
#if HAS_LINUX_INTERFACE
if ((type & GenericMessage) == GenericMessage || (type & BinaryCodeReplyFlag) != 0)
{
reprap.GetLinuxInterface().HandleGCodeReply(type, message);
if ((type & BinaryCodeReplyFlag) != 0)
{
return;
}
}
#endif
if ((type & (ErrorMessageFlag | WarningMessageFlag)) == 0)
{
RawMessage(type, message);
}
else
{
String<FormatStringLength> formatString;
formatString.copy(((type & ErrorMessageFlag) != 0) ? "Error: " : "Warning: ");
formatString.cat(message);
RawMessage((MessageType)(type & ~(ErrorMessageFlag | WarningMessageFlag)), formatString.c_str());
}
}
// Send a message box, which may require an acknowledgement
// sParam = 0 Just display the message box, optional timeout
// sParam = 1 As for 0 but display a Close button as well
// sParam = 2 Display the message box with an OK button, wait for acknowledgement (waiting is set up by the caller)
// sParam = 3 As for 2 but also display a Cancel button
void Platform::SendAlert(MessageType mt, const char *message, const char *title, int sParam, float tParam, AxesBitmap controls) noexcept
{
if ((mt & (HttpMessage | AuxMessage | BinaryCodeReplyFlag)) != 0)
{
reprap.SetAlert(message, title, sParam, tParam, controls); // make the RepRap class cache this message until it's picked up by the HTTP clients and/or PanelDue
}
mt = (MessageType)(mt & (UsbMessage | TelnetMessage));
if (mt != 0)
{
if (strlen(title) > 0)
{
MessageF(mt, "- %s -\n", title);
}
MessageF(mt, "%s\n", message);
if (sParam == 2)
{
Message(mt, "Send M292 to continue\n");
}
else if (sParam == 3)
{
Message(mt, "Send M292 to continue or M292 P1 to cancel\n");
}
}
}
#if HAS_MASS_STORAGE
// Configure logging according to the M929 command received, returning true if error
GCodeResult Platform::ConfigureLogging(GCodeBuffer& gb, const StringRef& reply)
{
if (gb.Seen('S'))
{
StopLogging();
if (gb.GetIValue() > 0)
{
// Start logging
if (logger == nullptr)
{
logger = new Logger();
}
else
{
StopLogging();
}
char buf[MaxFilenameLength + 1];
StringRef filename(buf, ARRAY_SIZE(buf));
if (gb.Seen('P'))
{
gb.GetQuotedString(filename);
}
else
{
filename.copy(DEFAULT_LOG_FILE);
}
logger->Start(realTime, filename);
}
}
else
{
reply.printf("Event logging is %s", (logger != nullptr && logger->IsActive()) ? "enabled" : "disabled");
}
return GCodeResult::ok;
}
#endif
// This is called from EmergencyStop. It closes the log file and stops logging.
void Platform::StopLogging() noexcept
{
#if HAS_MASS_STORAGE
if (logger != nullptr)
{
logger->Stop(realTime);
}
#endif
}
bool Platform::AtxPower() const noexcept
{
#ifdef __LPC17xx__
const bool val = IoPort::ReadPin(ATX_POWER_PIN);
return (ATX_POWER_INVERTED) ? !val : val;
#else
return IoPort::ReadPin(ATX_POWER_PIN);
#endif
}
void Platform::AtxPowerOn() noexcept
{
deferredPowerDown = false;
IoPort::WriteDigital(ATX_POWER_PIN, true);
}
void Platform::AtxPowerOff(bool defer) noexcept
{
deferredPowerDown = defer;
if (!defer)
{
#if HAS_MASS_STORAGE
if (logger != nullptr)
{
logger->LogMessage(realTime, "Power off commanded");
logger->Flush(true);
// We don't call logger->Stop() here because we don't know whether turning off the power will work
}
#endif
#ifdef __LPC17xx__
IoPort::WriteDigital(ATX_POWER_PIN, ATX_POWER_INVERTED);
#else
IoPort::WriteDigital(ATX_POWER_PIN, false);
#endif
}
}
GCodeResult Platform::SetPressureAdvance(float advance, GCodeBuffer& gb, const StringRef& reply)
{
GCodeResult rslt = GCodeResult::ok;
#if SUPPORT_CAN_EXPANSION
CanDriversData canDriversToUpdate;
#endif
if (gb.Seen('D'))
{
uint32_t eDrive[MaxExtruders];
size_t eCount = MaxExtruders;
gb.GetUnsignedArray(eDrive, eCount, false);
for (size_t i = 0; i < eCount; i++)
{
const uint32_t extruder = eDrive[i];
if (extruder >= reprap.GetGCodes().GetNumExtruders())
{
reply.printf("Invalid extruder number '%" PRIu32 "'", extruder);
rslt = GCodeResult::error;
break;
}
pressureAdvance[extruder] = advance;
#if SUPPORT_CAN_EXPANSION
if (extruderDrivers[extruder].IsRemote())
{
canDriversToUpdate.AddEntry(extruderDrivers[extruder], (uint16_t)(advance * 1000.0));
}
#endif
}
}
else
{
const Tool * const ct = reprap.GetCurrentTool();
if (ct == nullptr)
{
reply.copy("No tool selected");
rslt = GCodeResult::error;
}
else
{
#if SUPPORT_CAN_EXPANSION
ct->IterateExtruders([this, advance, &canDriversToUpdate](unsigned int extruder)
{
pressureAdvance[extruder] = advance;
if (extruderDrivers[extruder].IsRemote())
{
canDriversToUpdate.AddEntry(extruderDrivers[extruder], (uint16_t)(advance * 1000.0));
}
}
);
#else
ct->IterateExtruders([this, advance](unsigned int extruder)
{
pressureAdvance[extruder] = advance;
}
);
#endif
}
}
#if SUPPORT_CAN_EXPANSION
const bool remoteOk = CanInterface::SetRemotePressureAdvance(canDriversToUpdate, reply);
return (remoteOk) ? rslt : GCodeResult::error;
#else
return rslt;
#endif
}
#if SUPPORT_NONLINEAR_EXTRUSION
bool Platform::GetExtrusionCoefficients(size_t extruder, float& a, float& b, float& limit) const noexcept
{
if (extruder < MaxExtruders)
{
a = nonlinearExtrusionA[extruder];
b = nonlinearExtrusionB[extruder];
limit = nonlinearExtrusionLimit[extruder];
return true;
}
return false;
}
void Platform::SetNonlinearExtrusion(size_t extruder, float a, float b, float limit) noexcept
{
if (extruder < MaxExtruders && nonlinearExtrusionLimit[extruder] > 0.0)
{
nonlinearExtrusionLimit[extruder] = limit;
nonlinearExtrusionA[extruder] = a;
nonlinearExtrusionB[extruder] = b;
}
}
#endif
void Platform::SetBaudRate(size_t chan, uint32_t br) noexcept
{
if (chan < NUM_SERIAL_CHANNELS)
{
baudRates[chan] = br;
ResetChannel(chan);
}
}
uint32_t Platform::GetBaudRate(size_t chan) const noexcept
{
return (chan < NUM_SERIAL_CHANNELS) ? baudRates[chan] : 0;
}
void Platform::SetCommsProperties(size_t chan, uint32_t cp) noexcept
{
if (chan < NUM_SERIAL_CHANNELS)
{
commsParams[chan] = cp;
ResetChannel(chan);
}
}
uint32_t Platform::GetCommsProperties(size_t chan) const noexcept
{
return (chan < NUM_SERIAL_CHANNELS) ? commsParams[chan] : 0;
}
// Re-initialise a serial channel.
void Platform::ResetChannel(size_t chan) noexcept
{
switch(chan)
{
case 0:
SERIAL_MAIN_DEVICE.end();
#if defined(__LPC17xx__)
SERIAL_MAIN_DEVICE.begin(baudRates[0]);
#else
SERIAL_MAIN_DEVICE.Start(UsbVBusPin);
#endif
break;
#ifdef SERIAL_AUX_DEVICE
case 1:
SERIAL_AUX_DEVICE.end();
SERIAL_AUX_DEVICE.begin(baudRates[1]);
break;
#endif
#ifdef SERIAL_AUX2_DEVICE
case 2:
SERIAL_AUX2_DEVICE.end();
SERIAL_AUX2_DEVICE.begin(baudRates[2]);
break;
#endif
default:
break;
}
}
void Platform::SetBoardType(BoardType bt) noexcept
{
if (bt == BoardType::Auto)
{
#if defined(DUET3)
board = BoardType::Duet3;
#elif defined(SAME70XPLD)
board = BoardType::SAME70XPLD_0;
#elif defined(DUET_NG)
// Get ready to test whether the Ethernet module is present, so that we avoid additional delays
pinMode(EspResetPin, OUTPUT_LOW); // reset the WiFi module or the W5500. We assume that this forces the ESP8266 UART output pin to high impedance.
pinMode(W5500ModuleSensePin, INPUT_PULLUP); // set our UART receive pin to be an input pin and enable the pullup
// Set up the VSSA sense pin. Older Duet WiFis don't have it connected, so we enable the pulldown resistor to keep it inactive.
pinMode(VssaSensePin, INPUT_PULLUP);
delayMicroseconds(10);
const bool vssaHighVal = digitalRead(VssaSensePin);
pinMode(VssaSensePin, INPUT_PULLDOWN);
delayMicroseconds(10);
const bool vssaLowVal = digitalRead(VssaSensePin);
const bool vssaSenseWorking = vssaLowVal || !vssaHighVal;
if (vssaSenseWorking)
{
pinMode(VssaSensePin, INPUT);
}
// Test whether the Ethernet module is present
if (digitalRead(W5500ModuleSensePin)) // the Ethernet module has this pin grounded
{
board = (vssaSenseWorking) ? BoardType::DuetWiFi_102 : BoardType::DuetWiFi_10;
}
else
{
board = (vssaSenseWorking) ? BoardType::DuetEthernet_102 : BoardType::DuetEthernet_10;
}
#elif defined(DUET_M)
board = BoardType::DuetM_10;
#elif defined(DUET_06_085)
// Determine whether this is a Duet 0.6 or a Duet 0.8.5 board.
// If it is a 0.85 board then DAC0 (AKA digital pin 67) is connected to ground via a diode and a 2.15K resistor.
// So we enable the pullup (value 100K-150K) on pin 67 and read it, expecting a LOW on a 0.8.5 board and a HIGH on a 0.6 board.
// This may fail if anyone connects a load to the DAC0 pin on a Duet 0.6, hence we implement board selection in M115 as well.
pinMode(Dac0DigitalPin, INPUT_PULLUP);
delayMicroseconds(10);
board = (digitalRead(Dac0DigitalPin)) ? BoardType::Duet_06 : BoardType::Duet_085;
pinMode(Dac0DigitalPin, INPUT); // turn pullup off
#elif defined(__RADDS__)
board = BoardType::RADDS_15;
#elif defined(__ALLIGATOR__)
board = BoardType::Alligator_2;
#elif defined(PCCB_10)
board = BoardType::PCCB_v10;
#elif defined(PCCB_08) || defined(PCCB_08_X5)
board = BoardType::PCCB_v08;
#elif defined(__LPC17xx__)
board = BoardType::Lpc;
#else
# error Undefined board type
#endif
}
else
{
board = bt;
}
}
// Get a string describing the electronics
const char* Platform::GetElectronicsString() const noexcept
{
switch (board)
{
#if defined(DUET3)
case BoardType::Duet3: return "Duet 3 " BOARD_SHORT_NAME;
#elif defined(SAME70XPLD)
case BoardType::SAME70XPLD_0: return "SAME70-XPLD";
#elif defined(DUET_NG)
case BoardType::DuetWiFi_10: return "Duet WiFi 1.0 or 1.01";
case BoardType::DuetWiFi_102: return "Duet WiFi 1.02 or later";
case BoardType::DuetEthernet_10: return "Duet Ethernet 1.0 or 1.01";
case BoardType::DuetEthernet_102: return "Duet Ethernet 1.02 or later";
#elif defined(DUET_M)
case BoardType::DuetM_10: return "Duet Maestro 1.0";
#elif defined(DUET_06_085)
case BoardType::Duet_06: return "Duet 0.6";
case BoardType::Duet_07: return "Duet 0.7";
case BoardType::Duet_085: return "Duet 0.85";
#elif defined(__RADDS__)
case BoardType::RADDS_15: return "RADDS 1.5";
#elif defined(__ALLIGATOR__)
case BoardType::Alligator_2: return "Alligator r2";
#elif defined(PCCB_10)
case BoardType::PCCB_v10: return "PC001373";
#elif defined(PCCB_08) || defined(PCCB_08_X5)
case BoardType::PCCB_v08: return "PCCB 0.8";
#elif defined(__LPC17xx__)
case BoardType::Lpc: return LPC_ELECTRONICS_STRING;
#else
# error Undefined board type
#endif
default: return "Unidentified";
}
}
// Get the board string
const char* Platform::GetBoardString() const noexcept
{
switch (board)
{
#if defined(DUET3)
case BoardType::Duet3:
# if defined(DUET3_V03)
return "duet3proto3";
# elif defined(DUET3_V05)
return "duet3proto5";
# elif defined(DUET3_V06)
return "duet3mb6hc";
# endif
#elif defined(SAME70XPLD)
case BoardType::SAME70XPLD_0: return "same70xpld";
#elif defined(DUET_NG)
case BoardType::DuetWiFi_10: return "duetwifi10";
case BoardType::DuetWiFi_102: return "duetwifi102";
case BoardType::DuetEthernet_10: return "duetethernet10";
case BoardType::DuetEthernet_102: return "duetethernet102";
#elif defined(DUET_M)
case BoardType::DuetM_10: return "duetmaestro100";
#elif defined(DUET_06_085)
case BoardType::Duet_06: return "duet06";
case BoardType::Duet_07: return "duet07";
case BoardType::Duet_085: return "duet085";
#elif defined(__RADDS__)
case BoardType::RADDS_15: return "radds15";
#elif defined(__ALLIGATOR__)
case BoardType::Alligator_2: return "alligator2";
#elif defined(PCCB_10)
case BoardType::PCCB_v10: return "pc001373";
#elif defined(PCCB_08) || defined(PCCB_08_X5)
case BoardType::PCCB_v08: return "pccb08";
#elif defined(__LPC17xx__)
case BoardType::Lpc: return LPC_BOARD_STRING;
#else
# error Undefined board type
#endif
default: return "unknown";
}
}
#ifdef DUET_NG
// Return true if this is a Duet WiFi, false if it is a Duet Ethernet
bool Platform::IsDuetWiFi() const noexcept
{
return board == BoardType::DuetWiFi_10 || board == BoardType::DuetWiFi_102;
}
const char *Platform::GetBoardName() const
{
return (IsDuetWiFi()) ? BOARD_NAME_WIFI : BOARD_NAME_ETHERNET;
}
const char *Platform::GetBoardShortName() const
{
return (IsDuetWiFi()) ? BOARD_SHORT_NAME_WIFI : BOARD_SHORT_NAME_ETHERNET;
}
#endif
#if HAS_MASS_STORAGE
// Where the system files are. Not thread safe!
const char* Platform::InternalGetSysDir() const noexcept
{
return (sysDir != nullptr) ? sysDir : DEFAULT_SYS_DIR;
}
// Open a file
FileStore* Platform::OpenFile(const char* folder, const char* fileName, OpenMode mode, uint32_t preAllocSize) const noexcept
{
String<MaxFilenameLength> location;
return (MassStorage::CombineName(location.GetRef(), folder, fileName))
? MassStorage::OpenFile(location.c_str(), mode, preAllocSize)
: nullptr;
}
bool Platform::Delete(const char* folder, const char *filename) const noexcept
{
String<MaxFilenameLength> location;
return MassStorage::CombineName(location.GetRef(), folder, filename) && MassStorage::Delete(location.c_str());
}
bool Platform::FileExists(const char* folder, const char *filename) const noexcept
{
String<MaxFilenameLength> location;
return MassStorage::CombineName(location.GetRef(), folder, filename) && MassStorage::FileExists(location.c_str());
}
bool Platform::DirectoryExists(const char *folder, const char *dir) const noexcept
{
String<MaxFilenameLength> location;
return MassStorage::CombineName(location.GetRef(), folder, dir) && MassStorage::DirectoryExists(location.c_str());
}
// Set the system files path
GCodeResult Platform::SetSysDir(const char* dir, const StringRef& reply) noexcept
{
String<MaxFilenameLength> newSysDir;
MutexLocker lock(Tasks::GetSysDirMutex());
if (!MassStorage::CombineName(newSysDir.GetRef(), InternalGetSysDir(), dir) || (!newSysDir.EndsWith('/') && newSysDir.cat('/')))
{
reply.copy("Path name too long");
return GCodeResult::error;
}
const size_t len = newSysDir.strlen() + 1;
char* const nsd = new char[len];
memcpy(nsd, newSysDir.c_str(), len);
const char *nsd2 = nsd;
std::swap(sysDir, nsd2);
delete nsd2;
return GCodeResult::ok;
}
bool Platform::SysFileExists(const char *filename) const noexcept
{
String<MaxFilenameLength> location;
return MakeSysFileName(location.GetRef(), filename) && MassStorage::FileExists(location.c_str());
}
FileStore* Platform::OpenSysFile(const char *filename, OpenMode mode) const noexcept
{
String<MaxFilenameLength> location;
return (MakeSysFileName(location.GetRef(), filename))
? MassStorage::OpenFile(location.c_str(), mode, 0)
: nullptr;
}
bool Platform::DeleteSysFile(const char *filename) const noexcept
{
String<MaxFilenameLength> location;
return MakeSysFileName(location.GetRef(), filename) && MassStorage::Delete(location.c_str());
}
bool Platform::MakeSysFileName(const StringRef& result, const char *filename) const noexcept
{
MutexLocker lock(Tasks::GetSysDirMutex());
return MassStorage::CombineName(result, InternalGetSysDir(), filename);
}
void Platform::GetSysDir(const StringRef & path) const noexcept
{
MutexLocker lock(Tasks::GetSysDirMutex());
path.copy(InternalGetSysDir());
}
#endif
// CNC and laser support
void Platform::SetLaserPwm(Pwm_t pwm) noexcept
{
lastLaserPwm = (float)pwm/65535;
laserPort.WriteAnalog(lastLaserPwm); // we don't currently have an function that accepts an integer PWM fraction
}
// Return laser PWM in 0..1
float Platform::GetLaserPwm() const noexcept
{
return lastLaserPwm;
}
bool Platform::AssignLaserPin(GCodeBuffer& gb, const StringRef& reply)
{
const bool ok = laserPort.AssignPort(gb, reply, PinUsedBy::laser, PinAccess::pwm);
if (ok)
{
SetLaserPwm(0);
}
return ok;
}
void Platform::SetLaserPwmFrequency(PwmFrequency freq) noexcept
{
laserPort.SetFrequency(freq);
}
// Axis limits
void Platform::SetAxisMaximum(size_t axis, float value, bool byProbing) noexcept
{
axisMaxima[axis] = value;
if (byProbing)
{
SetBit(axisMaximaProbed, axis);
}
}
void Platform::SetAxisMinimum(size_t axis, float value, bool byProbing) noexcept
{
axisMinima[axis] = value;
if (byProbing)
{
SetBit(axisMinimaProbed, axis);
}
}
ZProbeType Platform::GetCurrentZProbeType() const noexcept
{
return endstops.GetCurrentZProbe().GetProbeType();
}
void Platform::InitZProbeFilters() noexcept
{
zProbeOnFilter.Init(0);
zProbeOffFilter.Init(0);
}
#if SUPPORT_INKJET
// Fire the inkjet (if any) in the given pattern
// If there is no inkjet, false is returned; if there is one this returns true
// So you can test for inkjet presence with if(platform->Inkjet(0))
bool Platform::Inkjet(int bitPattern) noexcept
{
if (inkjetBits < 0)
return false;
if (!bitPattern)
return true;
for(int8_t i = 0; i < inkjetBits; i++)
{
if (bitPattern & 1)
{
digitalWrite(inkjetSerialOut, 1); // Write data to shift register
for(int8_t j = 0; j <= i; j++)
{
digitalWrite(inkjetShiftClock, HIGH);
digitalWrite(inkjetShiftClock, LOW);
digitalWrite(inkjetSerialOut, 0);
}
digitalWrite(inkjetStorageClock, HIGH); // Transfers data from shift register to output register
digitalWrite(inkjetStorageClock, LOW);
digitalWrite(inkjetOutputEnable, LOW); // Fire the droplet out
delayMicroseconds(inkjetFireMicroseconds);
digitalWrite(inkjetOutputEnable, HIGH);
digitalWrite(inkjetClear, LOW); // Clear to 0
digitalWrite(inkjetClear, HIGH);
delayMicroseconds(inkjetDelayMicroseconds); // Wait for the next bit
}
bitPattern >>= 1; // Put the next bit in the units column
}
return true;
}
#endif
#if HAS_CPU_TEMP_SENSOR
// CPU temperature
MinMaxCurrent Platform::GetMcuTemperatures() const noexcept
{
MinMaxCurrent result;
result.min = AdcReadingToCpuTemperature(lowestMcuTemperature);
result.current = AdcReadingToCpuTemperature(adcFilters[CpuTempFilterIndex].GetSum());
result.max = AdcReadingToCpuTemperature(highestMcuTemperature);
return result;
}
#endif
#if HAS_VOLTAGE_MONITOR
// Power in voltage
MinMaxCurrent Platform::GetPowerVoltages() const noexcept
{
MinMaxCurrent result;
result.min = AdcReadingToPowerVoltage(lowestVin);
result.current = AdcReadingToPowerVoltage(currentVin);
result.max = AdcReadingToPowerVoltage(highestVin);
return result;
}
float Platform::GetCurrentPowerVoltage() const noexcept
{
return AdcReadingToPowerVoltage(currentVin);
}
#endif
#if HAS_12V_MONITOR
MinMaxCurrent Platform::GetV12Voltages() const noexcept
{
MinMaxCurrent result;
result.min = AdcReadingToPowerVoltage(lowestV12);
result.current = AdcReadingToPowerVoltage(currentV12);
result.max = AdcReadingToPowerVoltage(highestV12);
return result;
}
#endif
#if HAS_SMART_DRIVERS
// TMC driver temperatures
float Platform::GetTmcDriversTemperature(unsigned int board) const noexcept
{
#if defined(DUET3)
const uint16_t mask = LowestNBits<uint16_t>(6); // there are 6 drivers, only one board
#elif defined(DUET_NG)
const uint16_t mask = LowestNBits<uint16_t>(5) << (5 * board); // there are 5 drivers on each board
#elif defined(DUET_M)
const uint16_t mask = (board == 0)
? LowestNBits<uint16_t>(5) // drivers 0-4 are on the main board
: LowestNBits<uint16_t>(2) << 5; // drivers 5-6 are on the daughter board
#elif defined(PCCB_10)
const uint16_t mask = (board == 0)
? LowestNBits<uint16_t>(2) // drivers 0,1 are on-board
: LowestNBits<uint16_t>(5) << 2; // drivers 2-7 are on the DueX5
#elif defined(PCCB_08_X5)
const uint16_t mask = LowestNBits<uint16_t>(5); // all drivers (0-4) are on the DueX, no further expansion supported
#elif defined(PCCB_08)
const uint16_t mask = LowestNBits<uint16_t>(2); // drivers 0, 1 are on-board, no expansion supported
#endif
return ((temperatureShutdownDrivers & mask) != 0) ? 150.0
: ((temperatureWarningDrivers & mask) != 0) ? 100.0
: 0.0;
}
#endif
#if HAS_STALL_DETECT
// Configure the motor stall detection, returning true if an error was encountered
GCodeResult Platform::ConfigureStallDetection(GCodeBuffer& gb, const StringRef& reply, OutputBuffer *& buf)
{
// Build a bitmap of all the drivers referenced
// First looks for explicit driver numbers
DriversBitmap drivers = 0;
#if SUPPORT_CAN_EXPANSION
CanDriversList canDrivers;
#endif
if (gb.Seen('P'))
{
DriverId drives[NumDirectDrivers];
size_t dCount = NumDirectDrivers;
gb.GetDriverIdArray(drives, dCount);
for (size_t i = 0; i < dCount; i++)
{
if (drives[i].IsLocal())
{
if (drives[i].localDriver >= numSmartDrivers)
{
reply.printf("Invalid local drive number '%u'", drives[i].localDriver);
return GCodeResult::error;
}
SetBit(drivers, drives[i].localDriver);
}
#if SUPPORT_CAN_EXPANSION
else
{
canDrivers.AddEntry(drives[i]);
}
#endif
}
}
// Now look for axes
for (size_t axis = 0; axis < reprap.GetGCodes().GetTotalAxes(); ++axis)
{
if (gb.Seen(reprap.GetGCodes().GetAxisLetters()[axis]))
{
IterateDrivers(axis,
[&drivers](uint8_t driver){ SetBit(drivers, driver); }
#if SUPPORT_CAN_EXPANSION
, [&canDrivers](DriverId driver){ canDrivers.AddEntry(driver); }
#endif
);
}
}
// Look for extruders
if (gb.Seen('E'))
{
uint32_t extruderNumbers[MaxExtruders];
size_t numSeen = MaxExtruders;
gb.GetUnsignedArray(extruderNumbers, numSeen, false);
for (size_t i = 0; i < numSeen; ++i)
{
if (extruderNumbers[i] < MaxExtruders)
{
const DriverId driver = GetExtruderDriver(extruderNumbers[i]);
if (driver.IsLocal())
{
SetBit(drivers, driver.localDriver);
}
#if SUPPORT_CAN_EXPANSION
else
{
canDrivers.AddEntry(driver);
}
#endif
}
}
}
// Now check for values to change
bool seen = false;
if (gb.Seen('S'))
{
seen = true;
const int sgThreshold = gb.GetIValue();
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
if (IsBitSet(drivers, drive))
{
SmartDrivers::SetStallThreshold(drive, sgThreshold);
}
}
}
if (gb.Seen('F'))
{
seen = true;
const bool sgFilter = (gb.GetIValue() == 1);
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
if (IsBitSet(drivers, drive))
{
SmartDrivers::SetStallFilter(drive, sgFilter);
}
}
}
if (gb.Seen('H'))
{
seen = true;
const unsigned int stepsPerSecond = gb.GetUIValue();
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
if (IsBitSet(drivers, drive))
{
SmartDrivers::SetStallMinimumStepsPerSecond(drive, stepsPerSecond);
}
}
}
if (gb.Seen('T'))
{
seen = true;
const uint16_t coolStepConfig = (uint16_t)gb.GetUIValue();
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
if (IsBitSet(drivers, drive))
{
SmartDrivers::SetRegister(drive, SmartDriverRegister::coolStep, coolStepConfig);
}
}
}
if (gb.Seen('R'))
{
seen = true;
const int action = gb.GetIValue();
switch (action)
{
case 0:
default:
logOnStallDrivers &= ~drivers;
pauseOnStallDrivers &= ~drivers;
rehomeOnStallDrivers &= ~drivers;
break;
case 1:
rehomeOnStallDrivers &= ~drivers;
pauseOnStallDrivers &= ~drivers;
logOnStallDrivers |= drivers;
break;
case 2:
logOnStallDrivers &= ~drivers;
rehomeOnStallDrivers &= ~drivers;
pauseOnStallDrivers |= drivers;
break;
case 3:
logOnStallDrivers &= ~drivers;
pauseOnStallDrivers &= ~drivers;
rehomeOnStallDrivers |= drivers;
break;
}
}
if (seen)
{
#if SUPPORT_CAN_EXPANSION
return CanInterface::SetRemoteDriverStallParameters(canDrivers, gb, reply);
#else
return GCodeResult::ok;
#endif
}
// Print the stall status
if (!OutputBuffer::Allocate(buf))
{
return GCodeResult::notFinished;
}
if (drivers == 0)
{
drivers = LowestNBits<DriversBitmap>(numSmartDrivers);
}
bool printed = false;
for (size_t drive = 0; drive < numSmartDrivers; ++drive)
{
if (IsBitSet(drivers, drive))
{
if (printed)
{
buf->cat('\n');
}
buf->catf("Driver %u: ", drive);
reply.Clear(); // we use 'reply' as a temporary buffer
SmartDrivers::AppendStallConfig(drive, reply);
buf->cat(reply.c_str());
buf->catf(", action: %s",
(IsBitSet(rehomeOnStallDrivers, drive)) ? "rehome"
: (IsBitSet(pauseOnStallDrivers, drive)) ? "pause"
: (IsBitSet(logOnStallDrivers, drive)) ? "log"
: "none"
);
printed = true;
}
}
return GCodeResult::ok;
}
#endif
// Real-time clock
bool Platform::SetDateTime(time_t time) noexcept
{
struct tm brokenDateTime;
const bool ok = (gmtime_r(&time, &brokenDateTime) != nullptr);
if (ok)
{
realTime = time; // set the date and time
// Write a log message, giving the time since power up in same format as the logger does
const uint32_t timeSincePowerUp = (uint32_t)(millis64()/1000u);
MessageF(LogMessage, "Date and time set at power up + %02" PRIu32 ":%02" PRIu32 ":%02" PRIu32 "\n", timeSincePowerUp/3600u, (timeSincePowerUp % 3600u)/60u, timeSincePowerUp % 60u);
timeLastUpdatedMillis = millis();
}
return ok;
}
// Configure an I/O port
GCodeResult Platform::ConfigurePort(GCodeBuffer& gb, const StringRef& reply)
{
// Exactly one of FHPS is allowed
unsigned int charsPresent = 0;
uint32_t deviceNumber = 0;
for (char c : (const char[]){'F', 'H', 'P', 'S'})
{
charsPresent <<= 1;
if (gb.Seen(c))
{
deviceNumber = gb.GetUIValue();
charsPresent |= 1;
}
}
switch (charsPresent)
{
case 1:
return ConfigureGpioOrServo(deviceNumber, true, gb, reply);
case 2:
return ConfigureGpioOrServo(deviceNumber, false, gb, reply);
case 4:
return reprap.GetHeat().ConfigureHeater(deviceNumber, gb, reply);
case 8:
return reprap.GetFansManager().ConfigureFanPort(deviceNumber, gb, reply);
default:
reply.copy("exactly one of FHPS must be given");
return GCodeResult::error;
}
}
GCodeResult Platform::ConfigureGpioOrServo(uint32_t gpioNumber, bool isServo, GCodeBuffer& gb, const StringRef& reply)
{
if (gpioNumber < MaxGpioPorts)
{
PwmFrequency freq = 0;
const bool seenFreq = gb.Seen('Q');
if (seenFreq)
{
freq = gb.GetPwmFrequency();
}
GpOutputPort& gpPort = gpioPorts[gpioNumber];
if (gb.Seen('C'))
{
String<StringLength50> pinName;
gb.GetReducedString(pinName.GetRef());
// Remove any existing assignment
#if SUPPORT_CAN_EXPANSION
if (gpPort.boardAddress != CanId::MasterAddress)
{
CanMessageGenericConstructor cons(M950GpioParams);
cons.AddUParam('P', gpioNumber);
cons.AddStringParam('C', NoPinName);
if (cons.SendAndGetResponse(CanMessageType::m950Gpio, gpPort.boardAddress, reply) != GCodeResult::ok)
{
reprap.GetPlatform().Message(WarningMessage, reply.c_str());
reply.Clear();
}
gpPort.boardAddress = CanId::MasterAddress;
}
#endif
gpPort.port.Release();
if (!seenFreq)
{
freq = (isServo) ? ServoRefreshFrequency : DefaultPinWritePwmFreq;
}
#if SUPPORT_CAN_EXPANSION
gpPort.boardAddress = IoPort::RemoveBoardAddress(pinName.GetRef());
if (gpPort.boardAddress != CanId::MasterAddress)
{
CanMessageGenericConstructor cons(M950GpioParams);
cons.AddUParam('P', gpioNumber);
cons.AddUParam('Q', freq);
cons.AddUParam('S', (isServo) ? 1 : 0);
cons.AddStringParam('C', pinName.c_str());
return cons.SendAndGetResponse(CanMessageType::m950Gpio, gpPort.boardAddress, reply);
}
#endif
if (!gpPort.port.AssignPort(pinName.c_str(), reply, PinUsedBy::gpio, (isServo) ? PinAccess::servo : PinAccess::pwm))
{
return GCodeResult::error;
}
gpPort.port.SetFrequency(freq);
}
else if (seenFreq)
{
#if SUPPORT_CAN_EXPANSION
if (gpPort.boardAddress != CanId::MasterAddress)
{
CanMessageGenericConstructor cons(M950GpioParams);
cons.AddUParam('P', gpioNumber);
cons.AddUParam('Q', freq);
return cons.SendAndGetResponse(CanMessageType::m950Gpio, gpPort.boardAddress, reply);
}
#endif
gpPort.port.SetFrequency(freq);
}
else
{
#if SUPPORT_CAN_EXPANSION
if (gpPort.boardAddress != CanId::MasterAddress)
{
CanMessageGenericConstructor cons(M950GpioParams);
cons.AddUParam('P', gpioNumber);
return cons.SendAndGetResponse(CanMessageType::m950Gpio, gpPort.boardAddress, reply);
}
#endif
reply.printf("GPIO/servo port %" PRIu32, gpioNumber);
gpPort.port.AppendDetails(reply);
}
return GCodeResult::ok;
}
reply.copy("GPIO port number out of range");
return GCodeResult::error;
}
// Configure the ancillary PWM
GCodeResult Platform::GetSetAncillaryPwm(GCodeBuffer& gb, const StringRef& reply)
{
bool seen = false;
if (gb.Seen('P'))
{
seen = true;
if (!extrusionAncilliaryPwmPort.AssignPort(gb, reply, PinUsedBy::gpio, PinAccess::pwm))
{
return GCodeResult::error;
}
const PwmFrequency freq = (gb.Seen('F')) ? gb.GetPwmFrequency() : DefaultPinWritePwmFreq;
extrusionAncilliaryPwmPort.SetFrequency(freq);
}
if (gb.Seen('S'))
{
extrusionAncilliaryPwmValue = min<float>(gb.GetFValue(), 1.0); // negative values are OK, they mean don't set the output
seen = true;
}
if (!seen)
{
reply.copy("Extrusion ancillary PWM");
extrusionAncilliaryPwmPort.AppendDetails(reply);
}
return GCodeResult::ok;
}
#if SAM4E || SAM4S || SAME70
// Get a pseudo-random number
uint32_t Platform::Random() noexcept
{
const uint32_t clocks = StepTimer::GetTimerTicks();
return clocks ^ uniqueId[0] ^ uniqueId[1] ^ uniqueId[2] ^ uniqueId[3];
}
#endif
// Process a 1ms tick interrupt
// This function must be kept fast so as not to disturb the stepper timing, so don't do any floating point maths in here.
// This is what we need to do:
// 1. Kick off a new ADC conversion.
// 2. Fetch and process the result of the last ADC conversion.
// 3a. If the last ADC conversion was for the Z probe, toggle the modulation output if using a modulated IR sensor.
// 3b. If the last ADC reading was a thermistor reading, check for an over-temperature situation and turn off the heater if necessary.
// We do this here because the usual polling loop sometimes gets stuck trying to send data to the USB port.
void Platform::Tick() noexcept
{
AnalogInFinaliseConversion();
#if HAS_VOLTAGE_MONITOR || HAS_12V_MONITOR
if (tickState != 0)
{
# if HAS_VOLTAGE_MONITOR
// Read the power input voltage
currentVin = AnalogInReadChannel(vInMonitorAdcChannel);
if (currentVin > highestVin)
{
highestVin = currentVin;
}
if (currentVin < lowestVin)
{
lowestVin = currentVin;
}
# endif
# if HAS_12V_MONITOR
currentV12 = AnalogInReadChannel(v12MonitorAdcChannel);
if (currentV12 > highestV12)
{
highestV12 = currentV12;
}
if (currentV12 < lowestV12)
{
lowestV12 = currentV12;
}
# endif
# if HAS_SMART_DRIVERS && (ENFORCE_MAX_VIN || ENFORCE_MIN_V12)
if (driversPowered &&
# if ENFORCE_MAX_VIN && ENFORCE_MIN_V12
(currentVin > driverOverVoltageAdcReading || currentV12 < driverV12OffAdcReading)
# elif ENFORCE_MAX_VIN
currentVin > driverOverVoltageAdcReading
# elif ENFORCE_MIN_V12
currentV12 < driverV12OffAdcReading
# endif
)
{
SmartDrivers::TurnDriversOff();
// We deliberately do not clear driversPowered here or increase the over voltage event count - we let the spin loop handle that
}
# endif
}
#endif
#if SAME70
// The SAME70 ADC is noisy, so read a thermistor on every tick so that we can average a greater number of readings
// Because we are in the tick ISR and no other ISR reads the averaging filter, we can cast away 'volatile' here.
if (tickState != 0)
{
ThermistorAveragingFilter& currentFilter = const_cast<ThermistorAveragingFilter&>(adcFilters[currentFilterNumber]); // cast away 'volatile'
currentFilter.ProcessReading(AnalogInReadChannel(filteredAdcChannels[currentFilterNumber]));
++currentFilterNumber;
if (currentFilterNumber == NumAdcFilters)
{
currentFilterNumber = 0;
}
}
#endif
const ZProbe& currentZProbe = GetCurrentZProbe();
switch (tickState)
{
case 1:
case 3:
{
#if !SAME70
// We read a filtered ADC channel on alternate ticks
// Because we are in the tick ISR and no other ISR reads the averaging filter, we can cast away 'volatile' here.
ThermistorAveragingFilter& currentFilter = const_cast<ThermistorAveragingFilter&>(adcFilters[currentFilterNumber]); // cast away 'volatile'
currentFilter.ProcessReading(AnalogInReadChannel(filteredAdcChannels[currentFilterNumber]));
++currentFilterNumber;
if (currentFilterNumber == NumAdcFilters)
{
currentFilterNumber = 0;
}
#endif
// If we are not using a simple modulated IR sensor, process the Z probe reading on every tick for a faster response.
// If we are using a simple modulated IR sensor then we need to allow the reading to settle after turning the IR emitter on or off,
// so on alternate ticks we read it and switch the emitter
if (currentZProbe.GetProbeType() != ZProbeType::dumbModulated)
{
const_cast<ZProbeAveragingFilter&>((tickState == 1) ? zProbeOnFilter : zProbeOffFilter).ProcessReading(currentZProbe.GetRawReading());
}
++tickState;
}
break;
case 2:
const_cast<ZProbeAveragingFilter&>(zProbeOnFilter).ProcessReading(currentZProbe.GetRawReading());
currentZProbe.SetIREmitter(false);
++tickState;
break;
case 4: // last conversion started was the Z probe, with IR LED off if modulation is enabled
const_cast<ZProbeAveragingFilter&>(zProbeOffFilter).ProcessReading(currentZProbe.GetRawReading());
currentZProbe.SetIREmitter(true);
tickState = 1;
break;
case 0: // this is the state after initialisation, no conversion has been started
default:
currentZProbe.SetIREmitter(true);
tickState = 1;
break;
}
#if SAME70
// On Duet 3, AFEC1 is used only for thermistors and associated Vref/Vssa monitoring. AFEC0 is used for everything else.
// To reduce noise, we use x16 hardware averaging on AFEC0 and x256 on AFEC1. This is hard coded in file AnalogIn.cpp in project CoreNG.
// There is enough time to convert all AFEC0 channels in one tick, but only one AFEC1 channel because of the higher averaging.
AnalogInStartConversion(0x0FFF | (1u << filteredAdcChannels[currentFilterNumber]));
#else
AnalogInStartConversion();
#endif
}
// Pragma pop_options is not supported on this platform
//#pragma GCC pop_options
// End
|