-
Notifications
You must be signed in to change notification settings - Fork 224
/
N64.ino
4728 lines (4111 loc) · 141 KB
/
N64.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//******************************************
// 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");