/
Pic17Utils.pas
2087 lines (2076 loc) · 67 KB
/
Pic17Utils.pas
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
{
Description
===========
Utilities for programming Mid-range PIC microcontrollers with 14 bits instructions
of the family Enhanced Mid-range. Include most of the PIC16F1 devices.
This unit works with 2K words pages and 128 bytes RAM banks.
The main class TPIC16 must model all devices of this family, including the most complex.
The aim of this unit is to be used as base for assemblers, compilers and simulators.
Created by Tito Hinostroza 26/07/2015
}
unit Pic17Utils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LCLProc, PicCore;
type //Mid-range PIC instructions
TPIC17Inst = (
//BYTE-ORIENTED FILE REGISTER OPERATIONS
i_ADDWF,
i_ANDWF,
i_CLRF,
i_CLRW,
i_COMF ,
i_DECF ,
i_DECFSZ,
i_INCF,
i_INCFSZ,
i_IORWF,
i_MOVF,
i_MOVWF,
i_NOP,
i_RLF,
i_RRF,
i_SUBWF,
i_SWAPF,
i_XORWF,
//BIT-ORIENTED FILE REGISTER OPERATIONS
i_BCF,
i_BSF,
i_BTFSC,
i_BTFSS,
//LITERAL AND CONTROL OPERATIONS
i_ADDLW,
i_ANDLW,
i_CALL,
i_CLRWDT,
i_GOTO,
i_IORLW,
i_MOVLW,
i_RETFIE,
i_RETLW,
i_RETURN,
i_SLEEP,
i_SUBLW,
i_XORLW,
//NEW INSTRUCTIONS
i_ADDWFC,
i_SUBWFB,
i_LSLF,
i_LSRF,
i_ASRF,
i_MOVLP,
i_MOVLB,
i_BRA,
i_BRW,
i_CALLW,
i_ADDFSR,
i_MOVIW,
i_MOVIWk, //Syntax of MOVIW that use a constant "k"
i_MOVWI,
i_MOVWIk, //Syntax of MOVWI that use a constant "k"
i_RESET,
//INVALID INSTRUCTION
i_Inval
{It's not clear for me if TRIS and OTPION instructions are still
supported in this family.}
);
//Destination of the instrucction
TPIC17destin = (
toW = %00000000, //al acumulador
toF = %10000000 //a memoria
);
//Select the FSR
TPIC17fsr = (
toFSR0 = %0000000, //FSR0
toFSR1 = %1000000 //FSR1
);
TPIC17fsrShort = (
toFSR0s = %000, //FSR0
toFSR1s = %100 //FSR1
);
const //Constants of address and bit positions for some registers
_INDF0 = $00;
_INDF1 = $01;
_PCL = $02;
_STATUS = $03;
_FSR0L = $04;
_FSR0H = $05;
_FSR1L = $06;
_FSR1H = $07;
_BSR = $08;
_WREG = $09;
_PCLATH = $0A;
_INTCON = $0B;
_C = 0;
_Z = 2;
type
{Objeto que representa al hardware de un PIC de la serie 16}
{ TPIC17 }
TPIC17 = class(TPicCore)
public //Fields to proccess instructions
idIns: TPIC17Inst; //ID de Instrucción.
d_ : TPIC17destin; //Destino de operación. Válido solo en algunas instrucciones.
f_ : byte; //Registro destino. Válido solo en algunas instrucciones.
b_ : byte; //Bit destino. Válido solo en algunas instrucciones.
k_ : word; //Parámetro Literal. Válido solo en algunas instrucciones.
n_ : byte; //Indicates the FSR register. Valid only for some instructions.
m_ : byte; //Indicates the increment/decrement. Valid only for some instructions.
private //Campos para procesar instrucciones
function GetBank(i : Longint): TPICRAMBank;
function GetINTCON: byte;
function GetINTCON_GIE: boolean;
function GetPage(i : Longint): TPICFlashPage;
function GetSTATUS: byte;
function GetSTATUS_C: boolean;
function GetSTATUS_DC: boolean;
function GetSTATUS_IRP: boolean;
function GetSTATUS_Z: boolean;
procedure SetINTCON_GIE(AValue: boolean);
procedure SetSTATUS_C(AValue: boolean);
procedure SetSTATUS_DC(AValue: boolean);
procedure SetSTATUS_IRP(AValue: boolean);
procedure SetSTATUS_Z(AValue: boolean);
procedure SetFRAM(value: byte);
function GetFRAM: byte;
public //Campos que modelan a los registros internos
W : byte; //Registro de trabajo
PC : TWordRec; //PC as record to fast access for bytes
//PCLATH : byte; //Contador de Programa H
STKPTR : 0..15; //Puntero de pila
STACK : array[0..15] of word;
property STATUS: byte read GetSTATUS;
property STATUS_Z: boolean read GetSTATUS_Z write SetSTATUS_Z;
property STATUS_C: boolean read GetSTATUS_C write SetSTATUS_C;
property STATUS_DC: boolean read GetSTATUS_DC write SetSTATUS_DC;
property STATUS_IRP: boolean read GetSTATUS_IRP write SetSTATUS_IRP;
property INTCON: byte read GetINTCON;
property INTCON_GIE: boolean read GetINTCON_GIE write SetINTCON_GIE;
property FRAM: byte read GetFRAM write SetFRAM;
public //Execution control
function CurInstruction: TPIC17Inst;
procedure Exec(aPC: word); override; //Ejecuta la instrucción en la dirección indicada.
procedure Exec; override; //Ejecuta instrucción actual
procedure ExecTo(endAdd: word); override; //Ejecuta hasta cierta dirección
procedure ExecStep; override; //Execute one instruction considering CALL as one instruction
procedure ExecNCycles(nCyc: integer; out stopped: boolean); override; //Ejecuta hasta cierta dirección
procedure Reset; override;
function ReadPC: dword; override;
procedure WritePC(AValue: dword); override;
public //Memories
procedure Decode(const opCode: word); //decodifica instrucción
function Disassembler(const opCode: word; bankNum: byte = 255;
useVarName: boolean = false): string; //Desensambla la instrucción actual
function DisassemblerAt(addr: word; useVarName: boolean = false): string; override;
property banks[i : Longint]: TPICRAMBank Read GetBank;
property pages[i : Longint]: TPICFlashPage Read GetPage;
public //RAM memory functions
function GetFreeBit(out addr: word; out bit: byte; shared: boolean): boolean;
function GetFreeByte(out addr: word; shared: boolean): boolean;
function GetFreeBytes(const size: integer; var addr: word): boolean; //obtiene una dirección libre
function TotalMemRAM: word; //devuelve el total de memoria RAM
function UsedMemRAM: word; //devuelve el total de memoria RAM usada
procedure ExploreUsed(rutExplorRAM: TPICRutExplorRAM); //devuelve un reporte del uso de la RAM
function ValidRAMaddr(addr: word): boolean; //indica si una posición de memoria es válida
function BankToAbsRAM(const offset, bank: byte): word; //devuelve dirección absoluta
procedure AbsToBankRAM(const AbsAddr: word; var offset, bank: byte); //convierte dirección absoluta
public //Métodos para codificar instrucciones de acuerdo a la sintaxis
procedure useFlash;
procedure codAsmFD(const inst: TPIC17Inst; const f: word; d: TPIC17destin);
procedure codAsmF(const inst: TPIC17Inst; const f: word);
procedure codAsmFB(const inst: TPIC17Inst; const f: word; b: byte);
procedure codAsmK(const inst: TPIC17Inst; const k: byte);
procedure codAsmA(const inst: TPIC17Inst; const a: word);
procedure codAsmNK(const inst: TPIC17Inst; const n: TPIC17fsr; k: byte);
procedure codAsmNM(const inst: TPIC17Inst; const n: TPIC17fsrShort; m: byte);
procedure codAsm(const inst: TPIC17Inst);
procedure codGotoAt(iflash0: integer; const k: word);
procedure codCallAt(iflash0: integer; const k: word);
function codInsert(iflash0, nInsert, nWords: integer): boolean;
procedure BTFSC_sw_BTFSS(iflash0: integer);
public //Métodos adicionales
function FindOpcode(Op: string; out syntax: string): TPIC17Inst; //busca Opcode
procedure GenHex(hexFile: string; ConfigWord: integer = - 1); //genera un archivo hex
procedure DumpCode(lOut: TStrings; incAdrr, incCom, incVarNam: boolean); //vuelva en código que contiene
public //Initialization
constructor Create; override;
destructor Destroy; override;
end;
var //variables globales
//mnemónico de las instrucciones
PIC17InstName: array[low(TPIC17Inst)..high(TPIC17Inst)] of string[7];
//sintaxis en ensamblador de las instrucciones
PIC17InstSyntax: array[low(TPIC17Inst)..high(TPIC17Inst)] of string[5];
implementation
{ TPIC17 }
procedure TPIC17.useFlash;
{Marca la posición actual, como usada, e incrementa el puntero iFlash. S ihay error,
actualiza el campo "MsjError"}
begin
//Protección de desborde
if iFlash >= MaxFlash then begin
MsjError := 'FLASH Memory limit exceeded.';
exit;
end;
flash[iFlash].used := true; //marca como usado
inc(iFlash);
end;
procedure TPIC17.codAsmFD(const inst: TPIC17Inst; const f: word; d: TPIC17destin);
{Codifica las instrucciones orientadas a registro, con sinatxis: NEMÓNICO f,d}
begin
case inst of
i_ADDWF : flash[iFlash].value := %00011100000000 + ord(d) + (f and %1111111);
i_ADDWFC: flash[iFlash].value := %11110100000000 + ord(d) + (f and %1111111);
i_ANDWF : flash[iFlash].value := %00010100000000 + ord(d) + (f and %1111111);
i_ASRF : flash[iFlash].value := %11011100000000 + ord(d) + (f and %1111111);
i_LSLF : flash[iFlash].value := %11010100000000 + ord(d) + (f and %1111111);
i_LSRF : flash[iFlash].value := %11011000000000 + ord(d) + (f and %1111111);
i_COMF : flash[iFlash].value := %00100100000000 + ord(d) + (f and %1111111);
i_DECF : flash[iFlash].value := %00001100000000 + ord(d) + (f and %1111111);
i_INCF : flash[iFlash].value := %00101000000000 + ord(d) + (f and %1111111);
i_DECFSZ: flash[iFlash].value := %00101100000000 + ord(d) + (f and %1111111);
i_INCFSZ: flash[iFlash].value := %00111100000000 + ord(d) + (f and %1111111);
i_IORWF : flash[iFlash].value := %00010000000000 + ord(d) + (f and %1111111);
i_MOVF : flash[iFlash].value := %00100000000000 + ord(d) + (f and %1111111);
i_RLF : flash[iFlash].value := %00110100000000 + ord(d) + (f and %1111111);
i_RRF : flash[iFlash].value := %00110000000000 + ord(d) + (f and %1111111);
i_SUBWF : flash[iFlash].value := %00001000000000 + ord(d) + (f and %1111111);
i_SUBWFB: flash[iFlash].value := %11101100000000 + ord(d) + (f and %1111111);
i_SWAPF : flash[iFlash].value := %00111000000000 + ord(d) + (f and %1111111);
i_XORWF : flash[iFlash].value := %00011000000000 + ord(d) + (f and %1111111);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmF(const inst: TPIC17Inst; const f: word);
{Codifica las instrucciones orientadas a registro, con sinatxis: NEMÓNICO f}
begin
case inst of
i_CLRF : flash[iFlash].value := %00000110000000 + (f and %1111111);
i_MOVWF : flash[iFlash].value := %00000010000000 + (f and %1111111);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmFB(const inst: TPIC17Inst; const f: word; b: byte);
//Codifica las instrucciones orientadas a bit.
begin
case inst of
i_BCF : flash[iFlash].value := %01000000000000 + word(b<<7) + (f and %1111111);
i_BSF : flash[iFlash].value := %01010000000000 + word(b<<7) + (f and %1111111);
i_BTFSC: flash[iFlash].value := %01100000000000 + word(b<<7) + (f and %1111111);
i_BTFSS: flash[iFlash].value := %01110000000000 + word(b<<7) + (f and %1111111);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmK(const inst: TPIC17Inst; const k: byte);
{Codifica las instrucciones con constantes.}
begin
case inst of
i_ADDLW : flash[iFlash].value := %11111000000000 + k;
i_ANDLW : flash[iFlash].value := %11100100000000 + k;
i_IORLW : flash[iFlash].value := %11100000000000 + k;
i_MOVLB : flash[iFlash].value := %00000000100000 + (k and %11111);
i_MOVLP : flash[iFlash].value := %11000110000000 + (k and %1111111);
i_MOVLW : flash[iFlash].value := %11000000000000 + k;
i_RETLW : flash[iFlash].value := %11010000000000 + k;
i_SUBLW : flash[iFlash].value := %11110000000000 + k;
i_XORLW : flash[iFlash].value := %11101000000000 + k;
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmA(const inst: TPIC17Inst; const a: word);
{Codifica las instrucciones de control.
"a" debe ser word, porque la dirección destino, requiere 11 bits.}
begin
case inst of
i_CALL : flash[iFlash].value := %10000000000000 + (a and %11111111111);
i_GOTO : flash[iFlash].value := %10100000000000 + (a and %11111111111);
i_BRA : flash[iFlash].value := %11001000000000 + (a and %111111111);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmNK(const inst: TPIC17Inst; const n: TPIC17fsr; k: byte);
{Codifica las instrucciones de tipo n,k.
"n" solo puede ser 0 o 1.}
begin
case inst of
i_ADDFSR: flash[iFlash].value := %11000100000000 + ord(n) + (k and %111111);
i_MOVIWk: flash[iFlash].value := %11111100000000 + ord(n) + (k and %111111);
i_MOVWIk: flash[iFlash].value := %11111110000000 + ord(n) + (k and %111111);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsmNM(const inst: TPIC17Inst; const n: TPIC17fsrShort; m: byte);
{Codifica las instrucciones de tipo n,m.}
begin
case inst of
i_MOVIW: flash[iFlash].value := %00000000010000 + ord(n) + (m and %11);
i_MOVWI: flash[iFlash].value := %00000000011000 + ord(n) + (m and %11);
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codAsm(const inst: TPIC17Inst);
//Codifica las instrucciones de control.
begin
case inst of
i_CLRW : flash[iFlash].value := %00000100000000;
i_NOP : flash[iFlash].value := %00000000000000;
i_CLRWDT: flash[iFlash].value := %00000001100100;
i_RETFIE: flash[iFlash].value := %00000000001001;
i_RETURN: flash[iFlash].value := %00000000001000;
i_SLEEP : flash[iFlash].value := %00000001100011;
i_BRW : flash[iFlash].value := %00000000001011;
i_CALLW : flash[iFlash].value := %00000000001010;
i_RESET : flash[iFlash].value := %00000000000001;
else
raise Exception.Create('Implementation Error.');
end;
useFlash; //marca como usado e incrementa puntero.
end;
procedure TPIC17.codGotoAt(iflash0: integer; const k: word);
{Codifica una instrucción GOTO, en una posición específica y sin alterar el puntero "iFlash"
actual. Se usa para completar saltos indefinidos}
begin
flash[iFlash0].value := %10100000000000 + (k and %11111111111);
end;
procedure TPIC17.codCallAt(iflash0: integer; const k: word);
{Codifica una instrucción i_CALL, en una posición específica y sin alterar el puntero "iFlash"
actual. Se usa para completar llamadas indefinidas}
begin
flash[iFlash0].value := %10000000000000 + (k and %11111111111);
end;
function TPIC17.codInsert(iflash0, nInsert, nWords: integer): boolean;
{Inserta en la posición iflash0, "nInsert" palabras, desplazando "nWords" palabras.
Al final debe quedar "nInsert" palabras de espacio libre en iflash0.
Si hay error devuelve FALSE.}
var
i: Integer;
begin
Result := True; //By default
if iFlash+nInsert+nWords-1> MaxFlash then begin
//Overflow on address
exit(false);
end;
for i:= iflash + nInsert + nWords -1 downto iFlash + nWords do begin
flash[i] := flash[i-nInsert];
end;
end;
procedure TPIC17.BTFSC_sw_BTFSS(iflash0: integer);
{Exchange instruction i_BTFSC to i_BTFSS, or viceversa, in the specified address.}
begin
//Solo necesita cambiar el bit apropiado
flash[iFlash0].value := flash[iFlash0].value XOR %10000000000;
end;
function TPIC17.FindOpcode(Op: string; out syntax: string): TPIC17Inst;
{Busca una cádena que represente a una instrucción (Opcode). Si encuentra devuelve
el identificador de instrucción y una cadena que representa a la sintaxis en "syntax".
Si no encuentra devuelve "i_Inval". }
var
idInst: TPIC17Inst;
tmp: String;
found: Boolean;
begin
found := false;
tmp := UpperCase(Op);
for idInst := low(TPIC17Inst) to high(TPIC17Inst) do begin
if PIC17InstName[idInst] = tmp then begin
found := true;
break;
end;
end;
if found then begin
Result := idInst;
syntax := PIC17InstSyntax[idInst];
end else begin
Result := i_Inval;
end;
end;
//Campos para procesar instrucciones
function TPIC17.GetBank(i : Longint): TPICRAMBank;
begin
Result.AddrStart := i*PICBANKSIZE;
Result.AddrEnd := (i+1)*PICBANKSIZE-1;
end;
function TPIC17.GetPage(i: Longint): TPICFlashPage;
begin
Result.AddrStart := i*PICPAGESIZE;
Result.AddrEnd := (i+1)*PICPAGESIZE-1;
end;
function TPIC17.GetSTATUS: byte;
begin
Result := ram[_STATUS].dvalue;
end;
function TPIC17.GetSTATUS_Z: boolean;
begin
Result := (ram[_STATUS].dvalue and %00000100) <> 0;
end;
procedure TPIC17.SetSTATUS_Z(AValue: boolean);
begin
if AVAlue then ram[_STATUS].dvalue := ram[_STATUS].dvalue or %00000100
else ram[_STATUS].dvalue := ram[_STATUS].dvalue and %11111011;
end;
function TPIC17.GetSTATUS_C: boolean;
begin
Result := (ram[_STATUS].dvalue and %00000001) <> 0;
end;
procedure TPIC17.SetSTATUS_C(AValue: boolean);
begin
if AVAlue then ram[_STATUS].dvalue := ram[_STATUS].dvalue or %00000001
else ram[_STATUS].dvalue := ram[_STATUS].dvalue and %11111110;
end;
function TPIC17.GetSTATUS_DC: boolean;
begin
Result := (ram[_STATUS].dvalue and %00000010) <> 0;
end;
procedure TPIC17.SetSTATUS_DC(AValue: boolean);
begin
if AVAlue then ram[_STATUS].dvalue := ram[_STATUS].dvalue or %00000010
else ram[_STATUS].dvalue := ram[_STATUS].dvalue and %11111101;
end;
function TPIC17.GetSTATUS_IRP: boolean;
begin
Result := (ram[_STATUS].dvalue and %10000000) <> 0;
end;
procedure TPIC17.SetSTATUS_IRP(AValue: boolean);
begin
if AVAlue then ram[_STATUS].dvalue := ram[_STATUS].dvalue or %10000000
else ram[_STATUS].dvalue := ram[_STATUS].dvalue and %01111111;
end;
function TPIC17.GetINTCON: byte;
begin
Result := ram[$0B].dvalue;
end;
function TPIC17.GetINTCON_GIE: boolean;
begin
Result := (ram[$0B].dvalue and %10000000) <> 0;
end;
procedure TPIC17.SetINTCON_GIE(AValue: boolean);
begin
if AVAlue then ram[$0B].dvalue := ram[$0B].dvalue or %10000000
else ram[$0B].dvalue := ram[$0B].dvalue and %01111111;
end;
procedure TPIC17.SetFRAM(value: byte);
{Escribe en la RAM; en la dirección global f_, el valor "value"
Para determinar el valor real de la dirección, se toma en cuenta los bits de STATUS}
var
pRAM : TPICRamCellPtr;
begin
if f_ = 0 then begin
//Caso especial de direccionamiento indirecto
if STATUS_IRP then begin
ram[ram[04].value + $100].value := value;
end else begin
ram[ram[04].value].value := value;
end;
exit;
end;
{Se escribe aplicando la máscara de bits implementados. Se podría usra la máscara en
lectura o escritura, pero se prefiere hacerlo en escritura, porque se espera que se
hagan menos operaciones de escritura que lectura.}
pRAM := @ram[f_+PICBANKSIZE*RAM[_BSR].dvalue];
pRAM^.value := value and pRAM^.implemAnd; // or pRAM^.implemOr; No se ha encontrado casos que requieran implemOr
{Se podría optimizar creando una constante en lugar de PICBANKSIZE y evitar así
la multiplicación. La constante puEde ser glocla, algo así como:
cons PIC_BANK_SIZE = 128 y usar luego esta constante para asiganrla a PICBANKSIZE.}
end;
function TPIC17.GetFRAM: byte;
{Devuelve el valor de la RAM, de la posición global f_.
Para determinar el valor real de la dirección, se toma en cuenta los bits de STATUS}
begin
if f_ = 0 then begin
//Caso especial de direccionamiento indirecto
if STATUS_IRP then begin
Result := ram[ram[04].value + $100].value;
end else begin
Result := ram[ram[04].value].value;
end;
exit;
end;
Result := ram[f_+PICBANKSIZE*RAM[_BSR].dvalue].value;
end;
procedure TPIC17.Decode(const opCode: word);
{Decodifica la instrucción indicada. Actualiza siempre la variable "idIns", y
dependiendo de la instrucción, puede actualizar: d_, f_, b_ y k_}
var
codH : byte; //6 bits altos de la instrucción
codL : byte; //byte bajo de la instrucción
begin
codH := (opCode and $3F00) >> 8; //se debería optimizar
codL := opCode and $00FF;
case codH of
%000111: begin
idIns := i_ADDWF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000101: begin
idIns := i_ANDWF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000001: begin
if (codL and %10000000) = %10000000 then begin
idIns := i_CLRF;
f_ := codL and %01111111;
end else begin
idIns := i_CLRW;
end;
end;
%001001: begin
idIns := i_COMF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000011: begin
idIns := i_DECF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001011: begin
idIns := i_DECFSZ;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001010: begin
idIns := i_INCF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001111: begin
idIns := i_INCFSZ;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000100: begin
idIns := i_IORWF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001000: begin
idIns := i_MOVF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000000: begin
if (codL and %10000000) = %10000000 then begin
//Bit 7 is 1
idIns := i_MOVWF;
f_ := codL and %01111111;
end else if (codL and %11100000) = %00100000 then begin
//Bit 7,6,5 = 001
idIns := i_MOVLB;
k_ := codL and %00011111;
end else if (codL and %11111000) = %00010000 then begin
//Bit 7,6,5,4,3 = 00010
idIns := i_MOVIW;
if (codL and %100) = %100 then n_:=1 else n_:=0;
m_ := codL and %11;
end else if (codL and %11111000) = %00011000 then begin
//Bit 7,6,5,4,3 = 00011
idIns := i_MOVWI;
if (codL and %100) = %100 then n_:=1 else n_:=0;
m_ := codL and %11;
end else begin
//Bit7 is 0, hay varias opciones
case codL of
%00000000,
%01000000,
%01100000: begin
idIns := i_NOP;
end;
%01100100: begin
idIns := i_CLRWDT;
end;
%00001001: begin
idIns := i_RETFIE;
end;
%00001000: begin
idIns := i_RETURN;
end;
%01100011: begin
idIns := i_SLEEP;
end;
%00001011: begin
idIns := i_BRW;
end;
%00001010: begin
idIns := i_CALLW;
end;
%00000001: begin
idIns := i_RESET;
end;
else
idIns := i_Inval;
end;
end;
end;
%001101: begin
idIns := i_RLF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001100: begin
idIns := i_RRF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000010: begin
idIns := i_SUBWF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%001110: begin
idIns := i_SWAPF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%000110: begin
idIns := i_XORWF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%111110: begin
idIns := i_ADDLW;
k_ := codL;
end;
%111111: begin
if (codL and %10000000) = %10000000 then begin
//Bit 7 is 1
idIns := i_MOVWIk;
if (codL and %1000000) = %1000000 then n_:=1 else n_:=0;
k_ := codL and %111111;
end else begin
//Bit7 is 0, hay varias opciones
idIns := i_MOVIWk;
if (codL and %1000000) = %1000000 then n_:=1 else n_:=0;
k_ := codL and %111111;
end;
end;
%111001: begin
idIns := i_ANDLW;
k_ := codL;
end;
%111000: begin
idIns := i_IORLW;
k_ := codL;
end;
%110000: begin
idIns := i_MOVLW;
k_ := codL;
end;
%110001: begin
if (codL and %10000000) <> 0 then begin
//Bit 7 is 1
idIns := i_MOVLP;
k_ := codL and %1111111;
end else begin
//Bit 7 is 0
idIns := i_ADDFSR;
if (codL and %1000000) = %1000000 then n_:=1 else n_:=0;
k_ := codL and %111111;
end;
end;
%110010: begin //Really %11001X
idIns := i_BRA;
k_ := codL;
end;
%110011: begin //Really %11001X
idIns := i_BRA;
k_ := $80+codL;
end;
%110100: begin
idIns := i_RETLW;
k_ := codL;
end;
%110101: begin
idIns := i_LSLF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%110110: begin
idIns := i_LSRF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%110111: begin
idIns := i_ASRF;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%111100: begin
idIns := i_SUBLW;
k_ := codL;
end;
%111101: begin
idIns := i_ADDWFC;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
%111010: begin
idIns := i_XORLW;
k_ := codL;
end;
%111011: begin
idIns := i_SUBWFB;
d_ := TPIC17destin(codL and %10000000);
f_ := codL and %01111111;
end;
else
if (codH and %110000) = %010000 then begin
case codH and %001100 of
%0000: begin
idIns := i_BCF;
b_ := (opCode and %1110000000) >> 7;
f_ := codL and %01111111;
end;
%0100: begin
idIns := i_BSF;
b_ := (opCode and %1110000000) >> 7;
f_ := codL and %01111111;
end;
%1000: begin
idIns := i_BTFSC;
b_ := (opCode and %1110000000) >> 7;
f_ := codL and %01111111;
end;
%1100: begin
idIns := i_BTFSS;
b_ := (opCode and %1110000000) >> 7;
f_ := codL and %01111111;
end;
else
idIns := i_Inval;
end;
end else if (codH and %111000) = %100000 then begin
idIns := i_CALL;
k_ := opCode and %11111111111;
end else if (codH and %111000) = %101000 then begin
idIns := i_GOTO;
k_ := opCode and %11111111111;
end else begin
idIns := i_Inval;
end;
end;
end;
function TPIC17.Disassembler(const opCode: word; bankNum: byte = 255;
useVarName: boolean = false): string;
{Desensambla la instrucción "opCode". Esta rutina utiliza las variables: d_, f_, b_ y k_
"opCode" -> Código de Operación que se desea decodificar. Se asuem que es de 14 bits.
"bankNum" -> Es el banco de trabajo en el que se supone se está decodificando el OpCode.
Se usa para determinar la dirección de memoria real a la que se accede
(cuando el OpCode alccede a memoria). Si no se conoce el valor, se debe
poner en 255.
"useVarName" -> Indica que se quiere usar etiquetas para los nombres de las variables
(En los Opcode que accedan a memoria). Solo es válido cuando
bankNum = 0,1,2,3 y exista un nombre asociado a la variable.
}
var
nemo: String;
f: word;
begin
Decode(opCode); //Decode instruction. Update: idIns, d_, f_, b_ and k_
nemo := lowerCase(trim(PIC17InstName[idIns])) + ' ';
case idIns of
i_ADDWF,
i_ANDWF,
i_COMF ,
i_DECF ,
i_DECFSZ,
i_INCF,
i_INCFSZ,
i_IORWF,
i_MOVF,
i_RLF,
i_RRF,
i_SUBWF,
i_SWAPF,
i_XORWF: begin
if bankNum in [0,1,2,3] then begin
//Banco conocido
f := f_ + PICBANKSIZE*bankNum; //Dirección real
end else begin
//Se asume un banco desconocido
useVarName := false; //Desactiva por si acaso
bankNum := 0; //Trabajará en este banco
f := f_; //Dirección asumida
end;
if useVarName and (ram[f].name<>'') then begin
//Required to include address name
if d_ = toF then
Result := nemo + ram[f].name + ',f'
else
Result := nemo + ram[f].name + ',w';
end else begin
//No Required to include address name
if d_ = toF then
Result := nemo + '0x'+IntToHex(f,3) + ',f'
else
Result := nemo + '0x'+IntToHex(f,3) + ',w';
end;
end;
i_CLRF,
i_MOVWF: begin
if bankNum in [0,1,2,3] then begin
//Banco conocido
f := f_ + PICBANKSIZE*bankNum; //Dirección real
end else begin
//Se asume un banco desconocido
useVarName := false; //Desactiva por si acaso
bankNum := 0; //Trabajará en este banco
f := f_; //Dirección asumida
end;
if useVarName and (ram[f].name<>'') then begin
Result := nemo + ram[f].name;
end else begin
Result := nemo + '0x'+IntToHex(f,3);
end;
end;
i_MOVLB: begin
Result := nemo + '0x'+IntToHex(k_,2);
end;
i_BCF,
i_BSF,
i_BTFSC,
i_BTFSS: begin //Instrucciones de bit
if bankNum in [0,1,2,3] then begin
//Banco conocido
f := f_ + PICBANKSIZE*bankNum; //Dirección real
end else begin
//Se asume un banco desconocido
useVarName := false; //Desactiva por si acaso
bankNum := 0; //Trabajará en este banco
f := f_; //Dirección asumida
end;
if useVarName and (ram[f].bitname[b_]<>'') then begin
//Hay nombre de bit
Result := nemo + ram[f].bitname[b_];
end else if useVarName and (ram[f].name<>'') then begin
//Hay nombre de byte
Result := nemo + ram[f].name + ', ' + IntToStr(b_);
end else begin
Result := nemo + '0x'+IntToHex(f,3) + ', ' + IntToStr(b_);
end;
end;
i_ADDLW,
i_ANDLW,
i_IORLW,
i_MOVLW,
i_RETLW,
i_SUBLW,
i_XORLW: begin
Result := nemo + '0x'+IntToHex(k_,2);
end;
i_CALL,
i_GOTO: begin //Faltaría decodificar la dirección
Result := nemo + '0x'+IntToHex(k_,3);
end;
i_CLRW,
i_NOP,
i_CLRWDT,
i_RETFIE,
i_RETURN,
i_SLEEP: begin
Result := nemo ;
end;
else
Result := 'Invalid'
end;
end;
function TPIC17.DisassemblerAt(addr: word; useVarName: boolean): string;
{Disassembler the instruction located at "addr"}
var
valOp: Word;
bnkOp: Byte;
begin
valOp := flash[addr].value;
bnkOp := flash[addr].curBnk;
Result := Disassembler(valOp, bnkOp, useVarName); //desensambla
end;
function TPIC17.CurInstruction: TPIC17Inst;
{Resturn the instruction pointed by PC, in this moment.}
begin
Decode(flash[PC.W].value); //decodifica instrucción
Result := idIns;
end;
procedure TPIC17.Exec;
{Execute the current instruction.}
begin
Exec(PC.W);
end;
procedure TPIC17.Exec(aPC: word);
{Ejecuta la instrución actual con dirección "pc".
Falta implementar las operaciones, cuando acceden al registro INDF, el Watchdog timer,
los contadores, las interrupciones}
var
opc: Word;
//fullAdd: word;
msk, resNib: byte;
resByte, bit7, bit0: byte;
resWord: word;
resInt: integer;
Borrow: byte;
kSigned: ShortInt;
begin
//Decodifica instrucción
opc := flash[aPC].value;
Decode(opc); //decodifica instrucción
case idIns of
i_ADDWF: begin
resByte := FRAM;
resWord := W + resByte;
resNib := (W and $0F) + (resByte and $0F);
if d_ = toF then begin
FRAM := resWord and $FF;
end else begin //toW
w := resWord and $FF;
end;
STATUS_Z := (resWord and $ff) = 0;
STATUS_C := (resWord > 255);
STATUS_DC := (resNib > 15);
end;
i_ANDWF: begin
resByte := W and FRAM;
if d_ = toF then begin
FRAM := resByte;
end else begin //toW
w := resByte;
end;
STATUS_Z := resByte = 0;
end;
i_CLRF: begin
FRAM := 0;
STATUS_Z := true;
end;
i_CLRW: begin
W := 0;
STATUS_Z := true;
end;
i_COMF : begin
resByte := not FRAM;
if d_ = toF then begin
FRAM := resByte;
end else begin //toW
w := resByte;
end;
STATUS_Z := resByte = 0;
end;
i_DECF : begin
resByte := FRAM;
if resByte = 0 then resByte := $FF else dec(resByte);
if d_ = toF then begin
FRAM := resByte;
end else begin //toW
w := resByte;
end;
STATUS_Z := resByte = 0;
end;
i_DECFSZ: begin
resByte := FRAM;
if resByte = 0 then resByte := $FF else dec(resByte);
if d_ = toF then begin
FRAM := resByte;
end else begin //toW
w := resByte;
end;
STATUS_Z := resByte = 0;
if STATUS_Z then begin
Inc(PC.W); //Jump one instrucción
Inc(nClck); //In this case it takes one more cicle
end;
end;
i_INCF: begin