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
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
|
//******************************************
// NINTENDO 64 MODULE
//******************************************
#ifdef ENABLE_N64
/******************************************
Defines
*****************************************/
// These two macros toggle the eepDataPin/ControllerDataPin between input and output
// External 1K pull-up resistor from eepDataPin to VCC required
// 0x10 = 00010000 -> Port H Pin 4
#define N64_HIGH DDRH &= ~0x10
#define N64_LOW DDRH |= 0x10
// Read the current state(0/1) of the eepDataPin
#define N64_QUERY (PINH & 0x10)
/******************************************
Variables
*****************************************/
// Received N64 Eeprom data bits, 1 page
int eepPages;
// N64 Controller
struct {
char stick_x;
char stick_y;
} N64_status;
//stings that hold the buttons
String button = "N/A";
String lastbutton = "N/A";
// Rom base address
unsigned long romBase = 0x10000000;
// Flashram type
byte flashramType = 1;
boolean MN63F81MPN = false;
//ControllerTest
bool quit = 1;
#ifdef OPTION_N64_SAVESUMMARY
String CRC1 = "";
String CRC2 = "";
#endif
#if (!defined(ENABLE_FLASH8) && !(defined(ENABLE_MD) && defined(ENABLE_FLASH)))
unsigned long flashSize;
#endif
/******************************************
Menu
*****************************************/
// N64 start menu
static const char n64MenuItem1[] PROGMEM = "Game Cartridge";
static const char n64MenuItem2[] PROGMEM = "Controller";
static const char n64MenuItem3[] PROGMEM = "Flash Repro";
static const char n64MenuItem4[] PROGMEM = "Flash Gameshark";
static const char n64MenuItem5[] PROGMEM = "Flash Xplorer 64";
static const char* const menuOptionsN64[] PROGMEM = { n64MenuItem1, n64MenuItem2, n64MenuItem3, n64MenuItem4, n64MenuItem5, FSTRING_RESET };
// N64 controller menu items
static const char N64ContMenuItem1[] PROGMEM = "Test Controller";
static const char N64ContMenuItem2[] PROGMEM = "Read ControllerPak";
static const char N64ContMenuItem3[] PROGMEM = "Write ControllerPak";
static const char* const menuOptionsN64Controller[] PROGMEM = { N64ContMenuItem1, N64ContMenuItem2, N64ContMenuItem3, FSTRING_RESET };
// N64 cart menu items
static const char N64CartMenuItem4[] PROGMEM = "Force Savetype";
static const char* const menuOptionsN64Cart[] PROGMEM = { FSTRING_READ_ROM, FSTRING_READ_SAVE, FSTRING_WRITE_SAVE, N64CartMenuItem4, FSTRING_RESET };
// Rom menu
static const char N64RomItem1[] PROGMEM = "4 MB";
static const char N64RomItem2[] PROGMEM = "8 MB";
static const char N64RomItem3[] PROGMEM = "12 MB";
static const char N64RomItem4[] PROGMEM = "16 MB";
static const char N64RomItem5[] PROGMEM = "32 MB";
static const char N64RomItem6[] PROGMEM = "64 MB";
static const char N64RomItem7[] PROGMEM = "128 MB";
static const char* const romOptionsN64[] PROGMEM = { N64RomItem1, N64RomItem2, N64RomItem3, N64RomItem4, N64RomItem5, N64RomItem6, N64RomItem7 };
// Save menu
static const char N64SaveItem1[] PROGMEM = "None";
static const char N64SaveItem2[] PROGMEM = "4K EEPROM";
static const char N64SaveItem3[] PROGMEM = "16K EEPROM";
static const char N64SaveItem4[] PROGMEM = "SRAM";
static const char N64SaveItem5[] PROGMEM = "FLASH";
static const char* const saveOptionsN64[] PROGMEM = { N64SaveItem1, N64SaveItem2, N64SaveItem3, N64SaveItem4, N64SaveItem5 };
#if defined(ENABLE_FLASH)
// Repro write buffer menu
static const char N64BufferItem1[] PROGMEM = "No buffer";
static const char N64BufferItem2[] PROGMEM = "32 Byte";
static const char N64BufferItem3[] PROGMEM = "64 Byte";
static const char N64BufferItem4[] PROGMEM = "128 Byte";
static const char* const bufferOptionsN64[] PROGMEM = { N64BufferItem1, N64BufferItem2, N64BufferItem3, N64BufferItem4 };
// Repro sector size menu
static const char N64SectorItem1[] PROGMEM = "8 KB";
static const char N64SectorItem2[] PROGMEM = "32 KB";
static const char N64SectorItem3[] PROGMEM = "64 KB";
static const char N64SectorItem4[] PROGMEM = "128 KB";
static const char* const sectorOptionsN64[] PROGMEM = { N64SectorItem1, N64SectorItem2, N64SectorItem3, N64SectorItem4 };
#endif
// N64 start menu
void n64Menu() {
// create menu with title and 6 options to choose from
unsigned char n64Dev;
// Copy menuOptions out of progmem
convertPgm(menuOptionsN64, 6);
n64Dev = question_box(F("Select N64 device"), menuOptions, 6, 0);
// wait for user choice to come back from the question box menu
switch (n64Dev) {
case 0:
display_Clear();
display_Update();
setup_N64_Cart();
printCartInfo_N64();
mode = CORE_N64_CART;
break;
case 1:
display_Clear();
display_Update();
setup_N64_Controller();
mode = CORE_N64_CONTROLLER;
break;
#if defined(ENABLE_FLASH)
case 2:
display_Clear();
display_Update();
setup_N64_Cart();
flashRepro_N64();
printCartInfo_N64();
mode = CORE_N64_CART;
break;
#endif
case 3:
display_Clear();
display_Update();
setup_N64_Cart();
flashGameshark_N64();
printCartInfo_N64();
mode = CORE_N64_CART;
break;
case 4:
display_Clear();
display_Update();
setup_N64_Cart();
flashXplorer_N64();
mode = CORE_N64_CART;
print_STR(press_button_STR, 1);
display_Update();
wait();
resetArduino();
break;
case 5:
resetArduino();
break;
default:
print_MissingModule(); // does not return
}
}
// N64 Controller Menu
void n64ControllerMenu() {
// create menu with title and 4 options to choose from
unsigned char mainMenu;
// Copy menuOptions out of progmem
convertPgm(menuOptionsN64Controller, 4);
mainMenu = question_box(F("N64 Controller"), menuOptions, 4, 0);
// wait for user choice to come back from the question box menu
switch (mainMenu) {
#if defined(ENABLE_CONTROLLERTEST)
case 0:
resetController();
display_Clear();
display_Update();
#if (defined(ENABLE_OLED) || defined(ENABLE_LCD))
controllerTest_Display();
#elif defined(ENABLE_SERIAL)
controllerTest_Serial();
#endif
quit = 1;
break;
#endif
case 1:
resetController();
checkController();
display_Clear();
display_Update();
readMPK();
verifyCRC();
validateMPK();
println_Msg(FS(FSTRING_EMPTY));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
break;
case 2:
resetController();
checkController();
display_Clear();
display_Update();
// Change to root
filePath[0] = '\0';
sd.chdir("/");
// Launch file browser
fileBrowser(F("Select mpk file"));
display_Clear();
display_Update();
writeMPK();
delay(500);
verifyMPK();
println_Msg(FS(FSTRING_EMPTY));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
break;
case 3:
resetArduino();
break;
default:
print_MissingModule(); // does not return
}
}
// N64 Cartridge Menu
void n64CartMenu() {
// create menu with title and 4 options to choose from
unsigned char mainMenu;
// Copy menuOptions out of progmem
convertPgm(menuOptionsN64Cart, 5);
mainMenu = question_box(F("N64 Cart Reader"), menuOptions, 5, 0);
// wait for user choice to come back from the question box menu
switch (mainMenu) {
case 0:
display_Clear();
sd.chdir("/");
#ifndef OPTION_N64_FASTCRC
// Dumping ROM slow
readRom_N64();
sd.chdir("/");
compareCRC("n64.txt", 0, 1, 0);
#else
// Dumping ROM fast
compareCRC("n64.txt", readRom_N64(), 1, 0);
#endif
#ifdef ENABLE_GLOBAL_LOG
save_log();
#endif
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
break;
case 1:
sd.chdir("/");
display_Clear();
if (saveType == 1) {
println_Msg(F("Reading SRAM..."));
display_Update();
readSram(32768, 1);
} else if (saveType == 2) {
println_Msg(F("Reading Sram 768..."));
display_Update();
readSram(98304, 1);
} else if (saveType == 4) {
getFramType();
println_Msg(F("Reading FLASH..."));
display_Update();
readFram(flashramType);
} else if ((saveType == 5) || (saveType == 6)) {
println_Msg(F("Reading EEPROM..."));
display_Update();
resetEeprom_N64();
readEeprom_N64();
} else {
print_Error(F("Savetype Error"));
}
println_Msg(FS(FSTRING_EMPTY));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
break;
case 2:
filePath[0] = '\0';
sd.chdir("/");
if (saveType == 1) {
// Launch file browser
fileBrowser(F("Select sra file"));
display_Clear();
writeSram(32768);
writeErrors = verifySram(32768, 1);
if (writeErrors == 0) {
println_Msg(F("SRAM verified OK"));
display_Update();
} else {
print_STR(error_STR, 0);
print_Msg(writeErrors);
print_STR(_bytes_STR, 1);
print_Error(did_not_verify_STR);
}
} else if (saveType == 2) {
// Launch file browser
fileBrowser(F("Select Sram 768 file"));
display_Clear();
writeSram(98304);
writeErrors = verifySram(98304, 1);
if (writeErrors == 0) {
println_Msg(F("Sram verified OK"));
display_Update();
} else {
print_STR(error_STR, 0);
print_Msg(writeErrors);
print_STR(_bytes_STR, 1);
print_Error(did_not_verify_STR);
}
} else if (saveType == 4) {
// Launch file browser
fileBrowser(F("Select fla file"));
display_Clear();
getFramType();
writeFram(flashramType);
print_STR(verifying_STR, 0);
display_Update();
writeErrors = verifyFram(flashramType);
if (writeErrors == 0) {
println_Msg(FS(FSTRING_OK));
display_Update();
} else {
println_Msg("");
print_STR(error_STR, 0);
print_Msg(writeErrors);
print_STR(_bytes_STR, 1);
print_Error(did_not_verify_STR);
}
} else if ((saveType == 5) || (saveType == 6)) {
// Launch file browser
fileBrowser(F("Select eep file"));
display_Clear();
resetEeprom_N64();
writeEeprom_N64();
resetEeprom_N64();
writeErrors = verifyEeprom_N64();
if (writeErrors == 0) {
println_Msg(F("EEPROM verified OK"));
display_Update();
} else {
print_STR(error_STR, 0);
print_Msg(writeErrors);
print_STR(_bytes_STR, 1);
print_Error(did_not_verify_STR);
}
} else {
display_Clear();
print_Error(F("Save Type Error"));
}
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
break;
case 3:
// create submenu with title and 6 options to choose from
unsigned char N64SaveMenu;
// Copy menuOptions out of progmem
convertPgm(saveOptionsN64, 5);
N64SaveMenu = question_box(F("Select save type"), menuOptions, 5, 0);
// wait for user choice to come back from the question box menu
switch (N64SaveMenu) {
case 0:
// None
saveType = 0;
break;
case 1:
// 4K EEPROM
saveType = 5;
eepPages = 64;
break;
case 2:
// 16K EEPROM
saveType = 6;
eepPages = 256;
break;
case 3:
// SRAM
saveType = 1;
break;
case 4:
// FLASHRAM
saveType = 4;
break;
}
break;
case 4:
resetArduino();
break;
}
}
/******************************************
Setup
*****************************************/
void setup_N64_Controller() {
// Request 3.3V
setVoltage(VOLTS_SET_3V3);
// Output a low signal
PORTH &= ~(1 << 4);
// Set Controller Data Pin(PH4) to Input
DDRH &= ~(1 << 4);
}
void setup_N64_Cart() {
// Request 3.3V
setVoltage(VOLTS_SET_3V3);
// Set Address Pins to Output and set them low
//A0-A7
DDRF = 0xFF;
PORTF = 0x00;
//A8-A15
DDRK = 0xFF;
PORTK = 0x00;
// Set Control Pins to Output RESET(PH0) WR(PH5) RD(PH6) aleL(PC0) aleH(PC1)
DDRH |= (1 << 0) | (1 << 5) | (1 << 6);
DDRC |= (1 << 0) | (1 << 1);
// Pull RESET(PH0) low until we are ready
PORTH &= ~(1 << 0);
// Output a high signal on WR(PH5) RD(PH6), pins are active low therefore everything is disabled now
PORTH |= (1 << 5) | (1 << 6);
// Pull aleL(PC0) low and aleH(PC1) high
PORTC &= ~(1 << 0);
PORTC |= (1 << 1);
#ifdef ENABLE_CLOCKGEN
// Adafruit Clock Generator
initializeClockOffset();
if (!i2c_found) {
display_Clear();
print_FatalError(F("Clock Generator not found"));
}
// Set Eeprom clock to 2Mhz
clockgen.set_freq(200000000ULL, SI5351_CLK1);
// Start outputting Eeprom clock
clockgen.output_enable(SI5351_CLK1, 1); // Eeprom clock
#else
// Set Eeprom Clock Pin(PH1) to Output
DDRH |= (1 << 1);
// Output a high signal
PORTH |= (1 << 1);
#endif
// Set Eeprom Data Pin(PH4) to Input
DDRH &= ~(1 << 4);
// Activate Internal Pullup Resistors
//PORTH |= (1 << 4);
// Set sram base address
sramBase = 0x08000000;
#ifdef ENABLE_CLOCKGEN
// Wait for clock generator
clockgen.update_status();
#endif
// Wait until all is stable
delay(300);
// Pull RESET(PH0) high to start eeprom
PORTH |= (1 << 0);
}
/******************************************
Low level functions
*****************************************/
// Switch Cartridge address/data pins to write
void adOut_N64() {
//A0-A7
DDRF = 0xFF;
PORTF = 0x00;
//A8-A15
DDRK = 0xFF;
PORTK = 0x00;
}
// Switch Cartridge address/data pins to read
void adIn_N64() {
//A0-A7
DDRF = 0x00;
//A8-A15
DDRK = 0x00;
//Enable internal pull-up resistors
//PORTF = 0xFF;
//PORTK = 0xFF;
}
// Set Cartridge address
void setAddress_N64(unsigned long myAddress) {
// Set address pins to output
adOut_N64();
// Split address into two words
word myAdrLowOut = myAddress & 0xFFFF;
word myAdrHighOut = myAddress >> 16;
// Switch WR(PH5) RD(PH6) ale_L(PC0) ale_H(PC1) to high (since the pins are active low)
PORTH |= (1 << 5) | (1 << 6);
PORTC |= (1 << 1);
__asm__("nop\n\t"); // needed for repro
PORTC |= (1 << 0);
// Output high part to address pins
PORTF = myAdrHighOut & 0xFF;
PORTK = (myAdrHighOut >> 8) & 0xFF;
// Leave ale_H high for additional 62.5ns
__asm__("nop\n\t");
// Pull ale_H(PC1) low
PORTC &= ~(1 << 1);
// Output low part to address pins
PORTF = myAdrLowOut & 0xFF;
PORTK = (myAdrLowOut >> 8) & 0xFF;
// Leave ale_L high for ~125ns
__asm__("nop\n\t"
"nop\n\t");
// Pull ale_L(PC0) low
PORTC &= ~(1 << 0);
// Set data pins to input
adIn_N64();
}
// Read one word out of the cartridge
word readWord_N64() {
// Pull read(PH6) low
PORTH &= ~(1 << 6);
// Wait ~310ns
__asm__("nop\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t");
// Join bytes from PINF and PINK into a word
word tempWord = ((PINK & 0xFF) << 8) | (PINF & 0xFF);
// Pull read(PH6) high
PORTH |= (1 << 6);
return tempWord;
}
// Write one word to data pins of the cartridge
void writeWord_N64(word myWord) {
// Set address pins to output
adOut_N64();
// Output word to AD0-AD15
PORTF = myWord & 0xFF;
PORTK = (myWord >> 8) & 0xFF;
// Wait ~62.5ns
__asm__("nop\n\t");
// Pull write(PH5) low
PORTH &= ~(1 << 5);
// Wait ~310ns
__asm__("nop\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t");
// Pull write(PH5) high
PORTH |= (1 << 5);
// Wait ~125ns
__asm__("nop\n\t"
"nop\n\t");
// Set data pins to input
adIn_N64();
}
/******************************************
N64 Controller CRC Functions
*****************************************/
static word addrCRC(word address) {
const char n64_address_crc_table[] = { 0x15, 0x1F, 0x0B, 0x16, 0x19, 0x07, 0x0E, 0x1C, 0x0D, 0x1A, 0x01 };
const char* cur_xor = n64_address_crc_table;
byte crc = 0;
for (word mask = 0x0020; mask; mask <<= 1, cur_xor++) {
if (address & mask) {
crc ^= *cur_xor;
}
}
return (address & 0xFFE0) | crc;
}
static uint8_t dataCRC(uint8_t* data) {
uint8_t ret = 0;
for (uint8_t i = 0; i <= 32; i++) {
for (uint8_t mask = 0x80; mask; mask >>= 1) {
uint8_t tmp = ret & 0x80 ? 0x85 : 0;
ret <<= 1;
if (i < 32) {
if (data[i] & mask) {
ret |= 0x1;
}
}
ret ^= tmp;
}
}
return ret;
}
// Macro producing a delay loop waiting an number of cycles multiple of 3, with
// a range of 3 to 768 cycles (187.5ns to 48us). It takes 6 bytes to do so
// (3 instructions) making it the same size as the equivalent 3-cycles NOP
// delay. For shorter delays or non-multiple-of-3-cycle delays, add your own
// NOPs.
#define N64_DELAY_LOOP(cycle_count) \
do { \
byte i; \
__asm__ __volatile__("\n" \
"\tldi %[i], %[loop_count]\n" \
".delay_loop_%=:\n" \
"\tdec %[i]\n" \
"\tbrne .delay_loop_%=\n" \
: [i] "=r"(i) \
: [loop_count] "i"(cycle_count / 3) \
: "cc"); \
} while (0)
/******************************************
N64 Controller Protocol Functions
*****************************************/
void sendJoyBus(const byte* buffer, char length) {
// Implemented in assembly as there is very little wiggle room, timing-wise.
// Overall structure:
// outer_loop:
// mask = 0x80
// cur_byte = *(buffer++)
// inner_loop:
// falling edge
// if (cur_byte & mask) {
// wait 1us starting at the falling edge
// rising edge
// wait 2us starting at the rising edge
// } else {
// wait 3us starting at the falling edge
// rising edge
// }
// inner_common_codepath:
// mask >>= 1
// if (mask == 0)
// goto outer_loop_trailer
// wait +1us from the rising edge
// goto inner_loop
// outer_loop_trailer:
// length -= 1
// if (length == 0)
// goto stop_bit
// wait +1us from the rising edge
// goto outer_loop
// stop_bit:
// wait +1us from the rising edge
// falling edge
// wait 1us from the falling edge
// rising edge
byte mask, cur_byte, scratch;
// Note on DDRH: retrieve the current DDRH value, and pre-compute the values
// to write in order to drive the line high or low. This saves 3 cycles per
// transition: sts (2 cycles) instead of lds, or/and, sts (2 + 1 + 2 cycles).
// This means that no other code may run in parallel, but this function anyway
// requires interrupts to be disabled in order to work in the expected amount
// of time.
const byte line_low = DDRH | 0x10;
const byte line_high = line_low & 0xef;
__asm__ __volatile__("\n"
".outer_loop_%=:\n"
// mask = 0x80
"\tldi %[mask], 0x80\n" // 1
// load byte to send from memory
"\tld %[cur_byte], Z+\n" // 2
".inner_loop_%=:\n"
// Falling edge
"\tsts %[out_byte], %[line_low]\n" // 2
// Test cur_byte & mask, without clobbering either
"\tmov %[scratch], %[cur_byte]\n" // 1
"\tand %[scratch], %[mask]\n" // 1
"\tbreq .bit_is_0_%=\n" // bit is 1: 1, bit is 0: 2
// bit is a 1
// Stay low for 1us (16 cycles).
// Time before: 3 cycles (mov, and, breq-false).
// Time after: sts (2 cycles).
// So 11 to go, so 3 3-cycles iterations and 2 nop.
"\tldi %[scratch], 3\n" // 1
".delay_1_low_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_1_low_%=\n" // exit: 1, loop: 2
"\tnop\n" // 1
"\tnop\n" // 1
// Rising edge
"\tsts %[out_byte], %[line_high]\n" // 2
// Wait for 2us (32 cycles) to sync with the bot_is_0 codepath.
// Time before: 0 cycles.
// Time after: 2 cycles (rjmp).
// So 30 to go, so 10 3-cycles iterations and 0 nop.
"\tldi %[scratch], 10\n" // 1
".delay_1_high_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_1_high_%=\n" // exit: 1, loop: 2
"\trjmp .inner_common_path_%=\n" // 2
".bit_is_0_%=:\n"
// bit is a 0
// Stay high for 3us (48 cycles).
// Time before: 4 cycles (mov, and, breq-true).
// Time after: 2 cycles (sts).
// So 42 to go, so 14 3-cycles iterations, and 0 nop.
"\tldi %[scratch], 14\n" // 1
".delay_0_low_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_0_low_%=\n" // exit: 1, loop: 2
// Rising edge
"\tsts %[out_byte], %[line_high]\n" // 2
// codepath common to both possible values
".inner_common_path_%=:\n"
"\tnop\n" // 1
"\tlsr %[mask]\n" // 1
"\tbreq .outer_loop_trailer_%=\n" // mask!=0: 1, mask==0: 2
// Stay high for 1us (16 cycles).
// Time before: 3 cycles (nop, lsr, breq-false).
// Time after: 4 cycles (rjmp, sts)
// So 9 to go, so 3 3-cycles iterations and 0 nop.
"\tldi %[scratch], 3\n" // 1
".delay_common_high_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_common_high_%=\n" // exit: 1, loop: 2
"\trjmp .inner_loop_%=\n" // 2
".outer_loop_trailer_%=:\n"
"\tdec %[length]\n" // 1
"\tbreq .stop_bit_%=\n" // length!=0: 1, length==0: 2
// Stay high for 1us (16 cycles).
// Time before: 6 cycles (lsr, nop, breq-true, dec, breq-false).
// Time after: 7 cycles (rjmp, ldi, ld, sts).
// So 3 to go, so 3 nop (for simplicity).
"\tnop\n" // 1
"\tnop\n" // 1
"\tnop\n" // 1
"\trjmp .outer_loop_%=\n" // 2
// Done sending data, send a stop bit.
".stop_bit_%=:\n"
// Stay high for 1us (16 cycles).
// Time before: 7 cycles (lsr, nop, breq-true, dec, breq-true).
// Time after: 2 cycles (sts).
// So 7 to go, so 2 3-cycles iterations and 1 nop.
"\tldi %[scratch], 2\n" // 1
".delay_stop_high_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_stop_high_%=\n" // exit: 1, loop: 2
"\tnop\n"
"\tsts %[out_byte], %[line_low]\n" // 2
// Stay low for 1us (16 cycles).
// Time before: 0 cycles.
// Time after: 2 cycles (sts).
// So 14 to go, so 4 3-cycles iterations and 2 nop.
"\tldi %[scratch], 5\n" // 1
".delay_stop_low_%=:\n"
"\tdec %[scratch]\n" // 1
"\tbrne .delay_stop_low_%=\n" // exit: 1, loop: 2
"\tnop\n"
"\tnop\n"
"\tsts %[out_byte], %[line_high]\n" // 2
// Notes on arguments:
// - mask and scratch are used wth "ldi", which can only work on registers
// 16 to 31, so tag these with "a" rather than the generic "r"
// - mark all output-only arguments as early-clobber ("&"), as input
// registers are used throughout all iterations and both sets must be
// strictly distinct
// - tag buffer with "z", to use the "ld r?, Z+" instruction (load from
// 16bits RAM address and postincrement, in 2 cycles).
// XXX: any pointer register pair would do, but mapping to Z explicitly
// because I cannot find a way to get one of "X", "Y" or "Z" to appear
// when expanding "%[buffer]", causing the assembler to reject the
// instruction. Pick Z as it is the only call-used such register,
// avoiding the need to preserve any value a caller may have set it to.
: [buffer] "+z"(buffer),
[length] "+r"(length),
[cur_byte] "=&r"(cur_byte),
[mask] "=&a"(mask),
[scratch] "=&a"(scratch)
: [line_low] "r"(line_low),
[line_high] "r"(line_high),
[out_byte] "i"(&DDRH)
: "cc", "memory");
}
word recvJoyBus(byte* output, byte byte_count) {
// listen for expected byte_count bytes of data back from the controller
// return the number of bytes not (fully) received if the delay for a signal
// edge takes too long.
// Implemented in assembly as there is very little wiggle room, timing-wise.
// Overall structure:
// mask = 0x80
// cur_byte = 0
// read_loop:
// wait for falling edge
// wait for a bit more than 1us
// if input:
// cur_byte |= mask
// mask >>= 1
// if (mask == 0)
// if (--byte_count == 0)
// goto read_end
// append cur_byte to output
// mask = 0x80
// cur_byte = 0
// wait for data high
// goto read_loop
// read_end:
// return byte_count
byte mask, cur_byte, timeout, scratch;
__asm__ __volatile__("\n"
"\tldi %[mask], 0x80\n"
"\tclr %[cur_byte]\n"
".read_loop_%=:\n"
// Wait for input to be low. Time out if it takes more than ~27us (~7 bits
// worth of time) for it to go low.
// Takes 5 cycles to exit on input-low iteration (lds, sbrs-false, rjmp).
// Takes 7 cycles to loop on input-high iteration (lds, sbrs-true, dec,
// brne-true).
"\tldi %[timeout], 0x3f\n" // 1
".read_wait_falling_edge_%=:\n"
"\tlds %[scratch], %[in_byte]\n" // 2
"\tsbrs %[scratch], %[in_bit]\n" // low: 1, high: 2
"\trjmp .read_input_low_%=\n" // 2
"\tdec %[timeout]\n" // 1
"\tbrne .read_wait_falling_edge_%=\n" // timeout==0: 1, timeout!=0: 2
"\trjmp .read_end_%=\n" // 2
".read_input_low_%=:\n"
// Wait for 1500 us (24 cycles) before reading input.
// As it takes from 5 to 7 cycles for the prevous loop to exit,
// this means this loop exits from 1812.5us to 1937.5us after the falling
// edge, so at least 812.5us after a 1-bit rising edge, and at least
// 1062.5us before a 0-bit rising edge.
// This also leaves us with up to 2062.5us (33 cycles) to update cur_byte,
// possibly moving on to the next byte, waiting for a high input, and
// waiting for the next falling edge.
// Time taken until waiting for input high for non-last byte:
// - shift to current byte:
// - 1: 4 cycles (lds, sbrc-false, or)
// - 0: 4 cycles (lds, sbrc-true)
// - byte done: 8 cycles (lsr, brne-false, st, dec, brne-false, ldi, clr)
// - byte not done: 3 cycles (lsr, brne-true)
// Total: 7 to 12 cycles, so there are at least 21 cycles left until the
// next bit.
"\tldi %[timeout], 8\n" // 1
".read_wait_low_%=:\n"
"\tdec %[timeout]\n" // 1
"\tbrne .read_wait_low_%=\n" // timeout=0: 1, timeout!=0: 2
// Sample input
"\tlds %[scratch], %[in_byte]\n" // 2
// Add to cur_byte
"\tsbrc %[scratch], %[in_bit]\n" // high: 1, low: 2
"\tor %[cur_byte], %[mask]\n" // 1
// Shift mask
"\tlsr %[mask]\n"
"\tbrne .read_wait_input_high_init_%=\n" // mask==0: 1, mask!=0: 2
// A wole byte was read, store in output
"\tst Z+, %[cur_byte]\n" // 2
// Decrement byte count
"\tdec %[byte_count]\n" // 1
// Are we done reading ?
"\tbreq .read_end_%=\n" // byte_count!=0: 1, byte_count==0: 2
// No, prepare for reading another
"\tldi %[mask], 0x80\n"
"\tclr %[cur_byte]\n"
// Wait for rising edge
".read_wait_input_high_init_%=:"
"\tldi %[timeout], 0x3f\n" // 1
".read_wait_input_high_%=:\n"
"\tlds %[scratch], %[in_byte]\n" // 2
"\tsbrc %[scratch], %[in_bit]\n" // high: 1, low: 2
"\trjmp .read_loop_%=\n" // 2
"\tdec %[timeout]\n" // 1
"\tbrne .read_wait_input_high_%=\n" // timeout==0: 1, timeout!=0: 2
"\trjmp .read_end_%=\n" // 2
".read_end_%=:\n"
: [output] "+z"(output),
[byte_count] "+r"(byte_count),
[mask] "=&a"(mask),
[cur_byte] "=&r"(cur_byte),
[timeout] "=&a"(timeout),
[scratch] "=&a"(scratch)
: [in_byte] "i"(&PINH),
[in_bit] "i"(4)
: "cc", "memory");
return byte_count;
}
/******************************************
N64 Controller Functions
*****************************************/
void get_button() {
// Command to send to the gamecube
// The last bit is rumble, flip it to rumble
const byte command[] = { 0x01 };
byte response[4];
// don't want interrupts getting in the way
noInterrupts();
sendJoyBus(command, sizeof(command));
recvJoyBus(response, sizeof(response));
// end of time sensitive code
interrupts();
// These are 8 bit values centered at 0x80 (128)
N64_status.stick_x = response[2];
N64_status.stick_y = response[3];
// Buttons (A,B,Z,S,DU,DD,DL,DR,0,0,L,R,CU,CD,CL,CR)
if (response[0] & 0x80)
button = F("A");
else if (response[0] & 0x40)
button = F("B");
else if (response[0] & 0x20)
button = F("Z");
else if (response[0] & 0x10)
button = F("START");
else if (response[0] & 0x08)
button = F("D-Up");
else if (response[0] & 0x04)
button = F("D-Down");
else if (response[0] & 0x02)
button = F("D-Left");
else if (response[0] & 0x01)
button = F("D-Right");
//else if (response[1] & 0x80)
//else if (response[1] & 0x40)
else if (response[1] & 0x20)
button = F("L");
else if (response[1] & 0x10)
button = F("R");
else if (response[1] & 0x08)
button = F("C-Up");
else if (response[1] & 0x04)
button = F("C-Down");
else if (response[1] & 0x02)
button = F("C-Left");
else if (response[1] & 0x01)
button = F("C-Right");
else {
lastbutton = button;
button = F("Press a button");
}
}
/******************************************
N64 Controller Test
*****************************************/
#if defined(ENABLE_CONTROLLERTEST)
#ifdef ENABLE_SERIAL
void controllerTest_Serial() {
while (quit) {
// Get Button and analog stick
get_button();
// Print Button
String buttonc = String("Button: " + String(button) + " ");
Serial.print(buttonc);
// Print Stick X Value
String stickx = String("X: " + String(N64_status.stick_x, DEC) + " ");
Serial.print(stickx);
// Print Stick Y Value
String sticky = String(" Y: " + String(N64_status.stick_y, DEC) + " ");
Serial.println(sticky);
if (button == "Press a button" && lastbutton == "Z") {
// Quit
Serial.println("");
quit = 0;
}
}
}
#endif
#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
#define CENTER 64
// on which screens do we start
int startscreen = 1;
int test = 1;
void printSTR(String st, int x, int y) {
char buf[st.length() + 1];
if (x == CENTER) {
x = 64 - (((st.length() - 5) / 2) * 4);
}
st.toCharArray(buf, st.length() + 1);
display.drawStr(x, y, buf);
}
void nextscreen() {
if (button == "Press a button" && lastbutton == "START") {
// reset button
lastbutton = "N/A";
display.clearDisplay();
if (startscreen != 4)
startscreen = startscreen + 1;
else {
startscreen = 1;
test = 1;
}
} else if (button == "Press a button" && lastbutton == "Z" && startscreen == 4) {
// Quit
quit = 0;
}
}
void controllerTest_Display() {
boolean cmode = 1;
//name of the current displayed result
String anastick = "";
// Graph
int xax = 24; // midpoint x
int yax = 24; // midpoint y
// variables to display test data of different sticks
int upx = 0;
int upy = 0;
int uprightx = 0;
int uprighty = 0;
int rightx = 0;
int righty = 0;
int downrightx = 0;
int downrighty = 0;
int downx = 0;
int downy = 0;
int downleftx = 0;
int downlefty = 0;
int leftx = 0;
int lefty = 0;
int upleftx = 0;
int uplefty = 0;
// variables to save test data
int bupx = 0;
int bupy = 0;
int buprightx = 0;
int buprighty = 0;
int brightx = 0;
int brighty = 0;
int bdownrightx = 0;
int bdownrighty = 0;
int bdownx = 0;
int bdowny = 0;
int bdownleftx = 0;
int bdownlefty = 0;
int bleftx = 0;
int blefty = 0;
int bupleftx = 0;
int buplefty = 0;
int results = 0;
int prevStickX = 0;
String stickx;
String sticky;
String stickx_old;
String sticky_old;
String button_old;
while (quit) {
// Get Button and analog stick
get_button();
switch (startscreen) {
case 1:
{
display.drawStr(32, 8, "Controller Test");
display.drawLine(0, 10, 128, 10);
// Delete old button value
if (button_old != button) {
display.setDrawColor(0);
for (byte y = 13; y < 22; y++) {
display.drawLine(0, y, 128, y);
}
display.setDrawColor(1);
}
// Print button
printSTR(" " + button + " ", CENTER, 20);
// Save value
button_old = button;
// Update stick values
stickx = String("X: " + String(N64_status.stick_x, DEC) + " ");
sticky = String("Y: " + String(N64_status.stick_y, DEC) + " ");
// Delete old stick values
if ((stickx_old != stickx) || (sticky_old != sticky)) {
display.setDrawColor(0);
for (byte y = 31; y < 38; y++) {
display.drawLine(0, y, 128, y);
}
display.setDrawColor(1);
}
// Print stick values
printSTR(stickx, 36, 38);
printSTR(sticky, 74, 38);
// Save values
stickx_old = stickx;
sticky_old = sticky;
printSTR("(Continue with START)", 16, 55);
//Update LCD
display.updateDisplay();
// go to next screen
nextscreen();
break;
}
case 2:
{
display.drawStr(36, 8, "Range Test");
display.drawLine(0, 9, 128, 9);
if (cmode == 0) {
// Print Stick X Value
String stickx = String("X:" + String(N64_status.stick_x, DEC) + " ");
printSTR(stickx, 22 + 54, 26);
// Print Stick Y Value
String sticky = String("Y:" + String(N64_status.stick_y, DEC) + " ");
printSTR(sticky, 22 + 54, 36);
}
// Draw Axis
display.drawPixel(10 + xax, 12 + yax);
display.drawPixel(10 + xax, 12 + yax - 80 / 4);
display.drawPixel(10 + xax, 12 + yax + 80 / 4);
display.drawPixel(10 + xax + 80 / 4, 12 + yax);
display.drawPixel(10 + xax - 80 / 4, 12 + yax);
// Draw corners
display.drawPixel(10 + xax - 68 / 4, 12 + yax - 68 / 4);
display.drawPixel(10 + xax + 68 / 4, 12 + yax + 68 / 4);
display.drawPixel(10 + xax + 68 / 4, 12 + yax - 68 / 4);
display.drawPixel(10 + xax - 68 / 4, 12 + yax + 68 / 4);
//Draw Analog Stick
if (cmode == 1) {
display.drawPixel(10 + xax + N64_status.stick_x / 4, 12 + yax - N64_status.stick_y / 4);
//Update LCD
display.updateDisplay();
} else {
display.drawCircle(10 + xax + N64_status.stick_x / 4, 12 + yax - N64_status.stick_y / 4, 2);
//Update LCD
display.updateDisplay();
display_Clear_Slow();
}
// switch mode
if (button == "Press a button" && lastbutton == "Z") {
if (cmode == 0) {
cmode = 1;
display.clearDisplay();
} else {
cmode = 0;
display.clearDisplay();
}
}
// go to next screen
nextscreen();
break;
}
case 3:
{
display.setDrawColor(0);
display.drawPixel(22 + prevStickX, 40);
display.setDrawColor(1);
printSTR("Skipping Test", 34, 8);
display.drawLine(0, 9, 128, 9);
display.drawFrame(22 + 0, 15, 22 + 59, 21);
if (N64_status.stick_x > 0) {
display.drawLine(22 + N64_status.stick_x, 15, 22 + N64_status.stick_x, 35);
display.drawPixel(22 + N64_status.stick_x, 40);
prevStickX = N64_status.stick_x;
}
printSTR("Try to fill the box by", 22, 45);
printSTR("slowly moving right", 22, 55);
//Update LCD
display.updateDisplay();
if (button == "Press a button" && lastbutton == "Z") {
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
// go to next screen
nextscreen();
break;
}
case 4:
{
switch (test) {
case 0: // Display results
{
switch (results) {
case 0:
{
anastick = "Your Stick";
upx = bupx;
upy = bupy;
uprightx = buprightx;
uprighty = buprighty;
rightx = brightx;
righty = brighty;
downrightx = bdownrightx;
downrighty = bdownrighty;
downx = bdownx;
downy = bdowny;
downleftx = bdownleftx;
downlefty = bdownlefty;
leftx = bleftx;
lefty = blefty;
upleftx = bupleftx;
uplefty = buplefty;
if (button == "Press a button" && lastbutton == "A") {
// reset button
lastbutton = "N/A";
results = 1;
display.clearDisplay();
break;
}
printSTR(anastick, 22 + 50, 15);
display.drawStr(22 + 50, 25, "U:");
printSTR(String(upy), 100, 25);
display.drawStr(22 + 50, 35, "D:");
printSTR(String(downy), 100, 35);
display.drawStr(22 + 50, 45, "L:");
printSTR(String(leftx), 100, 45);
display.drawStr(22 + 50, 55, "R:");
printSTR(String(rightx), 100, 55);
display.drawLine(xax + upx / 4, yax - upy / 4, xax + uprightx / 4, yax - uprighty / 4);
display.drawLine(xax + uprightx / 4, yax - uprighty / 4, xax + rightx / 4, yax - righty / 4);
display.drawLine(xax + rightx / 4, yax - righty / 4, xax + downrightx / 4, yax - downrighty / 4);
display.drawLine(xax + downrightx / 4, yax - downrighty / 4, xax + downx / 4, yax - downy / 4);
display.drawLine(xax + downx / 4, yax - downy / 4, xax + downleftx / 4, yax - downlefty / 4);
display.drawLine(xax + downleftx / 4, yax - downlefty / 4, xax + leftx / 4, yax - lefty / 4);
display.drawLine(xax + leftx / 4, yax - lefty / 4, xax + upleftx / 4, yax - uplefty / 4);
display.drawLine(xax + upleftx / 4, yax - uplefty / 4, xax + upx / 4, yax - upy / 4);
display.drawPixel(xax, yax);
//Update LCD
display.updateDisplay();
break;
}
case 1:
{
anastick = "Original";
upx = 1;
upy = 84;
uprightx = 67;
uprighty = 68;
rightx = 83;
righty = -2;
downrightx = 67;
downrighty = -69;
downx = 3;
downy = -85;
downleftx = -69;
downlefty = -70;
leftx = -85;
lefty = 0;
upleftx = -68;
uplefty = 68;
if (button == "Press a button" && lastbutton == "A") {
// reset button
lastbutton = "N/A";
results = 0;
display.clearDisplay();
break;
}
printSTR(anastick, 22 + 50, 15);
display.drawStr(22 + 50, 25, "U:");
printSTR(String(upy), 100, 25);
display.drawStr(22 + 50, 35, "D:");
printSTR(String(downy), 100, 35);
display.drawStr(22 + 50, 45, "L:");
printSTR(String(leftx), 100, 45);
display.drawStr(22 + 50, 55, "R:");
printSTR(String(rightx), 100, 55);
display.drawLine(xax + upx / 4, yax - upy / 4, xax + uprightx / 4, yax - uprighty / 4);
display.drawLine(xax + uprightx / 4, yax - uprighty / 4, xax + rightx / 4, yax - righty / 4);
display.drawLine(xax + rightx / 4, yax - righty / 4, xax + downrightx / 4, yax - downrighty / 4);
display.drawLine(xax + downrightx / 4, yax - downrighty / 4, xax + downx / 4, yax - downy / 4);
display.drawLine(xax + downx / 4, yax - downy / 4, xax + downleftx / 4, yax - downlefty / 4);
display.drawLine(xax + downleftx / 4, yax - downlefty / 4, xax + leftx / 4, yax - lefty / 4);
display.drawLine(xax + leftx / 4, yax - lefty / 4, xax + upleftx / 4, yax - uplefty / 4);
display.drawLine(xax + upleftx / 4, yax - uplefty / 4, xax + upx / 4, yax - upy / 4);
display.drawPixel(xax, yax);
//Update LCD
display.updateDisplay();
break;
}
} //results
break;
} //display results
case 1: // +y Up
{
display.drawStr(34, 26, "Hold Stick Up");
display.drawStr(34, 34, "then press A");
//display.drawBitmap(110, 60, ana1);
if (button == "Press a button" && lastbutton == "A") {
bupx = N64_status.stick_x;
bupy = N64_status.stick_y;
// reset button
lastbutton = "N/A";
display.clearDisplay();
test = 2;
}
break;
}
case 2: // +y+x Up-Right
{
display.drawStr(42, 26, "Up-Right");
//display.drawBitmap(110, 60, ana2);
if (button == "Press a button" && lastbutton == "A") {
buprightx = N64_status.stick_x;
buprighty = N64_status.stick_y;
test = 3;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 3: // +x Right
{
display.drawStr(50, 26, "Right");
//display.drawBitmap(110, 60, ana3);
if (button == "Press a button" && lastbutton == "A") {
brightx = N64_status.stick_x;
brighty = N64_status.stick_y;
test = 4;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 4: // -y+x Down-Right
{
display.drawStr(38, 26, "Down-Right");
//display.drawBitmap(110, 60, ana4);
if (button == "Press a button" && lastbutton == "A") {
bdownrightx = N64_status.stick_x;
bdownrighty = N64_status.stick_y;
test = 5;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 5: // -y Down
{
display.drawStr(49, 26, "Down");
//display.drawBitmap(110, 60, ana5);
if (button == "Press a button" && lastbutton == "A") {
bdownx = N64_status.stick_x;
bdowny = N64_status.stick_y;
test = 6;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 6: // -y-x Down-Left
{
display.drawStr(39, 26, "Down-Left");
//display.drawBitmap(110, 60, ana6);
if (button == "Press a button" && lastbutton == "A") {
bdownleftx = N64_status.stick_x;
bdownlefty = N64_status.stick_y;
test = 7;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 7: // -x Left
{
display.drawStr(51, 26, "Left");
//display.drawBitmap(110, 60, ana7);
if (button == "Press a button" && lastbutton == "A") {
bleftx = N64_status.stick_x;
blefty = N64_status.stick_y;
test = 8;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
case 8: // +y+x Up-Left
{
display.drawStr(43, 26, "Up-Left");
//display.drawBitmap(110, 60, ana8);
if (button == "Press a button" && lastbutton == "A") {
bupleftx = N64_status.stick_x;
buplefty = N64_status.stick_y;
test = 0;
// reset button
lastbutton = "N/A";
display.clearDisplay();
}
break;
}
}
if (test != 0) {
display.drawStr(38, 8, "Benchmark");
display.drawLine(0, 9, 128, 9);
}
display.updateDisplay();
// go to next screen
nextscreen();
break;
}
}
}
}
#endif
#endif
/******************************************
N64 Controller Pak Functions
(connected via Controller)
*****************************************/
// Reset the controller
void resetController() {
const byte command[] = { 0xFF };
noInterrupts();
sendJoyBus(command, sizeof(command));
interrupts();
delay(100);
}
// read 3 bytes from controller
void checkController() {
byte response[8];
const byte command[] = { 0x00 };
display_Clear();
// Check if line is HIGH
if (!N64_QUERY)
print_FatalError(F("Data line LOW"));
// don't want interrupts getting in the way
noInterrupts();
sendJoyBus(command, sizeof(command));
recvJoyBus(response, sizeof(response));
// end of time sensitive code
interrupts();
if (response[0] != 0x05)
print_FatalError(F("Controller not found"));
if (response[2] != 0x01)
print_FatalError(F("Controller Pak not found"));
}
// read 32bytes from controller pak and calculate CRC
byte readBlock(byte* output, word myAddress) {
byte response_crc;
// Calculate the address CRC
word myAddressCRC = addrCRC(myAddress);
const byte command[] = { 0x02, (byte)(myAddressCRC >> 8), (byte)(myAddressCRC & 0xff) };
word error;
// don't want interrupts getting in the way
noInterrupts();
sendJoyBus(command, sizeof(command));
error = recvJoyBus(output, 32);
if (error == 0)
error = recvJoyBus(&response_crc, 1);
// end of time sensitive code
interrupts();
if (error) {
myFile.close();
println_Msg(F("Controller Pak was"));
println_Msg(F("not dumped due to a"));
print_FatalError(F("read timeout"));
}
// Compare with computed CRC
if (response_crc != dataCRC(output)) {
display_Clear();
// Close the file:
myFile.close();
println_Msg(F("Controller Pak was"));
println_Msg(F("not dumped due to a"));
print_FatalError(F("protocol CRC error"));
}
return response_crc;
}
// reads the MPK file to the sd card
void readMPK() {
// Change to root
sd.chdir("/");
// Make MPK directory
sd.mkdir("N64/MPK", true);
// Change to MPK directory
sd.chdir("N64/MPK");
// Get name, add extension and convert to char array for sd lib
EEPROM_readAnything(0, foldern);
sprintf(fileName, "%d", foldern);
strcat(fileName, ".mpk");
// write new folder number back to eeprom
foldern = foldern + 1;
EEPROM_writeAnything(0, foldern);
//open crc file on sd card
sprintf(filePath, "%d", foldern - 1);
strcat(filePath, ".crc");
FsFile crcFile;
if (!crcFile.open(filePath, O_RDWR | O_CREAT)) {
print_FatalError(open_file_STR);
}
//open mpk file on sd card
if (!myFile.open(fileName, O_RDWR | O_CREAT)) {
print_FatalError(open_file_STR);
}
print_Msg(F("Saving N64/MPK/"));
println_Msg(fileName);
display_Update();
// Dummy write because first write to file takes 1 second and messes up timing
blinkLED();
myFile.write(0xFF);
myFile.rewind();
blinkLED();
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(0x7FFF);
draw_progressbar(0, totalProgressBar);
// Controller paks, which all have 32kB of space, are mapped between 0x0000 – 0x7FFF
for (word currSdBuffer = 0x0000; currSdBuffer < 0x8000; currSdBuffer += 512) {
// Read 32 byte block into sdBuffer
for (word currBlock = 0; currBlock < sizeof(sdBuffer); currBlock += 32) {
// Read one block of the Controller Pak into array myBlock and write CRC of that block to crc file
crcFile.write(readBlock(&sdBuffer[currBlock], currSdBuffer + currBlock));
// Real N64 has about 627us pause between banks, add a bit extra delay
if (currBlock < 479)
delayMicroseconds(800);
}
// This will take 1300us
blinkLED();
myFile.write(sdBuffer, sizeof(sdBuffer));
// Blink led
blinkLED();
// Update progress bar
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
// Close the file:
myFile.close();
crcFile.close();
}
// verifies if read was successful
void verifyCRC() {
writeErrors = 0;
print_STR(verifying_STR, 1);
display_Update();
//open CRC file on sd card
FsFile crcFile;
if (!crcFile.open(filePath, O_READ)) {
print_FatalError(open_file_STR);
}
//open MPK file on sd card
if (!myFile.open(fileName, O_READ)) {
print_FatalError(open_file_STR);
}
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(0x7FFF);
draw_progressbar(0, totalProgressBar);
// Controller paks, which all have 32kB of space, are mapped between 0x0000 – 0x7FFF
for (word currSdBuffer = 0x0000; currSdBuffer < 0x8000; currSdBuffer += 512) {
// Read 32 bytes into SD buffer
myFile.read(sdBuffer, 512);
// Compare 32 byte block CRC to CRC from file
for (word currBlock = 0; currBlock < 512; currBlock += 32) {
// Calculate CRC of block and compare against crc file
if (dataCRC(&sdBuffer[currBlock]) != crcFile.read())
writeErrors++;
}
// Blink led
blinkLED();
// Update progress bar
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
// Close the file:
myFile.close();
crcFile.close();
if (writeErrors == 0) {
println_Msg(F("Saved successfully"));
sd.remove(filePath);
display_Update();
} else {
print_STR(error_STR, 0);
print_Msg(writeErrors);
println_Msg(F(" blocks "));
print_Error(did_not_verify_STR);
}
}
// Calculates the checksum of the header
boolean checkHeader(byte* buf) {
word sum = 0;
word buf_sum = (buf[28] << 8) + buf[29];
// first 28 bytes are the header, then comes the checksum(word) followed by the reverse checksum(0xFFF2 - checksum)
for (byte i = 0; i < 28; i += 2) {
sum += (buf[i] << 8) + buf[i + 1];
}
return sum == buf_sum;
}
// verifies if Controller Pak holds valid header data
void validateMPK() {
byte writeErrors = 0;
boolean failed = false;
SdFile mpk_file;
byte buf[256];
//open file on sd card
if (!mpk_file.open(fileName, O_READ)) {
print_FatalError(open_file_STR);
}
// Read first 256 byte which contains the header including checksum and reverse checksum and three copies of it
mpk_file.read(buf, sizeof(buf));
//Check all four header copies
writeErrors = 0;
if (!checkHeader(&buf[0x20]))
writeErrors++;
if (!checkHeader(&buf[0x60]))
writeErrors++;
if (!checkHeader(&buf[0x80]))
writeErrors++;
if (!checkHeader(&buf[0xC0]))
writeErrors++;
if (writeErrors)
failed = true;
print_Msg(F("HDR: "));
print_Msg(4 - writeErrors);
print_Msg(F("/4 - "));
display_Update();
// Check both TOC copies
writeErrors = 0;
// Read 2nd and 3rd 256 byte page with TOC info
for (word currSdBuffer = 0x100; currSdBuffer < 0x300; currSdBuffer += 256) {
byte sum = 0;
// Read 256 bytes into SD buffer
mpk_file.read(buf, sizeof(buf));
// Calculate TOC checksum
for (byte i = 5; i < 128; i++) {
sum += buf[(i << 1) + 1];
}
if (buf[1] != sum)
writeErrors++;
}
if (writeErrors)
failed = true;
print_Msg(F("ToC: "));
print_Msg(2 - writeErrors);
println_Msg(F("/2"));
print_Msg(F("Consistency check "));
if (failed) {
errorLvl = 1;
print_Msg(F("failed"));
} else {
errorLvl = 0;
print_Msg(F("passed"));
}
display_Update();
// Close the file:
mpk_file.close();
}
void writeMPK() {
// 3 command bytes, 32 data bytes
byte command[3 + 32];
command[0] = 0x03;
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
print_Msg(F("Writing "));
print_Msg(filePath);
println_Msg(F("..."));
display_Update();
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
//Initialize progress bar
uint32_t totalProgressBar = 0x7FFF;
draw_progressbar(0, totalProgressBar);
for (word address = 0x0000; address < 0x8000; address += 32) {
myFile.read(command + 3, sizeof(command) - 3);
word address_with_crc = addrCRC(address);
command[1] = (byte)(address_with_crc >> 8);
command[2] = (byte)(address_with_crc & 0xff);
// don't want interrupts getting in the way
noInterrupts();
sendJoyBus(command, sizeof(command));
// Enable interrupts
interrupts();
// Real N64 has about 627us pause between banks, add a bit extra delay
delayMicroseconds(650);
if ((address & 0x1FF) == 0) {
// Blink led
// Update progress bar
blinkLED();
draw_progressbar(address, totalProgressBar);
}
}
// Close the file:
myFile.close();
} else {
print_FatalError(open_file_STR);
}
}
// verifies if write was successful
void verifyMPK() {
byte block[32];
writeErrors = 0;
print_STR(verifying_STR, 1);
display_Update();
//open file on sd card
if (!myFile.open(filePath, O_READ)) {
print_FatalError(open_file_STR);
}
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(0x7FFF);
draw_progressbar(0, totalProgressBar);
// Controller paks, which all have 32kB of space, are mapped between 0x0000 – 0x7FFF
for (word currSdBuffer = 0x0000; currSdBuffer < 0x8000; currSdBuffer += sizeof(sdBuffer)) {
// Read 512 bytes into SD buffer
myFile.read(sdBuffer, sizeof(sdBuffer));
// Compare 32 byte block
for (word currBlock = 0; currBlock < sizeof(sdBuffer); currBlock += 32) {
// Read one block of the Controller Pak
readBlock(block, currSdBuffer + currBlock);
// Check against file on SD card
for (byte currByte = 0; currByte < 32; currByte++) {
if (sdBuffer[currBlock + currByte] != block[currByte]) {
writeErrors++;
}
}
// Real N64 has about 627us pause between banks, add a bit extra delay
if (currBlock < 479)
delayMicroseconds(1500);
}
// Blink led
blinkLED();
// Update progress bar
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
// Close the file:
myFile.close();
if (writeErrors == 0) {
println_Msg(F("Written successfully"));
display_Update();
} else {
print_STR(error_STR, 0);
print_Msg(writeErrors);
print_STR(_bytes_STR, 1);
print_Error(did_not_verify_STR);
}
}
/******************************************
N64 Cartridge functions
*****************************************/
void printCartInfo_N64() {
// Check cart
getCartInfo_N64();
// Print start page
if (cartSize != 0) {
display_Clear();
print_Msg(FS(FSTRING_NAME));
println_Msg(romName);
print_Msg(FS(FSTRING_SERIAL));
println_Msg(cartID);
print_Msg(FS(FSTRING_REVISION));
println_Msg(romVersion);
print_Msg(FS(FSTRING_ROM_SIZE));
print_Msg(cartSize);
println_Msg(F(" MB"));
print_Msg(F("Save Type: "));
switch (saveType) {
case 1:
println_Msg(F("SRAM"));
break;
case 2:
println_Msg(F("SRAM 768"));
break;
case 4:
println_Msg(F("FLASH"));
break;
case 5:
println_Msg(F("4K EEPROM"));
eepPages = 64;
break;
case 6:
println_Msg(F("16K EEPROM"));
eepPages = 256;
break;
default:
println_Msg(F("None/Unknown"));
break;
}
print_Msg(F("CRC1: "));
println_Msg(checksumStr);
// Wait for user input
println_Msg(FS(FSTRING_SPACE));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
} else {
// Display error
display_Clear();
println_Msg(F("GAMEPAK ERROR"));
println_Msg("");
print_Msg(FS(FSTRING_NAME));
println_Msg(romName);
print_Msg(FS(FSTRING_SERIAL));
println_Msg(cartID);
print_Msg(F("CRC1: "));
println_Msg(checksumStr);
display_Update();
strcpy(romName, "GPERROR");
print_Error(F("Cartridge unknown"));
println_Msg("");
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
// Set cartsize manually
unsigned char N64RomMenu;
// Copy menuOptions out of progmem
convertPgm(romOptionsN64, 7);
N64RomMenu = question_box(F("Select ROM size"), menuOptions, 7, 0);
// wait for user choice to come back from the question box menu
switch (N64RomMenu) {
case 0:
// 4MB
cartSize = 4;
break;
case 1:
// 8MB
cartSize = 8;
break;
case 2:
// 12MB
cartSize = 12;
break;
case 3:
// 16MB
cartSize = 16;
break;
case 4:
// 32MB
cartSize = 32;
break;
case 5:
// 64MB
cartSize = 64;
break;
case 6:
// 128MB
cartSize = 128;
break;
}
}
}
/* look-up the calculated crc in the file n64.txt on sd card
boolean searchCRC(char crcStr[9]) {
boolean result = 0;
char tempStr2[2];
char tempStr1[9];
char tempStr[5];
// Change to root dir
sd.chdir("/");
if (myFile.open("n64.txt", O_READ)) {
// Loop through file
while (myFile.available()) {
// Read 8 bytes into String, do it one at a time so byte order doesn't get mixed up
sprintf(tempStr1, "%c", myFile.read());
for (byte i = 0; i < 7; i++) {
sprintf(tempStr2, "%c", myFile.read());
strcat(tempStr1, tempStr2);
}
// Check if string is a match
if (strcasecmp(tempStr1, crcStr) == 0) {
// Skip the , in the file
myFile.seekCur(1);
// Read 4 bytes into String, do it one at a time so byte order doesn't get mixed up
sprintf(tempStr, "%c", myFile.read());
for (byte i = 0; i < 3; i++) {
sprintf(tempStr2, "%c", myFile.read());
strcat(tempStr, tempStr2);
}
if (strcmp(tempStr, cartID) == 0) {
result = 1;
break;
}
else {
result = 0;
break;
}
}
// If no match, empty string, advance by 12 and try again
else {
myFile.seekCur(12);
}
}
// Close the file:
myFile.close();
return result;
}
else {
print_FatalError(F("n64.txt missing"));
}
}*/
// look-up cart id in file n64.txt on sd card
void getCartInfo_N64() {
char tempStr[9];
int read_bytes;
// cart not in list
cartSize = 0;
saveType = 0;
// Read cart id
idCart();
display_Clear();
println_Msg(F("Searching database..."));
display_Update();
if (myFile.open("n64.txt", O_READ)) {
// Loop through file
while (myFile.available()) {
// Skip first line with name
skip_line(&myFile);
// Skip over the CRC32 checksum
myFile.seekCur(9);
// Read 8 bytes into String
read_bytes = myFile.read(tempStr, 8);
tempStr[read_bytes == -1 ? 0 : read_bytes] = 0;
// Check if string is a match
if (strcmp(tempStr, checksumStr) == 0) {
// Skip the , in the file
myFile.seekCur(1);
read_bytes = myFile.read(tempStr, 2);
tempStr[read_bytes == -1 ? 0 : read_bytes] = 0;
cartSize = atoi(tempStr);
// Skip the , in the file
myFile.seekCur(1);
// Read the next ascii character and subtract 48 to convert to decimal
saveType = myFile.read() - 48;
// End loop
break;
}
// If no match skip to next entry
else {
// skip rest of line
myFile.seekCur(7);
// skip third empty line
skip_line(&myFile);
}
}
// Close the file:
myFile.close();
} else {
print_FatalError(F("n64.txt missing"));
}
}
// Read rom ID
void idCart() {
// Set the address
setAddress_N64(romBase);
// Read first 64 bytes of rom
for (int c = 0; c < 64; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
// CRC1
sprintf(checksumStr, "%02X%02X%02X%02X", sdBuffer[0x10], sdBuffer[0x11], sdBuffer[0x12], sdBuffer[0x13]);
// Get cart id
cartID[0] = sdBuffer[0x3B];
cartID[1] = sdBuffer[0x3C];
cartID[2] = sdBuffer[0x3D];
cartID[3] = sdBuffer[0x3E];
// Get rom version
romVersion = sdBuffer[0x3F];
// If name consists out of all japanese characters use cart id
if (buildRomName(romName, &sdBuffer[0x20], 20) == 0) {
strcpy(romName, cartID);
}
#ifdef OPTION_N64_SAVESUMMARY
// Get CRC1
for (int i = 0; i < 4; i++) {
if (sdBuffer[0x10 + i] < 0x10) {
CRC1 += '0';
}
CRC1 += String(sdBuffer[0x10 + i], HEX);
}
// Get CRC2
for (int i = 0; i < 4; i++) {
if (sdBuffer[0x14 + i] < 0x10) {
CRC2 += '0';
}
CRC2 += String(sdBuffer[0x14 + i], HEX);
}
#endif
}
// Write Eeprom to cartridge
void writeEeprom_N64() {
if ((saveType == 5) || (saveType == 6)) {
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
println_Msg(F("Writing..."));
println_Msg(filePath);
display_Update();
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
// 2 command bytes and 8 data bytes
byte command[2 + 8];
command[0] = 0x05;
// Note: eepPages can be 256, so page must be able to get to 256 for the
// loop to exit. So it is not possible to use command[1] directly as loop
// counter.
for (int page = 0; page < eepPages; page++) {
command[1] = page;
// TODO: read 512 bytes in a 512 + 2 bytes buffer, and move the command start 32 bytes at a time
myFile.read(command + 2, sizeof(command) - 2);
// Disable interrupts for more uniform clock pulses
// Blink led
blinkLED();
if (page)
delay(50); // Wait 50ms between pages when writing
noInterrupts();
sendJoyBus(command, sizeof(command));
interrupts();
}
// Close the file:
myFile.close();
print_STR(done_STR, 1);
display_Update();
delay(600);
} else {
print_FatalError(sd_error_STR);
}
} else {
print_FatalError(F("Savetype Error"));
}
}
boolean readEepromPageList(byte* output, byte page_number, byte page_count) {
byte command[] = { 0x04, page_number };
// Disable interrupts for more uniform clock pulses
while (page_count--) {
// Blink led
blinkLED();
noInterrupts();
sendJoyBus(command, sizeof(command));
// XXX: is it possible to read more than 8 bytes at a time ?
if (recvJoyBus(output, 8) > 0) {
// If any missing bytes error out
interrupts();
return 0;
break;
}
interrupts();
if (page_count)
delayMicroseconds(600); // wait 600us between pages when reading
command[1]++;
output += 8;
}
return 1;
}
// Reset Eeprom
void resetEeprom_N64() {
// Pull RESET(PH0) low
PORTH &= ~(1 << 0);
delay(100);
// Pull RESET(PH0) high
PORTH |= (1 << 0);
delay(100);
}
// Dump Eeprom to SD
void readEeprom_N64() {
if ((saveType == 5) || (saveType == 6)) {
// Get name, add extension and convert to char array for sd lib
createFolderAndOpenFile("N64", "SAVE", romName, "eep");
for (int i = 0; i < eepPages; i += sizeof(sdBuffer) / 8) {
// If any missing bytes error out
if (readEepromPageList(sdBuffer, i, sizeof(sdBuffer) / 8) == 0) {
println_Msg(FS(FSTRING_EMPTY));
print_STR(error_STR, 0);
println_Msg(F("no data received"));
println_Msg(FS(FSTRING_EMPTY));
break;
}
// Write 64 pages at once to the SD card
myFile.write(sdBuffer, sizeof(sdBuffer));
}
// Close the file:
myFile.close();
} else {
print_FatalError(F("Savetype Error"));
}
}
// Check if a write succeeded, returns 0 if all is ok and number of errors if not
unsigned long verifyEeprom_N64() {
unsigned long writeErrors;
if ((saveType == 5) || (saveType == 6)) {
writeErrors = 0;
display_Clear();
print_Msg(F("Verifying against "));
println_Msg(filePath);
display_Update();
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
for (int i = 0; i < eepPages; i += sizeof(sdBuffer) / 8) {
readEepromPageList(sdBuffer, i, sizeof(sdBuffer) / 8);
// Check sdBuffer content against file on sd card
for (size_t c = 0; c < sizeof(sdBuffer); c++) {
if (myFile.read() != sdBuffer[c]) {
writeErrors++;
}
}
}
// Close the file:
myFile.close();
} else {
// SD Error
writeErrors = 999999;
print_FatalError(sd_error_STR);
}
// Return 0 if verified ok, or number of errors
return writeErrors;
} else {
print_FatalError(F("Savetype Error"));
return 1;
}
}
/******************************************
SRAM functions
*****************************************/
// Write sram to cartridge
void writeSram(unsigned long sramSize) {
if (saveType == 1 || saveType == 2) {
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
println_Msg(F("Writing..."));
println_Msg(filePath);
display_Update();
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
for (unsigned long currByte = sramBase; currByte < (sramBase + sramSize); currByte += 512) {
// Read save from SD into buffer
myFile.read(sdBuffer, 512);
// Set the address for the next 512 bytes
setAddress_N64(currByte);
for (int c = 0; c < 512; c += 2) {
// Join bytes to word
word myWord = ((sdBuffer[c] & 0xFF) << 8) | (sdBuffer[c + 1] & 0xFF);
// Write word
writeWord_N64(myWord);
}
}
// Close the file:
myFile.close();
print_STR(done_STR, 1);
display_Update();
} else {
print_FatalError(sd_error_STR);
}
} else {
print_FatalError(F("Savetype Error"));
}
}
// Read sram and save to the SD card
void readSram(unsigned long sramSize, byte flashramType) {
word myWord;
int offset = 512;
int bufferSize = 512;
if (flashramType == 2) {
offset = 64;
bufferSize = 128;
}
// Get name, add extension and convert to char array for sd lib
const char* suffix;
if (saveType == 4) {
suffix = "fla";
} else if (saveType == 1) {
suffix = "sra";
} else if (saveType == 2) {
suffix = "768";
} else {
print_FatalError(F("Savetype Error"));
}
createFolderAndOpenFile("N64", "SAVE", romName, suffix);
for (unsigned long currByte = sramBase; currByte < (sramBase + (sramSize / flashramType)); currByte += offset) {
// Set the address
setAddress_N64(currByte);
for (int c = 0; c < bufferSize; c += 2) {
// read, split and write word to buffer
myWord = readWord_N64();
sdBuffer[c] = myWord >> 8;
sdBuffer[c + 1] = myWord & 0xFF;
}
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
myFile.write(sdBuffer, bufferSize);
}
// Close the file:
myFile.close();
}
unsigned long verifySram(unsigned long sramSize, byte flashramType) {
writeErrors = 0;
int offset = 512;
int bufferSize = 512;
if (flashramType == 2) {
offset = 64;
bufferSize = 128;
}
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
for (unsigned long currByte = sramBase; currByte < (sramBase + (sramSize / flashramType)); currByte += offset) {
// Set the address
setAddress_N64(currByte);
for (int c = 0; c < bufferSize; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
// Check sdBuffer content against file on sd card
for (int i = 0; i < bufferSize; i++) {
if (myFile.read() != sdBuffer[i]) {
writeErrors++;
}
}
}
// Close the file:
myFile.close();
} else {
print_FatalError(sd_error_STR);
}
// Return 0 if verified ok, or number of errors
return writeErrors;
}
/******************************************
Flashram functions
*****************************************/
// Send a command to the flashram command register
void sendFramCmd(unsigned long myCommand) {
// Split command into two words
word myComLowOut = myCommand & 0xFFFF;
word myComHighOut = myCommand >> 16;
// Set address to command register
setAddress_N64(0x08010000);
// Send command
writeWord_N64(myComHighOut);
writeWord_N64(myComLowOut);
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
}
// Init fram
void initFram() {
// FRAM_EXECUTE_CMD
sendFramCmd(0xD2000000);
delay(10);
// FRAM_EXECUTE_CMD
sendFramCmd(0xD2000000);
delay(10);
//FRAM_STATUS_MODE_CMD
sendFramCmd(0xE1000000);
delay(10);
}
void writeFram(byte flashramType) {
if (saveType == 4) {
// Erase fram
eraseFram();
// Check if empty
if (blankcheck_N64(flashramType) == 0) {
println_Msg(FS(FSTRING_OK));
display_Update();
} else {
println_Msg(F("FAIL"));
display_Update();
}
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
print_Msg(F("Writing "));
println_Msg(filePath);
display_Update();
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
// Init fram
initFram();
// Write all 8 fram banks
print_Msg(F("Bank "));
for (byte bank = 0; bank < 8; bank++) {
print_Msg(bank);
print_Msg(FS(FSTRING_SPACE));
display_Update();
// Write one bank of 128*128 bytes
for (byte offset = 0; offset < 128; offset++) {
// Read save from SD into buffer
myFile.read(sdBuffer, 128);
// FRAM_WRITE_MODE_CMD
sendFramCmd(0xB4000000);
delay(1);
// Set the address for the next 128 bytes
setAddress_N64(0x08000000);
// Send 128 bytes, 64 words
for (byte c = 0; c < 128; c += 2) {
// Join two bytes into one word
word myWord = ((sdBuffer[c] & 0xFF) << 8) | (sdBuffer[c + 1] & 0xFF);
// Write word
writeWord_N64(myWord);
}
// Delay between each "DMA"
delay(1);
//FRAM_WRITE_OFFSET_CMD + offset
sendFramCmd((0xA5000000 | (((bank * 128) + offset) & 0xFFFF)));
delay(1);
// FRAM_EXECUTE_CMD
sendFramCmd(0xD2000000);
while (waitForFram(flashramType)) {
delay(1);
}
}
// Delay between banks
delay(20);
}
println_Msg("");
// Close the file:
myFile.close();
} else {
print_FatalError(sd_error_STR);
}
} else {
print_FatalError(F("Savetype Error"));
}
}
// Delete all 8 flashram banks
void eraseFram() {
if (saveType == 4) {
print_Msg(F("Erasing..."));
display_Update();
// Init fram
initFram();
// Erase fram
// 0x4B00007F 0x4B0000FF 0x4B00017F 0x4B0001FF 0x4B00027F 0x4B0002FF 0x4B00037F 0x4B0003FF
for (unsigned long bank = 0x4B00007F; bank < 0x4B00047F; bank += 0x80) {
sendFramCmd(bank);
delay(10);
// FRAM_ERASE_MODE_CMD
sendFramCmd(0x78000000);
delay(10);
// FRAM_EXECUTE_CMD
sendFramCmd(0xD2000000);
while (waitForFram(flashramType)) {
delay(1);
}
}
} else {
print_FatalError(F("Savetype Error"));
}
}
// Read flashram
void readFram(byte flashramType) {
if (saveType == 4) {
// Put flashram into read mode
// FRAM_READ_MODE_CMD
sendFramCmd(0xF0000000);
// Read Flashram
readSram(131072, flashramType);
} else {
print_FatalError(F("Savetype Error"));
}
}
// Verify flashram
unsigned long verifyFram(byte flashramType) {
// Put flashram into read mode
// FRAM_READ_MODE_CMD
sendFramCmd(0xF0000000);
writeErrors = verifySram(131072, flashramType);
return writeErrors;
}
// Blankcheck flashram
unsigned long blankcheck_N64(byte flashramType) {
writeErrors = 0;
int offset = 512;
int bufferSize = 512;
if (flashramType == 2) {
offset = 64;
bufferSize = 128;
}
// Put flashram into read mode
// FRAM_READ_MODE_CMD
sendFramCmd(0xF0000000);
// Read Flashram
for (unsigned long currByte = sramBase; currByte < (sramBase + (131072 / flashramType)); currByte += offset) {
// Set the address for the next 512 bytes
setAddress_N64(currByte);
for (int c = 0; c < bufferSize; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
// Check sdBuffer content against file on sd card
for (int i = 0; i < bufferSize; i++) {
if (0xFF != sdBuffer[i]) {
writeErrors++;
}
}
}
// Return 0 if verified ok, or number of errors
return writeErrors;
}
// Wait until current operation is done
byte waitForFram(byte flashramType) {
byte framStatus = 0;
byte statusMXL1100[] = { 0x11, 0x11, 0x80, 0x01, 0x00, 0xC2, 0x00, 0x1E };
byte statusMXL1101[] = { 0x11, 0x11, 0x80, 0x01, 0x00, 0xC2, 0x00, 0x1D };
byte statusMN63F81[] = { 0x11, 0x11, 0x80, 0x01, 0x00, 0x32, 0x00, 0xF1 };
// FRAM_STATUS_MODE_CMD
sendFramCmd(0xE1000000);
delay(1);
// Set address to Fram status register
setAddress_N64(0x08000000);
// Read Status
for (byte c = 0; c < 8; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
if (flashramType == 2) {
for (byte c = 0; c < 8; c++) {
if (statusMXL1100[c] != sdBuffer[c]) {
framStatus = 1;
}
}
} else if (flashramType == 1) {
//MX29L1101
if (MN63F81MPN == false) {
for (byte c = 0; c < 8; c++) {
if (statusMXL1101[c] != sdBuffer[c]) {
framStatus = 1;
}
}
}
//MN63F81MPN
else if (MN63F81MPN == true) {
for (byte c = 0; c < 8; c++) {
if (statusMN63F81[c] != sdBuffer[c]) {
framStatus = 1;
}
}
}
}
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
return framStatus;
}
// Get flashram type
void getFramType() {
// FRAM_STATUS_MODE_CMD
sendFramCmd(0xE1000000);
delay(10);
// Set address to Fram status register
setAddress_N64(0x08000000);
// Read Status
for (byte c = 0; c < 8; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
//MX29L1100
if (sdBuffer[7] == 0x1e) {
flashramType = 2;
println_Msg(F("Type: MX29L1100"));
display_Update();
}
//MX29L1101
else if (sdBuffer[7] == 0x1d) {
flashramType = 1;
MN63F81MPN = false;
println_Msg(F("Type: MX29L1101"));
display_Update();
}
//MN63F81MPN
else if (sdBuffer[7] == 0xf1) {
flashramType = 1;
MN63F81MPN = true;
println_Msg(F("Type: MN63F81MPN"));
display_Update();
}
// 29L1100KC-15B0 compat MX29L1101
else if ((sdBuffer[7] == 0x8e) || (sdBuffer[7] == 0x84)) {
flashramType = 1;
MN63F81MPN = false;
println_Msg(F("Type: 29L1100KC-15B0"));
println_Msg(F("(compat. MX29L1101)"));
display_Update();
}
// Type unknown
else {
for (byte c = 0; c < 8; c++) {
print_Msg(sdBuffer[c], HEX);
if (c < 7)
print_Msg(F(", "));
if (c == 7)
println_Msg(FS(FSTRING_EMPTY));
}
print_FatalError(F("Flashram unknown"));
}
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
}
/******************************************
Rom functions
*****************************************/
// Read rom and save to the SD card
#ifndef OPTION_N64_FASTCRC
// dumping rom slow
void readRom_N64() {
// Get name, add extension and convert to char array for sd lib
createFolder("N64", "ROM", romName, "Z64");
// clear the screen
// display_Clear();
printAndIncrementFolder();
// Open file on sd card
if (!myFile.open(fileName, O_RDWR | O_CREAT)) {
print_FatalError(create_file_STR);
}
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(cartSize)*1024 * 1024;
draw_progressbar(0, totalProgressBar);
for (unsigned long currByte = romBase; currByte < (romBase + (cartSize * 1024 * 1024)); currByte += 512) {
// Blink led
if ((currByte & 0x3FFF) == 0)
blinkLED();
// Set the address for the next 512 bytes
setAddress_N64(currByte);
for (word c = 0; c < 512; c += 2) {
word myWord = readWord_N64();
sdBuffer[c] = myWord >> 8;
sdBuffer[c + 1] = myWord & 0xFF;
}
myFile.write(sdBuffer, 512);
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
// Pull ale_H(PC1) high
PORTC |= (1 << 1);
}
// Close the file:
myFile.close();
}
#else
// dumping rom fast
uint32_t readRom_N64() {
// Get name, add extension and convert to char array for sd lib
createFolder("N64", "ROM", romName, "Z64");
// clear the screen
// display_Clear();
printAndIncrementFolder();
// Open file on sd card
if (!myFile.open(fileName, O_RDWR | O_CREAT)) {
print_FatalError(create_file_STR);
}
byte buffer[1024];
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(cartSize)*1024 * 1024;
draw_progressbar(0, totalProgressBar);
// prepare crc32
uint32_t oldcrc32 = 0xFFFFFFFF;
// run combined dumper + crc32 routine for better performance, as N64 ROMs are quite large for an 8bit micro
// currently dumps + checksums a 32MB cart in 170 seconds (down from 347 seconds)
for (unsigned long currByte = romBase; currByte < (romBase + (cartSize * 1024 * 1024)); currByte += 1024) {
// Blink led
if (currByte % 16384 == 0)
blinkLED();
// Set the address for the first 512 bytes to dump
setAddress_N64(currByte);
// Wait 62.5ns (safety)
NOP;
for (int c = 0; c < 512; c += 2) {
// Pull read(PH6) low
PORTH &= ~(1 << 6);
// Wait ~310ns
NOP;
NOP;
NOP;
NOP;
NOP;
// data on PINK and PINF is valid now, read into sd card buffer
buffer[c] = PINK; // hiByte
buffer[c + 1] = PINF; // loByte
// Pull read(PH6) high
PORTH |= (1 << 6);
// crc32 update
UPDATE_CRC(oldcrc32, buffer[c]);
UPDATE_CRC(oldcrc32, buffer[c + 1]);
}
// Set the address for the next 512 bytes to dump
setAddress_N64(currByte + 512);
// Wait 62.5ns (safety)
NOP;
for (int c = 512; c < 1024; c += 2) {
// Pull read(PH6) low
PORTH &= ~(1 << 6);
// Wait ~310ns
NOP;
NOP;
NOP;
NOP;
NOP;
// data on PINK and PINF is valid now, read into sd card buffer
buffer[c] = PINK; // hiByte
buffer[c + 1] = PINF; // loByte
// Pull read(PH6) high
PORTH |= (1 << 6);
// crc32 update
UPDATE_CRC(oldcrc32, buffer[c]);
UPDATE_CRC(oldcrc32, buffer[c + 1]);
}
processedProgressBar += 1024;
draw_progressbar(processedProgressBar, totalProgressBar);
// write out 1024 bytes to file
myFile.write(buffer, 1024);
}
// Close the file:
myFile.close();
// Return checksum
return oldcrc32;
}
#endif
#ifdef OPTION_N64_SAVESUMMARY
// Save an info.txt with information on the dumped rom to the SD card
void savesummary_N64(boolean checkfound, char crcStr[9], unsigned long timeElapsed) {
// Open file on sd card
if (!myFile.open("N64/ROM/n64log.txt", O_RDWR | O_CREAT | O_APPEND)) {
print_FatalError(sd_error_STR);
}
//Write the info
myFile.print(F("Name\t: "));
myFile.println(romName);
myFile.print(F("ID\t: "));
myFile.println(cartID);
myFile.print(F("ROM CRC1: "));
myFile.println(CRC1);
myFile.print(F("ROM CRC2: "));
myFile.println(CRC2);
myFile.print(F("Size\t: "));
myFile.print(cartSize);
myFile.println(F(" MB"));
myFile.print(F("Save\t: "));
switch (saveType) {
case 1:
myFile.println(F("SRAM"));
break;
case 4:
myFile.println(F("FLASH"));
break;
case 5:
myFile.println(F("4K EEPROM"));
break;
case 6:
myFile.println(F("16K EEPROM"));
break;
default:
myFile.println(F("None/Unknown"));
break;
}
myFile.print(F("Version\t: 1."));
myFile.println(romVersion);
myFile.print(F("Saved To: "));
myFile.println(folder);
#ifdef ENABLE_RTC
myFile.print(F("Dumped\t: "));
myFile.println(RTCStamp());
#endif
myFile.print(F("CRC\t: "));
myFile.print(crcStr);
if (checkfound) {
// Dump was a known good rom
// myFile.println(F("Checksum matches"));
myFile.println(" [Match]");
} else {
// myFile.println(F("Checksum not found"));
myFile.println(" [No Match]");
}
myFile.print(F("Time\t: "));
myFile.println(timeElapsed);
myFile.println(FS(FSTRING_SPACE));
// Close the file:
myFile.close();
}
#endif
#if defined(ENABLE_FLASH)
/******************************************
N64 Repro Flashrom Functions
*****************************************/
void flashRepro_N64() {
unsigned long sectorSize = 0;
byte bufferSize = 0;
// Check flashrom ID's
idFlashrom_N64();
// If the ID is known continue
if (cartSize != 0) {
// Print flashrom name
if ((flashid == 0x227E) && (strcmp(cartID, "2201") == 0)) {
print_Msg(F("Spansion S29GL256N"));
if (cartSize == 64)
println_Msg(F(" x2"));
else
println_Msg("");
} else if ((flashid == 0x227E) && (strcmp(cartID, "2101") == 0)) {
print_Msg(F("Spansion S29GL128N"));
} else if ((flashid == 0x227E) && (strcmp(cartID, "2100") == 0)) {
print_Msg(F("ST M29W128GL"));
} else if ((flashid == 0x22C9) || (flashid == 0x22CB)) {
print_Msg(F("Macronix MX29LV640"));
if (cartSize == 16)
println_Msg(F(" x2"));
else
println_Msg("");
} else if (flashid == 0x8816)
println_Msg(F("Intel 4400L0ZDQ0"));
else if (flashid == 0x7E7E)
println_Msg(F("Fujitsu MSP55LV100S"));
else if ((flashid == 0x227E) && (strcmp(cartID, "2301") == 0))
println_Msg(F("Fujitsu MSP55LV512"));
else if ((flashid == 0x227E) && (strcmp(cartID, "3901") == 0))
println_Msg(F("Intel 512M29EW"));
// Print info
print_Msg(F("ID: "));
print_Msg(flashid_str);
print_Msg(F(" Size: "));
print_Msg(cartSize);
println_Msg(F("MB"));
println_Msg("");
println_Msg(F("This will erase your"));
println_Msg(F("Repro Cartridge."));
println_Msg(F("Attention: Use 3.3V!"));
println_Msg("");
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
} else {
println_Msg(F("Unknown flashrom"));
print_Msg(F("ID: "));
print_Msg(vendorID);
print_Msg(FS(FSTRING_SPACE));
print_Msg(flashid_str);
print_Msg(FS(FSTRING_SPACE));
println_Msg(cartID);
println_Msg(FS(FSTRING_SPACE));
println_Msg(F("Press button for"));
println_Msg(F("manual config"));
println_Msg(F("This will erase your"));
println_Msg(F("Repro Cartridge."));
println_Msg(F("Attention: Use 3.3V!"));
display_Update();
wait();
// clear IDs
sprintf(vendorID, "%s", "CONF");
flashid = 0;
sprintf(flashid_str, "%s", "CONF");
sprintf(cartID, "%s", "CONF");
// Set cartsize manually
unsigned char N64RomMenu;
// Copy menuOptions out of progmem
convertPgm(romOptionsN64, 7);
N64RomMenu = question_box(F("Select flash size"), menuOptions, 7, 0);
// wait for user choice to come back from the question box menu
switch (N64RomMenu) {
case 0:
// 4MB
cartSize = 4;
break;
case 1:
// 8MB
cartSize = 8;
break;
case 2:
// 12MB
cartSize = 12;
break;
case 3:
// 16MB
cartSize = 16;
break;
case 4:
// 32MB
cartSize = 32;
break;
case 5:
// 64MB
cartSize = 64;
break;
case 6:
// 128MB
cartSize = 128;
break;
}
// Set flash buffer manually
unsigned char N64BufferMenu;
// Copy menuOptions out of progmem
convertPgm(bufferOptionsN64, 4);
N64BufferMenu = question_box(F("Select buffer size"), menuOptions, 4, 0);
// wait for user choice to come back from the question box menu
switch (N64BufferMenu) {
case 0:
// no buffer
bufferSize = 0;
break;
case 1:
// 32 byte buffer
bufferSize = 32;
break;
case 2:
// 64 byte buffer
bufferSize = 64;
break;
case 3:
// 128 byte buffer
bufferSize = 128;
break;
}
// Set sector size manually
unsigned char N64SectorMenu;
// Copy menuOptions out of progmem
convertPgm(sectorOptionsN64, 4);
N64SectorMenu = question_box(F("Select sector size"), menuOptions, 4, 0);
// wait for user choice to come back from the question box menu
switch (N64SectorMenu) {
case 0:
// 8KB sectors
sectorSize = 0x2000;
break;
case 1:
// 32KB sectors
sectorSize = 0x8000;
break;
case 2:
// 64KB sectors
sectorSize = 0x10000;
break;
case 3:
// 128KB sectors
sectorSize = 0x20000;
break;
}
}
// Launch file browser
filePath[0] = '\0';
sd.chdir("/");
fileBrowser(F("Select z64 file"));
display_Clear();
display_Update();
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
// Get rom size from file
fileSize = myFile.fileSize();
print_Msg(F("File size: "));
print_Msg(fileSize / 1048576);
println_Msg(F("MB"));
display_Update();
// Compare file size to flashrom size
if ((fileSize / 1048576) > cartSize) {
print_FatalError(file_too_big_STR);
}
// Erase needed sectors
if (flashid == 0x227E) {
// Spansion S29GL256N or Fujitsu MSP55LV512 with 0x20000 sector size and 32 byte buffer
eraseSector_N64(0x20000);
} else if (flashid == 0x7E7E) {
// Fujitsu MSP55LV100S
eraseMSP55LV100_N64();
} else if ((flashid == 0x8813) || (flashid == 0x8816)) {
// Intel 4400L0ZDQ0
eraseIntel4400_N64();
resetIntel4400_N64();
} else if ((flashid == 0x22C9) || (flashid == 0x22CB)) {
// Macronix MX29LV640, C9 is top boot and CB is bottom boot block
eraseSector_N64(0x8000);
} else {
eraseFlashrom_N64();
}
// Check if erase was successful
if (blankcheckFlashrom_N64()) {
// Write flashrom
println_Msg(FS(FSTRING_OK));
print_Msg(F("Writing "));
println_Msg(filePath);
display_Update();
if ((strcmp(cartID, "3901") == 0) && (flashid == 0x227E)) {
// Intel 512M29EW(64MB) with 0x20000 sector size and 128 byte buffer
writeFlashBuffer_N64(0x20000, 128);
} else if ((strcmp(cartID, "2100") == 0) && (flashid == 0x227E)) {
// ST M29W128GH(16MB) with 0x20000 sector size and 64 byte buffer
writeFlashBuffer_N64(0x20000, 64);
} else if (flashid == 0x227E) {
// Spansion S29GL128N/S29GL256N or Fujitsu MSP55LV512 with 0x20000 sector size and 32 byte buffer
writeFlashBuffer_N64(0x20000, 32);
} else if (flashid == 0x7E7E) {
//Fujitsu MSP55LV100S
writeMSP55LV100_N64(0x20000);
} else if ((flashid == 0x22C9) || (flashid == 0x22CB)) {
// Macronix MX29LV640 without buffer and 0x8000 sector size
writeFlashrom_N64(0x8000);
} else if ((flashid == 0x8813) || (flashid == 0x8816)) {
// Intel 4400L0ZDQ0
writeIntel4400_N64();
resetIntel4400_N64();
} else if (sectorSize) {
if (bufferSize) {
writeFlashBuffer_N64(sectorSize, bufferSize);
} else {
writeFlashrom_N64(sectorSize);
}
} else {
print_FatalError(F("sectorSize not set"));
}
// Close the file:
myFile.close();
// Verify
print_STR(verifying_STR, 1);
display_Update();
writeErrors = verifyFlashrom_N64();
if (writeErrors != 0) {
display_Clear();
print_Msg(writeErrors);
print_Msg(F(" bytes "));
print_Error(did_not_verify_STR);
}
} else {
// Close the file
myFile.close();
print_Error(F("failed"));
}
} else {
print_Error(open_file_STR);
}
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
display_Clear();
display_Update();
}
// Reset to read mode
void resetIntel4400_N64() {
for (unsigned long currPartition = 0; currPartition < (cartSize * 0x100000); currPartition += 0x20000) {
setAddress_N64(romBase + currPartition);
writeWord_N64(0xFF);
}
}
// Reset Fujitsu MSP55LV100S
void resetMSP55LV100_N64(unsigned long flashBase) {
// Send reset Command
setAddress_N64(flashBase);
writeWord_N64(0xF0F0);
delay(100);
}
// Common reset command
void resetFlashrom_N64(unsigned long flashBase) {
// Send reset Command
setAddress_N64(flashBase);
writeWord_N64(0xF0);
delay(100);
}
void sendFlashromCommand_N64(unsigned long addr, byte cmd) {
setAddress_N64(addr + (0x555 << 1));
writeWord_N64(0xAA);
setAddress_N64(addr + (0x2AA << 1));
writeWord_N64(0x55);
setAddress_N64(addr + (0x555 << 1));
writeWord_N64(cmd);
}
void idFlashrom_N64() {
// Set size to 0 if no ID is found
cartSize = 0;
// Send flashrom ID command
sendFlashromCommand_N64(romBase, 0x90);
// Read 1 byte vendor ID
setAddress_N64(romBase);
sprintf(vendorID, "%02X", readWord_N64());
// Read 2 bytes flashrom ID
flashid = readWord_N64();
sprintf(flashid_str, "%04X", flashid);
// Read 2 bytes secondary flashrom ID
setAddress_N64(romBase + 0x1C);
sprintf(cartID, "%04X", ((readWord_N64() << 8) | (readWord_N64() & 0xFF)));
// Spansion S29GL256N(32MB/64MB) with either one or two flashrom chips
if ((strcmp(cartID, "2201") == 0) && (flashid == 0x227E)) {
cartSize = 32;
// Reset flashrom
resetFlashrom_N64(romBase);
// Test for second flashrom chip at 0x2000000 (32MB)
sendFlashromCommand_N64(romBase + 0x2000000, 0x90);
char tempID[5];
setAddress_N64(romBase + 0x2000000);
// Read manufacturer ID
readWord_N64();
// Read flashrom ID
sprintf(tempID, "%04X", readWord_N64());
// Check if second flashrom chip is present
if (strcmp(tempID, "227E") == 0) {
cartSize = 64;
}
resetFlashrom_N64(romBase + 0x2000000);
}
// Macronix MX29LV640(8MB/16MB) with either one or two flashrom chips
else if ((flashid == 0x22C9) || (flashid == 0x22CB)) {
cartSize = 8;
resetFlashrom_N64(romBase + 0x800000);
// Test for second flashrom chip at 0x800000 (8MB)
sendFlashromCommand_N64(romBase + 0x800000, 0x90);
char tempID[5];
setAddress_N64(romBase + 0x800000);
// Read manufacturer ID
readWord_N64();
// Read flashrom ID
sprintf(tempID, "%04X", readWord_N64());
// Check if second flashrom chip is present
if ((strcmp(tempID, "22C9") == 0) || (strcmp(tempID, "22CB") == 0)) {
cartSize = 16;
}
resetFlashrom_N64(romBase + 0x800000);
}
// Intel 4400L0ZDQ0 (64MB)
else if (flashid == 0x8816) {
// Found first flashrom chip, set to 32MB
cartSize = 32;
resetIntel4400_N64();
// Test if second half of the flashrom might be hidden
sendFlashromCommand_N64(romBase + 0x2000000, 0x90);
// Read manufacturer ID
setAddress_N64(romBase + 0x2000000);
readWord_N64();
// Read flashrom ID
sprintf(cartID, "%04X", readWord_N64());
if (strcmp(cartID, "8813") == 0) {
cartSize = 64;
flashid = 0x8813;
strncpy(flashid_str, cartID, 5);
}
resetIntel4400_N64();
// Empty cartID string
cartID[0] = '\0';
}
//Fujitsu MSP55LV512/Spansion S29GL512N (64MB)
else if ((strcmp(cartID, "2301") == 0) && (flashid == 0x227E)) {
cartSize = 64;
// Reset flashrom
resetFlashrom_N64(romBase);
}
// Spansion S29GL128N(16MB) with one flashrom chip
else if ((strcmp(cartID, "2101") == 0) && (flashid == 0x227E)) {
cartSize = 16;
// Reset flashrom
resetFlashrom_N64(romBase);
}
// ST M29W128GL(16MB) with one flashrom chip
else if ((strcmp(cartID, "2100") == 0) && (flashid == 0x227E)) {
cartSize = 16;
// Reset flashrom
resetFlashrom_N64(romBase);
}
// Intel 512M29EW(64MB) with one flashrom chip
else if ((strcmp(cartID, "3901") == 0) && (flashid == 0x227E)) {
cartSize = 64;
// Reset flashrom
resetFlashrom_N64(romBase);
}
// Unknown 227E type
else if (flashid == 0x227E) {
cartSize = 0;
// Reset flashrom
resetFlashrom_N64(romBase);
}
//Test for Fujitsu MSP55LV100S (64MB)
else {
// Send flashrom ID command
setAddress_N64(romBase + (0x555 << 1));
writeWord_N64(0xAAAA);
setAddress_N64(romBase + (0x2AA << 1));
writeWord_N64(0x5555);
setAddress_N64(romBase + (0x555 << 1));
writeWord_N64(0x9090);
setAddress_N64(romBase);
// Read 1 byte vendor ID
readWord_N64();
// Read 2 bytes flashrom ID
sprintf(cartID, "%04X", readWord_N64());
if (strcmp(cartID, "7E7E") == 0) {
resetMSP55LV100_N64(romBase);
cartSize = 64;
flashid = 0x7E7E;
strncpy(flashid_str, cartID, 5);
}
}
if ((flashid == 0x1240) && (strcmp(cartID, "1240") == 0)) {
print_FatalError(F("Please reseat cartridge"));
}
}
// Erase Intel flashrom
void eraseIntel4400_N64() {
unsigned long flashBase = romBase;
print_Msg(F("Erasing..."));
display_Update();
// If the game is smaller than 32Mbit only erase the needed blocks
unsigned long lastBlock = 0x1FFFFFF;
if (fileSize < 0x1FFFFFF)
lastBlock = fileSize;
// Erase 4 blocks with 16kwords each
for (unsigned long currBlock = 0x0; currBlock < 0x1FFFF; currBlock += 0x8000) {
// Unlock block command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x60);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Erase command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x20);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Read the status register
setAddress_N64(flashBase + currBlock);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(flashBase + currBlock);
statusReg = readWord_N64();
}
}
// Erase up to 255 blocks with 64kwords each
for (unsigned long currBlock = 0x20000; currBlock < lastBlock; currBlock += 0x1FFFF) {
// Unlock block command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x60);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Erase command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x20);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Read the status register
setAddress_N64(flashBase + currBlock);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(flashBase + currBlock);
statusReg = readWord_N64();
}
// Blink led
blinkLED();
}
// Check if we should erase the second chip too
if ((cartSize = 64) && (fileSize > 0x2000000)) {
// Switch base address to second chip
flashBase = romBase + 0x2000000;
// 255 blocks with 64kwords each
for (unsigned long currBlock = 0x0; currBlock < 0x1FDFFFF; currBlock += 0x1FFFF) {
// Unlock block command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x60);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Erase command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x20);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Read the status register
setAddress_N64(flashBase + currBlock);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(flashBase + currBlock);
statusReg = readWord_N64();
}
// Blink led
blinkLED();
}
// 4 blocks with 16kword each
for (unsigned long currBlock = 0x1FE0000; currBlock < 0x1FFFFFF; currBlock += 0x8000) {
// Unlock block command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x60);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Erase command
setAddress_N64(flashBase + currBlock);
writeWord_N64(0x20);
setAddress_N64(flashBase + currBlock);
writeWord_N64(0xD0);
// Read the status register
setAddress_N64(flashBase + currBlock);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(flashBase + currBlock);
statusReg = readWord_N64();
}
}
}
}
// Erase Fujutsu MSP55LV100S
void eraseMSP55LV100_N64() {
unsigned long flashBase = romBase;
unsigned long sectorSize = 0x20000;
print_Msg(F("Erasing..."));
display_Update();
for (unsigned long currSector = 0; currSector < fileSize; currSector += sectorSize) {
// Blink led
blinkLED();
// Send Erase Command to first chip
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0xAAAA);
setAddress_N64(flashBase + (0x2AA << 1));
writeWord_N64(0x5555);
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0x8080);
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0xAAAA);
setAddress_N64(flashBase + (0x2AA << 1));
writeWord_N64(0x5555);
setAddress_N64(romBase + currSector);
writeWord_N64(0x3030);
// Read the status register
setAddress_N64(romBase + currSector);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(romBase + currSector);
statusReg = readWord_N64();
}
// Read the status register
setAddress_N64(romBase + currSector);
statusReg = readWord_N64();
while ((statusReg | 0x7FFF) != 0xFFFF) {
setAddress_N64(romBase + currSector);
statusReg = readWord_N64();
}
}
}
// Common chip erase command
void eraseFlashrom_N64() {
print_Msg(F("Chip erase..."));
display_Update();
// Send Erase Command
sendFlashromCommand_N64(romBase, 0x80);
sendFlashromCommand_N64(romBase, 0x10);
// Read the status register
setAddress_N64(romBase);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(romBase);
statusReg = readWord_N64();
// Blink led
blinkLED();
delay(500);
}
}
// Common sector erase command
void eraseSector_N64(unsigned long sectorSize) {
unsigned long flashBase = romBase;
print_Msg(F("Sector erase..."));
display_Update();
for (unsigned long currSector = 0; currSector < fileSize; currSector += sectorSize) {
// Blink led
blinkLED();
// Spansion S29GL256N(32MB/64MB) with two flashrom chips
if ((currSector == 0x2000000) && (strcmp(cartID, "2201") == 0) && (flashid == 0x227E)) {
// Change to second chip
flashBase = romBase + 0x2000000;
}
// Macronix MX29LV640(8MB/16MB) with two flashrom chips
else if ((currSector == 0x800000) && ((flashid == 0x22C9) || (flashid == 0x22CB))) {
flashBase = romBase + 0x800000;
}
// Send Erase Command
sendFlashromCommand_N64(flashBase, 0x80);
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0xAA);
setAddress_N64(flashBase + (0x2AA << 1));
writeWord_N64(0x55);
setAddress_N64(romBase + currSector);
writeWord_N64(0x30);
// Read the status register
setAddress_N64(romBase + currSector);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(romBase + currSector);
statusReg = readWord_N64();
}
}
}
boolean blankcheckFlashrom_N64() {
for (unsigned long currByte = romBase; currByte < romBase + fileSize; currByte += 512) {
// Blink led
if (currByte % 131072 == 0)
blinkLED();
// Set the address
setAddress_N64(currByte);
for (int c = 0; c < 512; c += 2) {
if (readWord_N64() != 0xFFFF) {
return 0;
}
}
}
return 1;
}
// Write Intel flashrom
void writeIntel4400_N64() {
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currSector = 0; currSector < fileSize; currSector += 131072) {
// Blink led
blinkLED();
// Write to flashrom
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
// Write 32 words at a time
for (int currWriteBuffer = 0; currWriteBuffer < 512; currWriteBuffer += 64) {
// Buffered program command
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64(0xE8);
// Check Status register
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
statusReg = readWord_N64();
}
// Write word count (minus 1)
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64(0x1F);
// Write buffer
for (byte currByte = 0; currByte < 64; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currWriteBuffer + currByte] & 0xFF) << 8) | (sdBuffer[currWriteBuffer + currByte + 1] & 0xFF);
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + currByte);
writeWord_N64(currWord);
}
// Write Buffer to Flash
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 62);
writeWord_N64(0xD0);
// Read the status register at last written address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 62);
statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != 0xFFFF) {
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 62);
statusReg = readWord_N64();
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
}
}
// Write Fujitsu MSP55LV100S flashrom consisting out of two MSP55LV512 flashroms one used for the high byte the other for the low byte
void writeMSP55LV100_N64(unsigned long sectorSize) {
unsigned long flashBase = romBase;
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currSector = 0; currSector < fileSize; currSector += sectorSize) {
// Blink led
blinkLED();
// Write to flashrom
for (unsigned long currSdBuffer = 0; currSdBuffer < sectorSize; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
// Write 32 bytes at a time
for (int currWriteBuffer = 0; currWriteBuffer < 512; currWriteBuffer += 32) {
// 2 unlock commands
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0xAAAA);
setAddress_N64(flashBase + (0x2AA << 1));
writeWord_N64(0x5555);
// Write buffer load command at sector address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64(0x2525);
// Write word count (minus 1) at sector address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64(0x0F0F);
// Define variable before loop so we can use it later when reading the status register
word currWord;
for (byte currByte = 0; currByte < 32; currByte += 2) {
// Join two bytes into one word
currWord = ((sdBuffer[currWriteBuffer + currByte] & 0xFF) << 8) | (sdBuffer[currWriteBuffer + currByte + 1] & 0xFF);
// Load Buffer Words
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + currByte);
writeWord_N64(currWord);
}
// Write Buffer to Flash
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 30);
writeWord_N64(0x2929);
// Read the status register at last written address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 30);
word statusReg = readWord_N64();
while ((statusReg | 0x7F7F) != (currWord | 0x7F7F)) {
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + 30);
statusReg = readWord_N64();
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
}
}
// Write Spansion S29GL256N flashrom using the 32 byte write buffer
void writeFlashBuffer_N64(unsigned long sectorSize, byte bufferSize) {
unsigned long flashBase = romBase;
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currSector = 0; currSector < fileSize; currSector += sectorSize) {
// Blink led
blinkLED();
// Spansion S29GL256N(32MB/64MB) with two flashrom chips
if ((currSector == 0x2000000) && (strcmp(cartID, "2201") == 0)) {
flashBase = romBase + 0x2000000;
}
// Write to flashrom
for (unsigned long currSdBuffer = 0; currSdBuffer < sectorSize; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
// Write 32 bytes at a time
for (int currWriteBuffer = 0; currWriteBuffer < 512; currWriteBuffer += bufferSize) {
// 2 unlock commands
setAddress_N64(flashBase + (0x555 << 1));
writeWord_N64(0xAA);
setAddress_N64(flashBase + (0x2AA << 1));
writeWord_N64(0x55);
// Write buffer load command at sector address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64(0x25);
// Write word count (minus 1) at sector address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer);
writeWord_N64((bufferSize / 2) - 1);
// Define variable before loop so we can use it later when reading the status register
word currWord = 0;
for (byte currByte = 0; currByte < bufferSize; currByte += 2) {
// Join two bytes into one word
currWord = ((sdBuffer[currWriteBuffer + currByte] & 0xFF) << 8) | (sdBuffer[currWriteBuffer + currByte + 1] & 0xFF);
// Load Buffer Words
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + currByte);
writeWord_N64(currWord);
}
// Write Buffer to Flash
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + bufferSize - 2);
writeWord_N64(0x29);
// Read the status register at last written address
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + bufferSize - 2);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != (currWord | 0xFF7F)) {
setAddress_N64(romBase + currSector + currSdBuffer + currWriteBuffer + bufferSize - 2);
statusReg = readWord_N64();
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
}
}
// Write MX29LV640 flashrom without write buffer
void writeFlashrom_N64(unsigned long sectorSize) {
unsigned long flashBase = romBase;
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currSector = 0; currSector < fileSize; currSector += sectorSize) {
// Blink led
blinkLED();
// Macronix MX29LV640(8MB/16MB) with two flashrom chips
if (currSector == 0x800000) {
flashBase = romBase + 0x800000;
}
// Write to flashrom
for (unsigned long currSdBuffer = 0; currSdBuffer < sectorSize; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
for (int currByte = 0; currByte < 512; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// 2 unlock commands
sendFlashromCommand_N64(flashBase, 0xA0);
// Write word
setAddress_N64(romBase + currSector + currSdBuffer + currByte);
writeWord_N64(currWord);
// Read the status register
setAddress_N64(romBase + currSector + currSdBuffer + currByte);
word statusReg = readWord_N64();
while ((statusReg | 0xFF7F) != (currWord | 0xFF7F)) {
setAddress_N64(romBase + currSector + currSdBuffer + currByte);
statusReg = readWord_N64();
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
}
}
unsigned long verifyFlashrom_N64() {
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
writeErrors = 0;
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currSector = 0; currSector < fileSize; currSector += 131072) {
// Blink led
blinkLED();
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
for (int currByte = 0; currByte < 512; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Read flash
setAddress_N64(romBase + currSector + currSdBuffer + currByte);
// Compare both
if (readWord_N64() != currWord) {
writeErrors++;
// Abord if too many errors
if (writeErrors > 20) {
print_Msg(F("More than "));
// Close the file:
myFile.close();
return writeErrors;
}
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
}
}
// Close the file:
myFile.close();
return writeErrors;
} else {
print_STR(open_file_STR, 1);
display_Update();
return 9999;
}
}
#endif
/******************************************
N64 Gameshark Flash Functions
*****************************************/
void sendFlashromGamesharkCommand_N64(uint16_t cmd) {
setAddress_N64(0x1EF0AAA8);
writeWord_N64(0xAAAA);
setAddress_N64(0x1EE05554);
writeWord_N64(0x5555);
setAddress_N64(0x1EF0AAA8);
writeWord_N64(cmd);
}
void flashGameshark_N64() {
// Check flashrom ID's
unlockGSAddressRanges();
idGameshark_N64();
// Check for SST 29LE010 (0808)/SST 28LF040 (0404)/AMTEL AT29LV010A (3535)/SST 29EE010 (0707)
// !!!! This has been confirmed to allow reading of v1.02, v1.04-v1.09, v2.0-2.21, v3.0-3.3 !!!!
// !!!! All referenced eeproms/flashroms are confirmed as being writable with this process. !!!!
// !!!! !!!!
// !!!! PROCEED AT YOUR OWN RISK !!!!
// !!!! !!!!
// !!!! SST 29EE010 may have a 5V requirement for writing however dumping works at 3V. As such it is not !!!!
// !!!! advised to write to a cart with this chip until further testing can be completed. !!!!
if (flashid == 0x0808 || flashid == 0x0404 || flashid == 0x3535 || flashid == 0x0707) {
backupGameshark_N64();
println_Msg("");
println_Msg(F("This will erase your"));
println_Msg(F("Gameshark cartridge"));
println_Msg(F("Attention: Use 3.3V!"));
println_Msg(F("Power OFF if Unsure!"));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
// Launch file browser
filePath[0] = '\0';
sd.chdir("/");
fileBrowser(F("Select z64 file"));
display_Update();
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
// Get rom size from file
fileSize = myFile.fileSize();
display_Clear();
print_Msg(F("File size: "));
print_Msg(fileSize / 1024);
println_Msg(F(" KB"));
display_Update();
// Compare file size to flashrom size for 1 Mbit eeproms
if (fileSize > 262144 && (flashid == 0x0808 || flashid == 0x3535 || flashid == 0x0707)) {
print_FatalError(file_too_big_STR);
}
// Compare file size to flashrom size for 1 Mbit eeproms
if (fileSize > 1048576 && flashid == 0x0404) {
print_FatalError(file_too_big_STR);
}
// SST 29LE010, chip erase not needed as this eeprom automaticly erases during the write cycle
eraseGameshark_N64();
blankCheck_N64();
// Write flashrom
print_Msg(F("Writing "));
println_Msg(filePath);
display_Update();
writeGameshark_N64();
// Close the file:
myFile.close();
// Verify
print_STR(verifying_STR, 0);
display_Update();
writeErrors = verifyGameshark_N64();
if (writeErrors == 0) {
display_Clear();
display_Update();
println_Msg(F("Verfied OK"));
println_Msg(FS(FSTRING_EMPTY));
println_Msg(F("Turn Cart Reader off now"));
display_Update();
while (1)
;
} else {
display_Clear();
display_Update();
println_Msg(F("Verification Failed"));
println_Msg(writeErrors);
print_Msg(F(" bytes "));
print_Error(did_not_verify_STR);
}
} else {
print_Error(open_file_STR);
}
}
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
display_Clear();
display_Update();
}
void unlockGSAddressRanges() {
// This enables using the 0x1EEx_xxxx, 0x1EFx_xxxx, and 0x1ECx_xxxx address ranges, necessary for writing to all supported chips
setAddress_N64(0x10400400);
writeWord_N64(0x1E);
writeWord_N64(0x1E);
}
//Test for SST 29LE010 or SST 28LF040 (0404) or AMTEL AT29LV010A (3535) or SST 29EE010 (0707)
void idGameshark_N64() {
flashid = 0x0;
//Send flashrom ID command
sendFlashromGamesharkCommand_N64(0x9090);
setAddress_N64(0x1EC00000);
// Read 1 byte vendor ID
readWord_N64();
// Read 2 bytes flashrom ID
flashid = readWord_N64();
if (flashid == 0x0808 || flashid == 0x3535 || flashid == 0x0707) {
flashSize = 262144;
} else if (flashid == 0x0404) {
//Set SST 28LF040 flashrom size
flashSize = 1048574;
} else {
println_Msg(F("Check cart connection"));
println_Msg(F("Unknown Flash ID"));
sprintf(flashid_str, "%04X", flashid);
print_STR(press_button_STR, 1);
display_Update();
wait();
mainMenu();
}
sprintf(flashid_str, "%04X", flashid);
// Reset flashrom
resetGameshark_N64();
}
void resetGameshark_N64() {
if (flashid == 0x0808 || flashid == 0x3535 || flashid == 0x0707) {
// Send reset command for SST 29LE010 / AMTEL AT29LV010A / SST 29EE010
sendFlashromGamesharkCommand_N64(0xF0F0);
delay(100);
} else if (flashid == 0x0404) {
// Send reset command for SST 28LF040
sendFlashromGamesharkCommand_N64(0xFFFF);
delay(300);
}
}
// Read rom and save to the SD card
void backupGameshark_N64() {
createFolderAndOpenFile("N64", "ROM", "GameShark", "z64");
for (unsigned long currByte = romBase + 0xEC00000; currByte < (romBase + 0xEC00000 + flashSize); currByte += 512) {
// Blink led
if (currByte % 16384 == 0)
blinkLED();
// Set the address for the next 512 bytes
setAddress_N64(currByte);
for (int c = 0; c < 512; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
myFile.write(sdBuffer, 512);
}
// Close the file:
myFile.close();
}
void eraseGameshark_N64() {
println_Msg(F("Erasing..."));
display_Update();
// Send chip erase to SST 29LE010 / AMTEL AT29LV010A / SST 29EE010
if (flashid == 0x0808 || flashid == 0x3535 || flashid == 0x0707) {
sendFlashromGamesharkCommand_N64(0x8080);
sendFlashromGamesharkCommand_N64(0x1010);
delay(20);
}
if (flashid == 0x0404) {
//Unprotect flash
setAddress_N64(0x1EF03044);
readWord_N64();
setAddress_N64(0x1EE03040);
readWord_N64();
setAddress_N64(0x1EE03044);
readWord_N64();
setAddress_N64(0x1EE00830);
readWord_N64();
setAddress_N64(0x1EF00834);
readWord_N64();
setAddress_N64(0x1EF00830);
readWord_N64();
setAddress_N64(0x1EE00834);
readWord_N64();
delay(1000);
//Erase flash
sendFlashromGamesharkCommand_N64(0x3030);
setAddress_N64(0x1EF0AAA8);
writeWord_N64(0x3030);
delay(1000);
}
}
void blankCheck_N64() {
// Blankcheck
println_Msg(F("Blankcheck..."));
display_Update();
for (unsigned long currSector = 0; currSector < flashSize; currSector += 131072) {
// Blink led
blinkLED();
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
for (int currByte = 0; currByte < 512; currByte += 2) {
// Read flash
setAddress_N64(romBase + 0xEC00000 + currSector + currSdBuffer + currByte);
// Compare both
if (readWord_N64() != 0xFFFF) {
println_Msg(F("Not empty"));
print_FatalError(F("Erase failed"));
}
}
}
}
}
void writeGameshark_N64() {
// Write Gameshark with 2x SST 29LE010 / AMTEL AT29LV010A / SST 29EE010 Eeproms
if (flashid == 0x0808 || flashid == 0x3535 || flashid == 0x0707) {
// Each 29LE010 has 1024 pages, each 128 bytes in size
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
myFile.seek(0);
for (unsigned long currPage = 0; currPage < fileSize / 2; currPage += 128) {
// Fill SD buffer with twice the amount since we flash 2 chips
myFile.read(sdBuffer, 256);
//Send page write command to both flashroms
sendFlashromGamesharkCommand_N64(0xA0A0);
// Write 1 page each, one flashrom gets the low byte, the other the high byte.
for (unsigned long currByte = 0; currByte < 256; currByte += 2) {
// Set address
setAddress_N64(romBase + 0xEC00000 + (currPage * 2) + currByte);
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Send byte data
writeWord_N64(currWord);
}
processedProgressBar += 256;
draw_progressbar(processedProgressBar, totalProgressBar);
blinkLED();
delay(30);
}
}
if (flashid == 0x0404) {
// Write Gameshark with 2x SST 28LF040
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
myFile.seek(0);
for (unsigned long currSector = 0; currSector < fileSize; currSector += 16384) {
for (unsigned long currSdBuffer = 0; currSdBuffer < 16384; currSdBuffer += 256) {
// Fill SD buffer
myFile.read(sdBuffer, 256);
for (unsigned long currByte = 0; currByte < 256; currByte += 2) {
// Send byte program command
sendFlashromGamesharkCommand_N64(0x1010);
// Set address
setAddress_N64(romBase + 0xEC00000 + currSector + currSdBuffer + currByte);
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Send byte data
writeWord_N64(currWord);
delayMicroseconds(60);
}
processedProgressBar += 256;
draw_progressbar(processedProgressBar, totalProgressBar);
blinkLED();
}
}
//Protect flash
setAddress_N64(0x1EF03044);
readWord_N64();
setAddress_N64(0x1EE03040);
readWord_N64();
setAddress_N64(0x1EE03044);
readWord_N64();
setAddress_N64(0x1EE00830);
readWord_N64();
setAddress_N64(0x1EF00834);
readWord_N64();
setAddress_N64(0x1EF00830);
readWord_N64();
setAddress_N64(0x1EE00814);
readWord_N64();
delay(1000);
}
}
unsigned long verifyGameshark_N64() {
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
println_Msg(FS(FSTRING_EMPTY));
draw_progressbar(0, totalProgressBar);
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
writeErrors = 0;
for (unsigned long currSector = 0; currSector < fileSize; currSector += 131072) {
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
for (int currByte = 0; currByte < 512; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Read flash
setAddress_N64(romBase + 0xEC00000 + currSector + currSdBuffer + currByte);
// Compare both
if (readWord_N64() != currWord) {
writeErrors++;
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
blinkLED();
}
}
// Close the file:
myFile.close();
return writeErrors;
} else {
print_STR(open_file_STR, 1);
display_Update();
return 9999;
}
}
/******************************************
XPLORER 64 Functions
*****************************************/
void sendFlashromXplorerCommand_N64(uint16_t cmd) {
oddXPaddrWrite(0x1040AAAA, 0xAAAA);
evenXPaddrWrite(0x10405555, 0x5555);
oddXPaddrWrite(0x1040AAAA, cmd);
}
void flashXplorer_N64() {
// Check flashrom ID's
idXplorer_N64();
if (flashid == 0x0808) {
backupXplorer_N64();
println_Msg("");
println_Msg(F("This will erase your"));
println_Msg(F("Xplorer64 cartridge"));
println_Msg(F("Attention: Use 3.3V!"));
println_Msg(F("Power OFF if Unsure!"));
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
// Launch file browser
filePath[0] = '\0';
sd.chdir("/");
fileBrowser(F("Select XP64 rom file"));
display_Update();
// Create filepath
sprintf(filePath, "%s/%s", filePath, fileName);
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
// Get rom size from file
fileSize = myFile.fileSize();
display_Clear();
print_Msg(F("File size: "));
print_Msg(fileSize / 1024);
println_Msg(F(" KB"));
display_Update();
// Compare file size to flashrom size
if (fileSize > 262144) {
print_FatalError(file_too_big_STR);
}
// SST 29LE010, chip erase not needed as this eeprom automaticly erases during the write cycle
eraseXplorer_N64();
blankCheck_XP64();
// Write flashrom
display_Clear();
print_Msg(F("Writing "));
println_Msg(filePath);
display_Update();
writeXplorer_N64();
// Close the file:
myFile.close();
// Verify
print_STR(verifying_STR, 0);
display_Update();
writeErrors = verifyXplorer_N64();
if (writeErrors == 0) {
display_Clear();
display_Update();
println_Msg(F("Verfied OK"));
println_Msg(FS(FSTRING_EMPTY));
println_Msg(F("Turn Cart Reader off now"));
display_Update();
while (1)
;
} else {
display_Clear();
display_Update();
println_Msg(F("Verification Failed"));
println_Msg(writeErrors);
print_Msg(F(" bytes "));
print_Error(did_not_verify_STR);
}
} else {
print_Error(open_file_STR);
}
}
// Prints string out of the common strings array either with or without newline
print_STR(press_button_STR, 1);
display_Update();
wait();
display_Clear();
display_Update();
}
//Test for SST 29LE010
void idXplorer_N64() {
flashid = 0x0;
//Send flashrom ID command
sendFlashromXplorerCommand_N64(0x9090);
setAddress_N64(0x10760000);
readWord_N64();
setAddress_N64(0x10400D88);
flashid = readWord_N64();
setAddress_N64(0x10740000);
readWord_N64();
if (flashid != 0x0808) {
println_Msg(F("Check cart connection"));
println_Msg(F("Unknown Flash ID"));
sprintf(flashid_str, "%04X", flashid);
print_STR(press_button_STR, 1);
display_Update();
wait();
mainMenu();
}
sprintf(flashid_str, "%04X", flashid);
// Reset flashrom
resetXplorer_N64();
}
void resetXplorer_N64() {
// Send reset command for SST 29LE010
sendFlashromXplorerCommand_N64(0xF0F0);
delay(100);
}
// Read rom and save to the SD card
void backupXplorer_N64() {
// create a new folder
createFolderAndOpenFile("N64", "ROM", "XPLORER64", "z64");
for (unsigned long currByte = 0x10400000; currByte <= 0x1043FFFF; currByte += 512) {
// Blink led
if (currByte % 16384 == 0)
blinkLED();
// Set the address for the next 512 bytes
setAddress_N64(currByte);
for (int c = 0; c < 512; c += 2) {
// split word
word myWord = readWord_N64();
byte loByte = myWord & 0xFF;
byte hiByte = myWord >> 8;
// write to buffer
sdBuffer[c] = hiByte;
sdBuffer[c + 1] = loByte;
}
myFile.write(sdBuffer, 512);
}
// Close the file:
myFile.close();
println_Msg(F("Done."));
}
unsigned long unscramble(unsigned long addr) {
unsigned long result = (((addr >> 4) & 0x001) | ((addr >> 8) & 0x002) | ((~addr >> 9) & 0x004) | ((addr >> 3) & 0x008) | ((addr >> 6) & 0x010) | ((addr >> 2) & 0x020) | ((~addr << 5) & 0x0C0) | ((~addr << 8) & 0x100) | ((~addr << 6) & 0x200) | ((~addr << 2) & 0x400) | ((addr << 6) & 0x800) | (addr & 0x1F000));
return result;
}
unsigned long scramble(unsigned long addr) {
unsigned long result = (((~addr >> 8) & 0x001) | ((~addr >> 5) & 0x006) | ((~addr >> 6) & 0x008) | ((addr << 4) & 0x010) | ((addr >> 6) & 0x020) | ((addr << 3) & 0x040) | ((addr << 2) & 0x080) | ((~addr >> 2) & 0x100) | ((addr << 8) & 0x200) | ((addr << 6) & 0x400) | ((~addr << 9) & 0x800) | (addr & 0x1F000));
return result;
}
void oddXPaddrWrite(unsigned long addr, word data) {
unsigned long oddAddr = (0x10400000 + ((unscramble((addr & 0xFFFFF) / 2) - 1) * 2));
setAddress_N64(0x10770000);
readWord_N64();
readWord_N64();
setAddress_N64(oddAddr);
writeWord_N64(data);
writeWord_N64(data);
setAddress_N64(0x10740000);
readWord_N64();
readWord_N64();
}
void evenXPaddrWrite(unsigned long addr, word data) {
unsigned long evenAddr = (0x10400000 + (unscramble((addr & 0xFFFFF) / 2) * 2));
setAddress_N64(0x10760000);
readWord_N64();
readWord_N64();
setAddress_N64(evenAddr);
writeWord_N64(data);
writeWord_N64(data);
setAddress_N64(0x10740000);
readWord_N64();
readWord_N64();
}
void eraseXplorer_N64() {
println_Msg(F("Erasing..."));
display_Update();
// Send chip erase to SST 29LE010
sendFlashromXplorerCommand_N64(0x8080);
sendFlashromXplorerCommand_N64(0x1010);
delay(20);
}
void blankCheck_XP64() {
// Blankcheck
println_Msg(F("Blankcheck..."));
display_Update();
for (unsigned long currSector = 0; currSector < 262144; currSector += 131072) {
// Blink led
blinkLED();
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
for (int currByte = 0; currByte < 512; currByte += 2) {
// Read flash
setAddress_N64(0x10400000 + currSector + currSdBuffer + currByte);
// Compare both
if (readWord_N64() != 0xFFFF) {
println_Msg(F("Not empty"));
print_FatalError(F("Erase failed"));
}
}
}
}
}
void writeXplorer_N64() {
// Write Xplorer64 with 2x SST 29LE010
// Each 29LE010 has 1024 pages, each 128 bytes in size
//Initialize progress bar
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(fileSize);
draw_progressbar(0, totalProgressBar);
for (unsigned long currPage = 0; currPage < fileSize / 2; currPage += 128) {
// Fill SD buffer with data in the order it will be expected by the CPLD
for (unsigned long i = 0; i < 256; i += 2) {
unsigned long unscrambled_address = (unscramble(((currPage * 2) + i) / 2) * 2);
myFile.seek(unscrambled_address);
myFile.read(&sdBuffer[i], 1);
myFile.seek(unscrambled_address + 1);
myFile.read(&sdBuffer[i + 1], 1);
}
//Send page write command to both flashroms
sendFlashromXplorerCommand_N64(0xA0A0);
// Write 1 page each, one flashrom gets the low byte, the other the high byte.
for (unsigned long currByte = 0; currByte < 256; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Set address
if ((((currByte / 2) >> 4) & 0x1) == 0) {
evenXPaddrWrite(0x10400000 + (currPage * 2) + currByte, currWord);
} else {
oddXPaddrWrite(0x10400000 + (currPage * 2) + currByte, currWord);
}
}
processedProgressBar += 256;
draw_progressbar(processedProgressBar, totalProgressBar);
blinkLED();
}
}
unsigned long verifyXplorer_N64() {
uint32_t processedProgressBar = 0;
uint32_t totalProgressBar = (uint32_t)(262144);
println_Msg(FS(FSTRING_EMPTY));
draw_progressbar(0, totalProgressBar);
// Open file on sd card
if (myFile.open(filePath, O_READ)) {
myFile.seek(0);
writeErrors = 0;
for (unsigned long currSector = 0; currSector < 262144; currSector += 131072) {
for (unsigned long currSdBuffer = 0; currSdBuffer < 131072; currSdBuffer += 512) {
// Fill SD buffer
myFile.read(sdBuffer, 512);
for (int currByte = 0; currByte < 512; currByte += 2) {
// Join two bytes into one word
word currWord = ((sdBuffer[currByte] & 0xFF) << 8) | (sdBuffer[currByte + 1] & 0xFF);
// Read flash
setAddress_N64(romBase + 0x400000 + currSector + currSdBuffer + currByte);
// Compare both
if (readWord_N64() != currWord) {
writeErrors++;
}
}
processedProgressBar += 512;
draw_progressbar(processedProgressBar, totalProgressBar);
blinkLED();
}
}
// Close the file:
myFile.close();
return writeErrors;
} else {
print_STR(open_file_STR, 1);
display_Update();
return 9999;
}
}
#endif
//******************************************
// End of File
//******************************************
|