-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcam86ll.dpr
executable file
·1385 lines (1199 loc) · 41.5 KB
/
cam86ll.dpr
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
// --------------------------------------------------------------------------------
// ASCOM Camera driver low-level interaction library for cam86 v.0.9.1L
// Edit Log:
// Date Who Vers Description
// ----------- --- ----- ---------------------------------------------------------
// 28-aug-2016 VSS 0.1 Initial release (code obtained from grim)
//
// 1-feb-2017 Luka Pravica 0.2L
// - Update code to match the newer cam86_view
// - Add function to set camera reading time
// - if camera is not idle cameraGetCoolerPower, cameraGetCoolerOn and
// cameraGetTemp return cashed values to prevent image corruption while
// downloading images
// 3-feb-2017 Luka Pravica 0.3L
// - Add function to set if TEC cooling should be on or off during frame reading
// - Add function to read firmware version
// - Add function to read version of this DLL
// 19-feb-2017 Luka Pravica 0.4L
// - Add bias-before-exposure option
// 2-mar-2017 Luka Pravica 0.5L
// - Add humidity functions by Gilmanov Rim
// - Add controls for maximum and starting TEC power
// 8-mar-2017 Luka Pravica 0.6L
// - Fix bug where timer stops working if time is greater than 999s
// by using multiple restarts of the timer for every 900s
// 11-mar-2017 Luka Pravica 0.7L
// - Fix bug in long exposures (over 900s)
// - Add code to debug to file (must be disabled in production version)
// 17-mar-2017 Luka Pravica 0.8L
// - Add code to set the KP proportional gain
// 20-mar-2017 Luka Pravica 0.9L
// - Add code to read Cooler min, cooler max and Pk
// 21-mar-2017 Luka Pravica 0.9.1L
// - Fix bugs in Pk reading
// 27-Sep-2017 Luka Pravica 0.9.2L
// - Add caching of setCCDtemperature Get/Set and CoolerOn Get/Set during frame reads to prevent the white line bug
// 10-Nov-2017 Oscar Casanova 0.9.3
// - Kp value sent is multiplied by 100 instead of 1000 to be compatible with new proportional control
// 24-Nov-2017 Oscar Casanova 0.9.4
// - Add camera[Set|Get]PIDProportionalGain
// camera[Set|Get]PIDIntegralGain
// camera[Set|Get]PIDDerivativeGain
// to be compatible with full PID implementation
// 03-Feb-2018 Luka Pravica 0.9.5
// - Improve debugging outputs
// - Add delays after some commands to fix problems where commands are being sent too quickly to ATMega and getting lost
// 17-Feb-2018 Luka Pravica 0.9.6
// - Remove delays, move them to the main driver
//
// --------------------------------------------------------------------------------
{ Copyright © 2017 Gilmanov Rim, Vakulenko Sergiy and Luka Pravica
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
library cam86ll;
uses
Classes,
SysUtils,
MyD2XX,
MMSystem,
Windows,
SyncObjs,
ExtCtrls;
{$R *.res}
const
debugOn = false;
//debugFileName: string = 'cam86_log.txt';
//debugFileName: string = 'C:\Users\user\Desktop\cam86_log.txt';
//debugFileName: string = 'I:\oscar\Documents\src\cam86_log.txt';
debugFileName: string = 'D:\cam86_log.txt';
softwareLLDriverVersion = 96;
//ширина изображениÑ
CameraWidth = 3000;
//выÑота изображениÑ
CameraHeight = 2000;
//первоначальное значение на выводах порта BDBUS
portfirst = $11;
xccd = 1500;
yccd = 1000;
//bitbang speed
spusb = 20000;
// MCU commands
COMMAND_READFRAME = $1b;
COMMAND_SHIFT3 = $2b;
COMMAND_OFF15V = $3b;
COMMAND_SET_ROISTARTY = $4b;
COMMAND_SET_ROINUMY = $5b;
COMMAND_SET_EXPOSURE = $6b;
COMMAND_SET_BINNING = $8b;
COMMAND_ONOFFCOOLER = $9b;
COMMAND_SET_TARGETTEMP = $ab;
COMMAND_CLEARFRAME = $cb;
COMMAND_INITMCU = $db;
COMMAND_SET_DELAYPERLINE = $eb;
COMMAND_SET_COOLERONDURINGREAD = $fb;
COMMAND_SET_COOLERPOWERSTART = $0a;
COMMAND_SET_COOLERPOWERMAX = $1a;
COMMAND_SET_PIDKP = $2a;
COMMAND_SET_PIDKI = $3a;
COMMAND_SET_PIDKD = $4a;
COMMAND_GET_CASETEMP = $f1;
COMMAND_GET_CASEHUM = $f2;
COMMAND_GET_CCDTEMP = $bf;
COMMAND_GET_TARGETTEMP = $be;
COMMAND_GET_COOLERSTATUS = $bd;
COMMAND_GET_COOLERPOWER = $bc;
COMMAND_GET_VERSION = $bb;
COMMAND_GET_COOLERPOWERSTART = $ba;
COMMAND_GET_COOLERPOWERMAX = $b9;
COMMAND_GET_PIDKP_LW = $b8;
COMMAND_GET_PIDKP_HW = $b7;
COMMAND_GET_PIDKI_LW = $b6;
COMMAND_GET_PIDKI_HW = $b5;
COMMAND_GET_PIDKD_LW = $b4;
COMMAND_GET_PIDKD_HW = $b3;
//camera state consts
cameraIdle = 0;
cameraWaiting = 1;
cameraExposing = 2;
cameraReading = 3;
cameraDownload = 4;
cameraError = 5;
TemperatureOffset = 1280;
MinErrTemp = -120.0;
MaxErrTemp = 120.0;
TRUE_INV_PROT = $aa55;
FALSE_INV_PROT = $55aa;
HIGH_MASK_PROT = $aa00;
//driver image type
type camera_image_type = array [0..CameraHeight*CameraWidth-1] of integer;
//Class for reading thread
posl = class(TThread)
private
//Private declarations
protected
procedure Execute; override;
end;
//GLobal variables}
var
debugTextFile: TextFile;
debugTextFileIsOpen: boolean = False;
//переменнаÑ-флаг, отображает ÑоÑтоÑние ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ Ñ ÐºÐ°Ð¼ÐµÑ€Ð¾Ð¹
isConnected : boolean = false;
//указатель текущего адреÑа в выходном буфере FT2232HL
adress : integer;
//биннинг,
mBin : integer;
//переменнаÑ-флаг, отображает готовноÑÑ‚ÑŒ к Ñчитыванию кадра
imageReady : boolean = false;
//переменнаÑ-ÑоÑтоÑние камеры 0 - ready 1 - longexp 2 - read
cameraState : integer = 0;
//таймер ÑкÑпозиции
ExposureTimer : integer;
//Ð¿ÐµÑ€ÐµÐ¼ÐµÐ½Ð½Ð°Ñ Ð´Ð»Ñ Ð²Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ потока (чтение изображениÑ)
co : posl;
//буферный маÑÑив-изображение Ð´Ð»Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹
bufim : camera_image_type;
//начало Ñ‡Ñ‚ÐµÐ½Ð¸Ñ Ð¸ количеÑтво по Ñтрокам
mYn, mdeltY : integer;
kolbyte : integer;
eexp : integer;
siin : array[0..3] of byte;
siout : word;
//error Flag
errorReadFlag : boolean;
errorWriteFlag : boolean;
//cached values
sensorTempCache : Double = 0;
targetTempCache : Double = 0;
targetTempDirty : Boolean = false;
coolerOnCache : WordBool = false;
coolerOnDirty : Boolean = false;
coolerPowerCache : Double = 0;
firmwareVersionCache : byte = 0;
tempDHTCache : Double = -128.0;
humidityDHTCache : Double = -1;
CoolingStartingPowerPercentageCache : integer = -1;
CoolingMaximumPowerPercentageCache : integer = 101;
KpCache : Double = 0.0;
KiCache : Double = 0.0;
KdCache : Double = 0.0;
// timer counter
// timer can only count <1000s
// for longer exposures repeat the timer run as needed
exposure_time_left : integer;
eposure_time_rollover : integer = 900000; // 900 seconds (999 seconds is max)
exposure_time_loop_counter : integer;
// used when 0s exposure image is taken to clear the sensor before real exposure
sensorClear : boolean;
// needed function declarations
function cameraSetTemp(temp : double): WordBool; stdcall; export; forward;
function cameraCoolingOn (): WordBool; stdcall; export; forward;
function cameraCoolingOff (): WordBool; stdcall; export; forward;
// -------------------------------------------------------------------------------
// Infrastructure part
// -------------------------------------------------------------------------------
// Ðебольшое поÑÑнение работы Ñ FT2232LH.
// Ð’Ñегда иÑпользуетÑÑ Ñ‚Ð°ÐºÐ¾Ð¹ прием:
// 1. Вначале заполнÑетÑÑ Ð±ÑƒÑ„ÐµÑ€ и иÑходными байтами (необходимой поÑледовательноÑти импульÑов на выводах порта BDBUS).
// При Ñтом инкрементируетÑÑ ÑƒÐºÐ°Ð·Ð°Ñ‚ÐµÐ»ÑŒ adress.
// 2. Далее веÑÑŒ Ñтот маÑÑив передаетÑÑ Ð½Ð° выход командой: n:=Write_USB_Device_Buffer(FT_CAM8B,adress);
// Ð—Ð°Ð¼ÐµÑ‡Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ð¼Ð¸ÐºÑ€Ð¾Ñхема FT2232HL чеÑтно без задержек вÑе Ñто передает на Ñвой порт // BDBUS. Передача 1 байта при Ñтом занимает 65 нÑ.
// Ð’Ñ€ÐµÐ¼Ñ Ð¾Ñ‚Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ Ñледующей команды n:=Write_USB_Device_Buffer(FT_CAM8B,adress) завиÑит // от загруженноÑти операционки и не контролируетÑÑ
// нами. ПоÑтому критичеÑкую поÑледовательноÑти импульÑов нужно заполнÑÑ‚ÑŒ вÑÑŽ, а не передавать по очереди.
// Благо програмный буфер драйвера Ñто позволÑет (в Ñтой программе до 24 Мбайт!) Ð”Ð»Ñ Ñтого нужно изменить текÑÑ‚ D2XX.pas, Ñ Ð½Ð°Ð·Ð²Ð°Ð» его MyD2XX.pas
procedure debugToFile(line: string);
begin
if debugOn then
begin
if not debugTextFileIsOpen then
begin
AssignFile(debugTextFile, debugFileName);
if FileExists(debugFileName) = False then
Rewrite(debugTextFile)
else begin
Reset(debugTextFile);
Append(debugTextFile);
end;
debugTextFileIsOpen := True;
end;
WriteLn(debugTextFile, DateToStr(Now) + ' ' + TimeToStr(Now) + ': ' + line);
Flush(debugTextFile);
CloseFile(debugTextFile);
debugTextFileIsOpen := False;
end;
end;
function Qbuf():integer;
begin
Get_USB_Device_QueueStatus(FT_HANDLEA);
result:=FT_Q_Bytes;
end;
procedure sspi;
var i,j:integer;
b:byte;
n:word;
begin
n:=100;
FillChar(FT_Out_Buffer,n,portfirst);
for j:=0 to 2 do
begin
b:=siin[j];
for i:= 0 to 7 do
begin
inc(FT_Out_Buffer[2*i+1+16*j],$20);
if (b and $80) = $80 then
begin
inc(FT_Out_Buffer[2*i+16*j],$80);
inc(FT_Out_Buffer[2*i+1+16*j],$80);
end;
b:=b*2;
end;
end;
if (not errorWriteFlag) then
begin
errorWriteFlag := Write_USB_Device_Buffer_wErr(FT_HANDLEB,@FT_Out_Buffer,n);
end;
end;
procedure sspo;
var i:integer;
b:word;
n:word;
byteCnt, byteExpected : Word;
begin
n:=100;
byteCnt := 0;
byteExpected := n;
if (not errorWriteFlag) then
begin
byteCnt := Read_USB_Device_Buffer(FT_HANDLEB,n);
end;
if (byteCnt<>byteExpected) then
begin
errorReadFlag:=true;
end;
b:=0;
for i:=0 to 15 do
begin
b:=b*2;
if (FT_In_Buffer[i+1+8] and $40) <> 0 then
begin
inc(b);
end;
end;
siout:=b;
end;
procedure Spi_comm(comm:byte;param:word);
begin
Purge_USB_Device_In(FT_HANDLEB);
Purge_USB_Device_Out(FT_HANDLEB);
siin[0]:=comm;
siin[1]:=hi(param);
siin[2]:=lo(param);
sspi;
sspo;
sleep(20);
end;
procedure ComRead;
begin
co:=posl.Create(true);
co.FreeOnTerminate:=true;
co.Priority:=tpNormal;
co.Resume;
end;
procedure posl.Execute;
//ÑобÑтвенно Ñамо чтение маÑÑива через порт ADBUS
// Хитрое преобразование Ñчитанного буфера FT2232HL в буферный маÑÑив изображениÑ
// из-за оÑобенноÑтей AD9822 Ñчитываем Ñначала Ñтарший байт, потом младший, а в delphi наоборот.
// ИÑпользуем также тип integer32, а не word16 из-за Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¸ поÑледующих операциÑÑ…
var x, y:integer;
byteCnt : Word;
byteExpected : Word;
begin
byteCnt := 0;
byteExpected := kolbyte;
if (not errorWriteFlag) then
begin
byteCnt := Read_USB_Device_Buffer(FT_HANDLEA,kolbyte);
end;
if (byteCnt<>byteExpected) then
begin
errorReadFlag:=true;
if (not errorWriteFlag) then
begin
Purge_USB_Device_IN(FT_HANDLEA);
Purge_USB_Device_OUT(FT_HANDLEA);
end;
end
else begin
if mBin = 0 then
begin
for y:= 0 to mdeltY-1 do
begin
for x:=0 to 1499 do
begin
bufim[2*x+0+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[4*x+4+y*6004]);
bufim[2*x+0+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[4*x+5+y*6004]);
bufim[2*x+1+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[4*x+6+y*6004]);
bufim[2*x+1+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[4*x+7+y*6004]);
end;
end;
end
else begin
for y:= 0 to mdeltY-1 do
begin
for x:=0 to 1498 do
begin
bufim[2*x+0+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[x+7+y*1504]);
bufim[2*x+0+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[x+7+y*1504]);
bufim[2*x+1+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[x+7+y*1504]);
bufim[2*x+1+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[x+7+y*1504]);
end;
x:=1499;
bufim[2*x+0+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[x+6+y*1504]);
bufim[2*x+0+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[x+6+y*1504]);
bufim[2*x+1+(2*(y+mYn)+1)*3000]:=swap(FT_In_Buffer[x+6+y*1504]);
bufim[2*x+1+(2*(y+mYn)+0)*3000]:=swap(FT_In_Buffer[x+6+y*1504]);
end;
end;
end;
// discard image if sensorClearing was required (Bias frame before exposure)
if( sensorClear = true) then
begin
imageReady := false;
sensorClear := false;
end
else
begin
imageReady := true;
end;
cameraState:=cameraIdle;
// check if we need to update the CameraSetTemp value, i.e. if the set value changed
// while the sensor was read
if ( targetTempDirty) then
begin
debugToFile('pos1: Setting temperature from cache' + FloatToStr(targetTempCache));
cameraSetTemp(targetTempCache);
targetTempDirty := false;
end;
if (coolerOnDirty) then
begin
debugToFile('pos1: Setting cooler ON/OFF from cache' + BoolToStr(coolerOnCache));
if (coolerOnCache) then
begin
cameraCoolingOn();
end
else
begin
cameraCoolingOff();
end;
coolerOnDirty := false;
end;
end;
// Заполнение выходного буфера маÑÑивом Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ð¸ и Ñ€Ð°Ð·Ð¼ÐµÑ‰ÐµÐ½Ð¸Ñ Ð±Ð°Ð¹Ñ‚Ð° val по адреÑу adr в микроÑхеме AD9822.
// Передача идет в поÑледовательном коде.
procedure AD9822(adr:byte;val:word);
const
kol = 64;
var
dan:array[0..kol-1] of byte;
i:integer;
begin
//заполнÑетÑÑ Ð¼Ð°ÑÑив первоначальным значением на выводах порта BDBUS
fillchar(dan,kol,portfirst);
for i:=1 to 32 do
begin
dan[i]:=dan[i] and $fe;
end;
for i:=0 to 15 do
begin
dan[2*i+2]:=dan[2*i+2] + 2;
end;
if (adr and 4) = 4 then
begin
dan[3]:=dan[3]+4;
dan[4]:=dan[4]+4;
end;
if (adr and 2) = 2 then
begin
dan[5]:=dan[5]+4;
dan[6]:=dan[6]+4;
end;
if (adr and 1) = 1 then
begin
dan[7]:=dan[7]+4;
dan[8]:=dan[8]+4;
end;
if (val and 256) = 256 then
begin
dan[15]:=dan[15]+4;
dan[16]:=dan[16]+4;
end;
if (val and 128) = 128 then
begin
dan[17]:=dan[17]+4;
dan[18]:=dan[18]+4;
end;
if (val and 64) = 64 then
begin
dan[19]:=dan[19]+4;
dan[20]:=dan[20]+4;
end;
if (val and 32) = 32 then
begin
dan[21]:=dan[21]+4;
dan[22]:=dan[22]+4;
end;
if (val and 16) = 16 then
begin
dan[23]:=dan[23]+4;
dan[24]:=dan[24]+4;
end;
if (val and 8) = 8 then
begin
dan[25]:=dan[25]+4;
dan[26]:=dan[26]+4;
end;
if (val and 4) = 4 then
begin
dan[27]:=dan[27]+4;
dan[28]:=dan[28]+4;
end;
if (val and 2) = 2 then
begin
dan[29]:=dan[29]+4;
dan[30]:=dan[30]+4;
end;
if (val and 1) = 1 then
begin
dan[31]:=dan[31]+4;
dan[32]:=dan[32]+4;
end;
if (not errorWriteFlag) then
begin
errorWriteFlag := Write_USB_Device_Buffer_wErr(FT_HANDLEB,@dan, kol);
end;
end;
// ИÑпользуетÑÑ 2 режима:
// 1.Цветной без бининга.
// 2.Ч/Б Ñ Ð±Ð¸Ð½Ð¸Ð½Ð³Ð¾Ð¼ 2*2.
// ОÑобенноÑтью матрицы ICX453 ÑвлÑетÑÑ Ñ‚Ð¾, что горизонтальный региÑÑ‚Ñ€ имеет удвоенную емкоÑÑ‚ÑŒ и
// при одном шаге вертикального Ñдвига в горизонтальный региÑÑ‚Ñ€ "падает" Ñразу пара Ñтрок,
// поÑтому количеÑтво Ñтрок Ð´Ð»Ñ Ñтих двух режимиов одинаковое.
// Заполнение выходного буфера маÑÑивом и ÑобÑтвенно Ñама Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ ÐºÐ°Ð´Ñ€Ð° в 1 режиме
procedure readframe;
begin
debugToFile('readframe called');
cameraState := cameraReading;
Purge_USB_Device_IN(FT_HANDLEA);
// Purge_USB_Device_OUT(FT_HANDLEB);
comread;
Spi_comm(COMMAND_READFRAME,0);
end;
// -------------------------------------------------------------------------------
// Interface part
// -------------------------------------------------------------------------------
// Set camera gain, return bool result
function cameraSetGain (val : integer) : WordBool; stdcall; export;
begin
//уÑиление AD9822
AD9822(3,val);
Result :=true;
end;
//Set camera offset, return bool result
function cameraSetOffset (val : integer) : WordBool; stdcall; export;
var x : integer;
begin
debugToFile('cameraSetOffset: Offset set to' + IntToStr(val));
x:=abs(2*val);
if val < 0 then
begin
x:=x+256;
end;
//Ñмещение AD9822
AD9822(6,x);
Result :=true;
end;
// Connect camera, return bool result
// ÐžÐ¿Ñ€Ð¾Ñ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð½Ñ‹Ñ… уÑтройÑтв и Ð¸Ð½Ð¸Ñ†Ð¸Ð°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ñ AD9822
function cameraConnect () : WordBool; stdcall; export;
var FT_flag : boolean;
begin
FT_Enable_Error_Report := true;
FT_flag := true;
errorWriteFlag := false;
sensorTempCache := 0;
targetTempCache := 0;
targetTempDirty := false;
coolerOnCache := false;
coolerOnDirty := false;
coolerPowerCache := 0;
firmwareVersionCache := 0;
debugToFile('cameraConnect called');
if (FT_flag) then
begin
if Open_USB_Device_By_Serial_Number(FT_HANDLEA,'CAM86A') <> FT_OK then
begin
FT_flag := false;
end;
end;
if (FT_flag) then
begin
if Open_USB_Device_By_Serial_Number(FT_HANDLEB,'CAM86B') <> FT_OK then
begin
FT_flag := false;
end;
end;
if (FT_flag) then
begin
// BitMode for B-channel
if Set_USB_Device_BitMode(FT_HANDLEB,$bf, $4) <> FT_OK then
begin
FT_flag := false;
end;
end;
if (FT_flag) then
begin
//speed = spusb
FT_Current_Baud:=spusb;
Set_USB_Device_BaudRate(FT_HANDLEB);
//макÑимальное быÑтродейÑтвие
Set_USB_Device_LatencyTimer(FT_HANDLEB,2);
Set_USB_Device_LatencyTimer(FT_HANDLEA,2);
Set_USB_Device_TimeOuts(FT_HANDLEA,6000,100);
Set_USB_Device_TimeOuts(FT_HANDLEB,100,100);
Set_USB_Parameters(FT_HANDLEA,65536,0);
Purge_USB_Device_IN(FT_HANDLEA);
Purge_USB_Device_OUT(FT_HANDLEA);
Purge_USB_Device_IN(FT_HANDLEB);
Purge_USB_Device_OUT(FT_HANDLEB);
adress:=0;
//режим AD9822 - канал G,4 вольта опорноÑÑ‚ÑŒ, CDS режим
AD9822(0,$d8);
AD9822(1,$a0);
CameraSetGain(0);
//уÑиление уÑтанавливаетÑÑ Ñ‚Ð°ÐºÐ¾Ðµ. что не переполнÑетÑÑ ÐЦП
CameraSetOffset(-6);
sleep(100);
//send init command
Spi_comm(COMMAND_INITMCU,0);
sleep(100);
//убрать 2 байта, возникших поÑле reset
Purge_USB_Device_IN(FT_HANDLEA);
mBin:=0;
end;
isConnected := FT_flag;
errorReadFlag := false;
cameraState := cameraIdle;
imageReady := false;
if(FT_flag = false) then
begin
cameraState := cameraError;
end;
Result := isConnected;
end;
//Disconnect camera, return bool result
function cameraDisconnect (): WordBool; stdcall; export;
var FT_OP_flag : boolean;
begin
debugToFile('cameraDisconnect called');
FT_OP_flag := true;
//закрытие уÑтройÑтв
if Close_USB_Device(FT_HANDLEA) <> FT_OK then
begin
FT_OP_flag := false;
end;
if Close_USB_Device(FT_HANDLEB) <> FT_OK then
begin
FT_OP_flag := false;
end;
isConnected := not FT_OP_flag;
Result:= FT_OP_flag;
end;
// Check camera connection, return bool result}
function cameraIsConnected () : WordBool; stdcall; export;
begin
debugToFile('cameraIsConnected: result=' + BoolToStr(isConnected));
Result := isConnected;
end;
procedure ExposureTimerTick(TimerID, Msg: Uint; dwUser, dw1, dw2: DWORD); stdcall;
begin
debugToFile('ExposureTimerTick:' +
'exp_time_left=' + IntToStr(exposure_time_left) +
', exp_time_loop_counter=' + IntToStr(exposure_time_loop_counter));
if exposure_time_loop_counter > 0 then
begin
// reduce the counter for the loop that just finished
exposure_time_loop_counter := exposure_time_loop_counter - 1;
// restart the timer if needed
if exposure_time_loop_counter > 0 then
begin
debugToFile('ExposureTimerTick: restarting timer' +
', exp_time_left=' + IntToStr(exposure_time_left) +
', exp_time_loop_counter=' + IntToStr(exposure_time_loop_counter));
ExposureTimer := TimeSetEvent(eposure_time_rollover, 100, @ExposureTimerTick, 0, TIME_ONESHOT);
Exit;
end
else begin
if exposure_time_left > 0 then
begin
debugToFile('ExposureTimerTick: final restarting of timer' +
', exp_time_left=' + IntToStr(exposure_time_left) +
', exp_time_loop_counter=' + IntToStr(exposure_time_loop_counter));
ExposureTimer := TimeSetEvent(exposure_time_left, 100, @ExposureTimerTick, 0, TIME_ONESHOT);
Exit;
end;
end;
end;
// if we get here then we are finished
debugToFile('ExposureTimerTick: final read');
readframe;
end;
procedure cameraSensorClearFull();
var expoz:integer;
begin
debugToFile('cameraSensorClearFull called');
errorReadFlag := false;
imageReady := false;
mYn:=0;
Spi_comm(COMMAND_SET_ROISTARTY,mYn);
mdeltY:=CameraHeight div 2;
Spi_comm(COMMAND_SET_ROINUMY,mdeltY);
// use 2x2 binning to increase the reading speed
// the image will be deleted anyway
kolbyte:=mdeltY*3008;
//bining
Spi_comm(COMMAND_SET_BINNING,1);
mBin:=1;
expoz := 0; // zero exposure
Spi_comm(COMMAND_SET_EXPOSURE,expoz);
cameraState := cameraExposing;
eexp:=0;
readframe;
// wait until the bias frame has been read - we will discard the data
// This will lock this main thread for a short time... not sure if this is a good thing?
// this seems to take 1600 ms
while (sensorClear = True) do
begin
sleep(10);
end;
// now exit to do proper exposure
end;
function cameraStartExposure (Bin, StartX, StartY, NumX, NumY : integer; Duration : double; light : WordBool) : WordBool; stdcall; export;
var expoz:integer;
begin
debugToFile('cameraStartExposure: Bin=' + IntToStr(Bin) + ', StartX=' + IntToStr(StartX) +
', StartY=' + IntToStr(StartY) + ', NumX=' + IntToStr(NumX) +
', NumY=' + IntToStr(NumY) + ', Duration=' + FloatToStr(Duration) +
', light=' + BoolToStr(light));
if (sensorClear) then
begin
cameraSensorClearFull;
end;
errorReadFlag := false;
imageReady := false;
mYn:=StartY div 2;
Spi_comm(COMMAND_SET_ROISTARTY,mYn);
mdeltY:=NumY div 2;
Spi_comm(COMMAND_SET_ROINUMY,mdeltY);
if bin = 2 then
begin
kolbyte:=mdeltY*3008;
//bining
Spi_comm(COMMAND_SET_BINNING,1);
mBin:=1;
end
else begin
kolbyte:=mdeltY*12008;
//no bining
Spi_comm(COMMAND_SET_BINNING,0);
mBin:=0;
end;
expoz:=round(Duration*1000);
if expoz > 1000 then
begin
expoz:=1001;
end;
Spi_comm(COMMAND_SET_EXPOSURE,expoz);
cameraState := cameraExposing;
if Duration > 1.0 then
begin
//shift3
Spi_comm(COMMAND_SHIFT3,0);
sleep(40);
//clear frame
Spi_comm(COMMAND_CLEARFRAME,0);
// for time of clear frame
sleep(180);
//off 15v
Spi_comm(COMMAND_OFF15V,0);
eexp:=round(1000*(Duration-1.2));
if eexp < 0 then
begin
eexp := 0;
end;
// calculate the exposure time with repetitions of the timing loop
exposure_time_left := eexp mod eposure_time_rollover;
exposure_time_loop_counter := eexp div eposure_time_rollover;
debugToFile('----------------');
debugToFile('cameraStartExposure: Duration=' + FloatToStr(Duration) +
', eexp=' + IntToStr(eexp) +
', exp_time_left=' + IntToStr(exposure_time_left) +
', exp_time_loop_counter=' + IntToStr(exposure_time_loop_counter) +
', eposure_time_rollover=' + IntToStr(eposure_time_rollover));
// start exposure while paying attention to the repetitions of the timing loop
if exposure_time_loop_counter > 0 then
begin
ExposureTimer := TimeSetEvent(eposure_time_rollover, 100, @ExposureTimerTick, 0, TIME_ONESHOT);
end
else begin
if exposure_time_left > 0 then
begin
ExposureTimer := TimeSetEvent(exposure_time_left, 100, @ExposureTimerTick, 0, TIME_ONESHOT);
end
else begin
eexp := 0;
readframe;
end;
end;
end
else begin
eexp:=0;
readframe;
end;
Result := true;
end;
function cameraStopExposure : WordBool; stdcall; export;
begin
debugToFile('cameraStopExposure called');
TimeKillEvent(ExposureTimer);
if (cameraState = cameraExposing) then
begin
readframe;
end;
Result := true;
end;
//Get camera state, return int result
function cameraGetCameraState : integer; stdcall; export;
begin
debugToFile('cameraGetCameraState called');
if (not errorWriteFlag) then
begin
Result := cameraState
end
else begin
Result := cameraError;
end;
debugToFile('cameraGetCameraState: state=' + IntToStr(Result));
end;
//Check ImageReady flag, is image ready for transfer - transfer image to driver and return bool ImageReady flag
function cameraGetImageReady : WordBool; stdcall; export;
begin
Result := imageReady;
debugToFile('cameraGetImageReady: state=' + BoolToStr(Result));
end;
//Get back pointer to image
function cameraGetImage : dword; stdcall; export;
begin
debugToFile('cameraGetImage called');
cameraState:=cameraDownload;
cameraState:=cameraIdle;
Result := dword(@bufim);
end;
//Get camera error state, return bool result
function cameraGetError : integer; stdcall; export;
var res : integer;
begin
debugToFile('cameraGetError called');
res:=0;
if (errorWriteFlag) then res :=res+2;
if (errorReadFlag) then res :=res+1;
Result:=res;
debugToFile('cameraGetError: error=' + IntToStr(Result));
end;
function cameraGetTemp (): double; stdcall; export;
var temp : double;
begin
debugToFile('cameraGetTemp called');
if ((cameraState = cameraReading) or (cameraState = cameraDownload)) then
begin
Result := sensorTempCache;
end
else
begin
Spi_comm(COMMAND_GET_CCDTEMP,0);
temp := (siout - TemperatureOffset) / 10.0;
if ((temp > MaxErrTemp) or (temp < MinErrTemp)) then
begin
temp := sensorTempCache;
end;
sensorTempCache := temp;
Result := temp;
end;
debugToFile('cameraGetTemp: temp=' + FloatToStr(Result));
end;
function cameraSetTemp(temp : double): WordBool; stdcall; export;
var d0:word;
begin
debugToFile('cameraSetTemp: temp=' + FloatToStr(temp));
if ((cameraState = cameraReading) or (cameraState = cameraDownload)) then
begin
targetTempCache := temp;
targetTempDirty := true;
debugToFile('cameraSetTemp: Caching temperature ' + FloatToStr(targetTempCache));
end
else
begin
d0 := TemperatureOffset + round(temp*10);
Spi_comm(COMMAND_SET_TARGETTEMP,d0);
targetTempDirty := false;
debugToFile('cameraSetTemp: setting temperature ' + FloatToStr(temp));
end;
Result := true;
end;
function cameraGetSetTemp (): double; stdcall; export;
var temp : double;
begin
debugToFile('cameraGetSetTemp called');
if ((cameraState = cameraReading) or (cameraState = cameraDownload)) then
begin
Result := targetTempCache;
end
else
begin
Spi_comm(COMMAND_GET_TARGETTEMP,0);
temp := (siout - TemperatureOffset) / 10.0;
if ((temp > MaxErrTemp) or (temp < MinErrTemp)) then
begin
temp := targetTempCache;
end;
targetTempCache := temp;
Result := temp;
end;
debugToFile('cameraGetSetTemp: temp=' + FloatToStr(Result));
end;
function cameraCoolingOn (): WordBool; stdcall; export;
begin
debugToFile('cameraCoolingOn called');
if ((cameraState = cameraReading) or (cameraState = cameraDownload)) then
begin
debugToFile('cameraCoolingOn: Caching cooler on value');
coolerOnCache := true;