Subversion Repositories f9daq

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
213 f9daq 1
// NativeExportsConsumerApp.cpp : Defines the entry point for the console application.
2
//
3
 
4
#include "stdafx.h"
5
#include <string.h>
6
#include <windows.h>
7
#include "AitMduManager.h"
8
#include "AitMduManager_DEF.h"
9
 
10
typedef unsigned short ushort;
11
typedef unsigned int uint;
12
 
13
extern "C"
14
{
15
        DLLIMPORT  void NE_Rainbow();
16
 
17
        DLLIMPORT  int  NE_Func(int a);
18
        DLLIMPORT  int  NE_Ptr2ByteArray(char *, int len);
19
        DLLIMPORT  char * NE_ByteArray2Ptr(char *, int *);
20
        DLLIMPORT  int  NE_Ptr2String(char *, int len);
21
        DLLIMPORT  int  NE_String2Ptr(char *);
22
        DLLIMPORT  char * NE_String();
23
        DLLIMPORT  unsigned int * NE_UInt(int *);
24
}
25
 
26
#ifdef _DEBUG
27
#pragma comment(lib, "../UnmanagedDllInterface/bin/Debug/AitSipmDAQDll.lib")
28
#else
29
#pragma comment(lib, "../UnmanagedDllInterface/bin/Release/AitSipmDAQDll.lib")
30
#endif
31
 
32
uint deviceId = 0;
33
int deviceIndex = -1;
34
int adcBufferLen;
35
ushort * adcBuffer;
36
int histograms[4][0xFFF];
37
int histogramTotalEvents = 0;
38
 
39
const double MONADC_SCALE = 65535.0;                    // 16-bit monitor ADC
40
const double DAC_SCALE = 65535.0;                       // 16-bit DAC
41
const double MONADC_VRANGE = 2.5;                       // 2.5V ADC voltage range
42
const double DISCR_OFFSETRANGE = 250.0;         // +/- 250mV discriminator offset range
43
const double DISCR_THRESHOLDRANGE = 1000.0;     // 0-1000mV discriminator threshold range
44
const double HV_IRANGE = 5.0;                           // 0-5.0mA HV current monitor range
45
const double HV_VRANGE = 80.0;                          // 0-80V HV voltage control range
46
const int INTEGRATOR_LSB = 10;                          // 10ns integrator time resolution
47
const double RAMPRATESCALE = 61036.0;           // Ramp rate register setting = (rate in V/s) / RAMPRATESCALE
48
const char statusNoDevice[0xFF] = "No Device Connected";
49
const char statusReconfig[0xFF] = "Reconfiguring Device ... ";
50
const char statusReset[0xFF] = "Resetting Device ... ";
51
const char statusReconnect[0xFF] = "Reconnecting Device ... ";
52
const char statusDone[0xFF] = "Done";
53
 
54
/*
55
void Sleep(int musec) {
56
 
57
}
58
*/
59
 
60
//----------------------------------------
61
// Utilities
62
//----------------------------------------
63
ushort SetBit(ushort data, int bitIndex, bool bitValue)
64
{
65
        if (bitValue == true)
66
                return (ushort)(data | (1 << bitIndex));
67
        else
68
                return (ushort)(data & ~(1 << bitIndex));
69
}
70
 
71
bool GetBit(int data, int bitIndex)
72
{
73
        return (data & (1 << bitIndex)) != 0;
74
}
75
 
76
ushort ReadSD4Register(int reg)
77
{
78
        return SD4_Read(deviceId, reg);
79
}
80
 
81
uint ReadSD4Register32(int addrHi, int addrLo)
82
{
83
        uint dataHi = (uint)SD4_Read(deviceId, addrHi);
84
        uint dataLo = (uint)SD4_Read(deviceId, addrLo);
85
        return (dataHi << 16) | dataLo;
86
}
87
 
88
void WriteSD4Register(int address, ushort data)
89
{
90
        SD4_Write(deviceId, address, data);
91
}
92
 
93
void WriteSD4Register32(int addrHi, int addrLo, uint data)
94
{
95
        WriteSD4Register(addrHi, (ushort)(data >> 16));
96
        WriteSD4Register(addrLo, (ushort)data);
97
}
98
 
99
 
100
void ReadModifyWrite(int reg, int bitIndex, bool bitValue)
101
{
102
        ushort regData = ReadSD4Register(reg);
103
        regData = SetBit(regData, bitIndex, bitValue);
104
        WriteSD4Register(reg, regData);
105
}
106
 
107
double LimitSetting(double value, double min, double max)
108
{
109
        double limited = value;
110
        if (limited > max) limited = max;
111
        if (limited < min) limited = min;
112
        return limited;
113
}
114
 
115
 
116
 
117
int ReadAdcBuffer()
118
{
119
        //if (adcBuffer == NULL)
120
        //      return -1;
121
        int bytes = 0;
122
        //printf("In\n%d\n%d\n%d\n", deviceId, ADDR_BUFFER, adcBufferLen);
123
        adcBuffer = SD4_ReadUShortArray(deviceId, ADDR_BUFFER, adcBufferLen, &bytes);
124
        return bytes;
125
}
126
// Equivalent to ReadAdcBuffer() except using byte buffer for acquisition
127
int ReadAdcByteBuffer()
128
{
129
        if (adcBuffer == NULL)
130
                return -1;
131
        int bytes = 0;
132
        char * byteBuffer = SD4_ReadByteArray(deviceId, ADDR_BUFFER, adcBufferLen * 2, &bytes);
133
        int byteIndex = 0;
134
        int words = bytes / 2;
135
        ushort dataword = 0;
136
        for (int i = 0; i < words; i++)
137
        {
138
                dataword = (ushort)(byteBuffer[byteIndex++] << 8);
139
                adcBuffer[i] = (ushort)(dataword | byteBuffer[byteIndex++]);
140
        }
141
        return words;
142
}
143
 
144
 
145
 
146
 
147
 
148
 
149
//----------------------------------------
150
// Monitor ADC
151
//----------------------------------------
152
 
153
double GetVoltage(int reg)
154
{
155
        return ReadSD4Register(reg) * MONADC_VRANGE / MONADC_SCALE;
156
}
157
 
158
double GetDetectorTemperature()
159
{
160
        // Temperature = 500mV + 1mV per degree C
161
        return (GetVoltage(ADDR_BASE_TEMPERATURE) - 0.5) / 0.01;
162
}
163
 
164
double GetHvVoltage(int reg)
165
{
166
        return GetVoltage(reg) / MONADC_VRANGE * HV_VRANGE;
167
}
168
 
169
double GetHvCurrentInUa()
170
{
171
        // 2.5V ADC input voltage = 5000 microamps
172
        return GetVoltage(ADDR_HV_IMON) * 2000.0;
173
}
174
 
175
double GetVoltage75(int reg)
176
{
177
        // 2.5V ADC input voltage = 7.5V monitor voltage
178
        return GetVoltage(reg) * 3.0;
179
}
180
 
181
 
182
 
183
//----------------------------------------
184
// Discriminator, Sum
185
//----------------------------------------
186
 
187
void SetSumGain(int gain)
188
{
189
        ushort csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
190
        bool g1 = GetBit(gain, 0);
191
        bool g2 = GetBit(gain, 1);
192
        bool g3 = GetBit(gain, 2);
193
        bool g4 = GetBit(gain, 3);
194
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN1, g1);
195
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN2, g2);
196
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN3, g3);
197
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN4, g4);
198
        WriteSD4Register(ADDR_CSR_DETECTOR, (ushort)csrDetector);
199
}
200
 
201
void SetSumCoupling(bool acCoupling)
202
{
203
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_SUMCOUPLING, acCoupling);
204
}
205
 
206
void SetThreshold(double thresholdInMillivolts)
207
{
208
        thresholdInMillivolts = LimitSetting(thresholdInMillivolts, -DISCR_THRESHOLDRANGE, DISCR_THRESHOLDRANGE);
209
        WriteSD4Register(ADDR_DISCR_THRESHOLD, (ushort)(thresholdInMillivolts * DAC_SCALE / DISCR_THRESHOLDRANGE));
210
}
211
 
212
double GetThreshold()
213
{
214
        return ReadSD4Register(ADDR_DISCR_THRESHOLD) / DAC_SCALE * DISCR_THRESHOLDRANGE;
215
}
216
 
217
double GetSumOffsetInMv()
218
{
219
        // Sum offsets are with respect to the positive sum output polarity.
220
        return (ReadSD4Register(ADDR_DISCR_OFFSET) / DAC_SCALE * (DISCR_OFFSETRANGE * 2)) - DISCR_OFFSETRANGE;
221
}
222
 
223
void SetSumOffset(double milliVolts)
224
{
225
        // Sum offsets are with respect to the positive sum output polarity.
226
        // Actual output offset is multiplied by the selectable gain stage.
227
        WriteSD4Register(ADDR_DISCR_OFFSET, (ushort)((milliVolts + DISCR_OFFSETRANGE) * DAC_SCALE / (DISCR_OFFSETRANGE * 2)));
228
}
229
 
230
 
231
 
232
//----------------------------------------
233
// Trigger
234
//----------------------------------------
235
 
236
void SetTriggerInterval(int triggerInterval)
237
{
238
        WriteSD4Register32(ADDR_TG_INTERVALHI, ADDR_TG_INTERVALLO, (uint)(triggerInterval / INTEGRATOR_LSB));
239
}
240
 
241
void SetTriggerBurst(int triggerBurst)
242
{
243
        WriteSD4Register32(ADDR_TG_COUNTHI, ADDR_TG_COUNTLO, (uint)triggerBurst);
244
}
245
 
246
void EnableTrigger(int bitIndex)
247
{
248
        WriteSD4Register(ADDR_CSR_TRIGGER, SetBit(0, bitIndex, true));
249
}
250
 
251
void DisableTriggers()
252
{
253
        WriteSD4Register(ADDR_CSR_TRIGGER, 0);
254
}
255
 
256
void SetDeadTime(int deadTimeInNs)
257
{
258
        WriteSD4Register(ADDR_DEADTIME, (ushort)(deadTimeInNs / INTEGRATOR_LSB));
259
}
260
 
261
 
262
 
263
//----------------------------------------
264
// Integrators, ADCs
265
//----------------------------------------
266
 
267
void SetIntegrationTime(int integrationTime)
268
{
269
        WriteSD4Register(ADDR_ITIME, (ushort)(integrationTime / INTEGRATOR_LSB));
270
}
271
 
272
int GetIntegrationTime()
273
{
274
        return ReadSD4Register(ADDR_ITIME) * INTEGRATOR_LSB;
275
}
276
 
277
void SetAdcCoupling(bool acCoupling)
278
{
279
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_ADCCOUPLING, acCoupling);
280
}
281
 
282
void ResetAdc(bool reset)
283
{
284
        ushort cmd = 0;
285
        cmd = SetBit(cmd, BIT_CSR_MAIN_ADCRESET, reset);
286
        WriteSD4Register(ADDR_CSR_MAIN, cmd);
287
}
288
 
289
double GetAdcOffsetInMv(int reg)
290
{
291
        // ADC offset polarity is with respect to the positive ADC polarity (integrator output), not the main negative input signal polarity.
292
        // Actual output offset is multiplied by the selectable gain stage.
293
        return DISCR_OFFSETRANGE - (ReadSD4Register(reg) / DAC_SCALE * (DISCR_OFFSETRANGE * 2));
294
}
295
 
296
void SetAdcOffset(int reg, double milliVolts)
297
{
298
        // ADC offset polarity is with respect to the positive ADC polarity (integrator output), not the main negative input signal polarity.
299
        // Actual output offset is multiplied by the selectable gain stage.
300
        WriteSD4Register(reg, (ushort)((DISCR_OFFSETRANGE - milliVolts) * DAC_SCALE / (DISCR_OFFSETRANGE * 2)));
301
}
302
 
303
 
304
 
305
//----------------------------------------
306
// Event ID
307
//----------------------------------------
308
 
309
void AddEventCount(bool addEventCount)
310
{
311
        ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_COUNT, addEventCount);
312
}
313
 
314
void AddTimeStamp(bool addTimeStamp)
315
{
316
        ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_TIME, addTimeStamp);
317
}
318
 
319
void AddChannelNumber(bool addChannelNumber)
320
{
321
        ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_CHNUM, addChannelNumber);
322
}
323
 
324
 
325
 
326
//----------------------------------------
327
// Detector VA
328
//----------------------------------------
329
 
330
void SetDetectorVaOn(bool on)
331
{
332
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_VAENABLE, on);
333
}
334
 
335
void SetDetectorVaHiRange(bool range)
336
{
337
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_VAHIRNG, range);
338
}
339
 
340
 
341
 
342
//----------------------------------------
343
// High Voltage
344
//----------------------------------------
345
 
346
void SetHvCurrentLimit(double milliamps)
347
{
348
        milliamps = LimitSetting(milliamps, 0, HV_IRANGE);
349
        WriteSD4Register(ADDR_HV_ILIMIT, (ushort)(milliamps * DAC_SCALE / HV_IRANGE));
350
}
351
 
352
void SetHvVoltage(int reg, double volts)
353
{
354
        volts = LimitSetting(volts, 0, HV_VRANGE);
355
        WriteSD4Register(reg, (ushort)(volts * DAC_SCALE / HV_VRANGE));
356
}
357
 
358
double GetHvIlimitSetting()
359
{
360
        return ReadSD4Register(ADDR_HV_ILIMIT) / DAC_SCALE * HV_IRANGE;
361
}
362
 
363
double GetHvVoltageSetting()
364
{
365
        return ReadSD4Register(ADDR_HV_CTRL) / DAC_SCALE * HV_VRANGE;
366
}
367
 
368
void SetHvOn(bool hvOn)
369
{
370
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVENABLE, hvOn);
371
}
372
 
373
void SetMaximumHvSetting(double volts)
374
{
375
        SetHvVoltage(ADDR_HV_MAX, volts);
376
}
377
 
378
void CycleHvReset()
379
{
380
        // CAUTION: Holding HV in reset will force it to ignore the current limit
381
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVRESET, true);
382
        ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVRESET, false);
383
}
384
 
385
void SetRampRate(double voltsPerSecond)
386
{
387
        WriteSD4Register(ADDR_HV_RAMPRATE, (ushort)(RAMPRATESCALE / voltsPerSecond));
388
}
389
 
390
double GetRampRate()
391
{
392
        return RAMPRATESCALE / (ReadSD4Register(ADDR_HV_RAMPRATE) + 1);
393
}
394
 
395
void SetAdcGain(int gain)
396
{
397
        ushort csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
398
        bool g1 = GetBit(gain, 0);
399
        bool g2 = GetBit(gain, 1);
400
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_ADCGAIN1, g1);
401
        csrDetector = SetBit(csrDetector, BIT_CSR_DET_ADCGAIN2, g2);
402
        WriteSD4Register(ADDR_CSR_DETECTOR, (ushort)csrDetector);
403
}
404
 
405
void SetAdcOffsets(int offsetInMv)
406
{
407
        //nudOffset1.Value = offsetInMv;
408
        //nudOffset2.Value = offsetInMv;
409
        //nudOffset3.Value = offsetInMv;
410
        //nudOffset4.Value = offsetInMv;
411
        SetAdcOffset(ADDR_OFFSET1, offsetInMv);
412
        SetAdcOffset(ADDR_OFFSET2, offsetInMv);
413
        SetAdcOffset(ADDR_OFFSET3, offsetInMv);
414
        SetAdcOffset(ADDR_OFFSET4, offsetInMv);
415
}
416
 
417
void QuickSetupContinuous()
418
{
419
        // Set ADC reset
420
        ResetAdc(true);
421
 
422
        // Clear ADC reset
423
        ResetAdc(false);
424
 
425
        // Set trigger dead time to 200ns
426
        SetDeadTime(200);
427
 
428
        // Set event ID
429
        AddTimeStamp(true);
430
        AddEventCount(true);
431
        AddChannelNumber(true);
432
 
433
        // Enable detector amplifier voltage
434
        SetDetectorVaHiRange(false);
435
        SetDetectorVaOn(true);
436
 
437
        /*
438
        // Set HV current limit
439
        double iLimit = 2.5;
440
        nudHvIlimit.Value = (decimal)iLimit;
441
        SetHvCurrentLimit(iLimit);
442
 
443
        // Reset any HV faults
444
        CycleHvReset();
445
 
446
        // Enable bias voltage
447
        SetHvOn(false);
448
        SetHvOn(true);
449
 
450
        // Set bias voltage
451
        double hvVoltage = 30.0;
452
        nudHvVoltage.Value = (decimal)hvVoltage;
453
        SetHvVoltage(ADDR_HV_CTRL, hvVoltage);
454
        */
455
 
456
        // Set integration time
457
        int integrationTime = 350;
458
        //nudIntegrationTime.Value = integrationTime;
459
        SetIntegrationTime(integrationTime);
460
 
461
        // Set discriminator threshold
462
        int threshold = 50;
463
        //nudThreshold.Value = threshold;
464
        SetThreshold(threshold);
465
 
466
        // Set sum coupling
467
        SetSumCoupling(true);
468
 
469
        // Set sum gain
470
        int sumGain = 3;
471
        //nudSumGain.Value = sumGain;
472
        SetSumGain(sumGain);
473
 
474
        // Set sum offset
475
        int offset = 0;
476
        //nudSumOffset.Value = offset;
477
        SetSumOffset(offset);
478
 
479
        // Set ADC coupling
480
        SetAdcCoupling(false);
481
 
482
        // Set ADC gains
483
        int gain = 1;
484
        //nudAdcGain.Value = gain;
485
        SetAdcGain(gain);
486
 
487
        // Set all ADC offsets
488
        SetAdcOffsets(5);
489
 
490
        // Set internal trigger interval
491
        int triggerInterval = 1000;
492
        //nudTriggerInterval.Value = triggerInterval;
493
        SetTriggerInterval(triggerInterval);
494
 
495
        // Enable continuous trigger
496
        EnableTrigger(BIT_CSR_TRIG_CONTINUOUS);
497
 
498
        // Begin continuous acquisition
499
        //nudEventsPerAcquisition.Value = 50000;
500
        //cbAcquireContinuous.Checked = true;
501
 
502
        // Update histogram offsets
503
        //SetAllHistogramOffsets(0);
504
}
505
 
506
 
507
void QuickSetupDiscriminator()
508
{
509
        // Set ADC reset
510
        ResetAdc(true);
511
 
512
        // Clear ADC reset
513
        ResetAdc(false);
514
 
515
        // Set trigger dead time to 300ns
516
        SetDeadTime(500);
517
 
518
        // Set event ID
519
        AddTimeStamp(true);
520
        AddEventCount(true);
521
        AddChannelNumber(true);
522
 
523
        // Enable detector amplifier voltage
524
        SetDetectorVaHiRange(true);
525
        SetDetectorVaOn(true);
526
 
527
        // Set HV current limit
528
        double iLimit = 2.5;
529
        //nudHvIlimit.Value = (decimal)iLimit;
530
        SetHvCurrentLimit(iLimit);
531
 
532
        // Reset any HV faults
533
        CycleHvReset();
534
 
535
        // Enable bias voltage
536
        SetHvOn(false);
537
        SetHvOn(true);
538
 
539
        // Set bias voltage
540
        double hvVoltage = 30.0;
541
        //nudHvVoltage.Value = (decimal)hvVoltage;
542
        SetHvVoltage(ADDR_HV_CTRL, hvVoltage);
543
 
544
        // Set integration time
545
        int integrationTime = 350;
546
        //nudIntegrationTime.Value = integrationTime;
547
        SetIntegrationTime(integrationTime);
548
 
549
        // Set discriminator threshold
550
        int threshold = 50;
551
        //nudThreshold.Value = threshold;
552
        SetThreshold(threshold);
553
 
554
        // Set sum coupling
555
        SetSumCoupling(true);
556
 
557
        // Set sum gain
558
        int sumGain = 3;
559
        //nudSumGain.Value = sumGain;
560
        SetSumGain(sumGain);
561
 
562
        // Set sum offset
563
        int offset = 0;
564
        //nudSumOffset.Value = offset;
565
        SetSumOffset(offset);
566
 
567
        // Set ADC coupling
568
        SetAdcCoupling(false);
569
 
570
        // Set ADC gains
571
        int gain = 1;
572
        //nudAdcGain.Value = gain;
573
        SetAdcGain(gain);
574
 
575
        // Set all ADC offsets
576
        SetAdcOffsets(5);
577
 
578
        // Clear histograms
579
        //ClearHistograms();
580
 
581
        // Enable discriminator trigger
582
        EnableTrigger(BIT_CSR_TRIG_DISCR);
583
 
584
        // Begin continuous acquisition
585
        //nudEventsPerAcquisition.Value = 1000;
586
        //cbAcquireContinuous.Checked = true;
587
 
588
        // Update histogram offsets
589
        //SetAllHistogramOffsets(0);
590
}
591
 
592
void QuickSetupTriggerOff()
593
{
594
        //cbAcquireContinuous.Checked = false;
595
        DisableTriggers();
596
        SetHvOn(false);
597
        SetDetectorVaOn(false);
598
}
599
 
600
void ReadRegisters()
601
{
602
        if (deviceIndex < 0)
603
                return;
604
 
605
        // Voltages
606
        double lHvImon = GetHvCurrentInUa();
607
        double HvVmon = GetHvVoltage(ADDR_HV_VMON);
608
        double HvVmax = GetHvVoltage(ADDR_HV_MAX);
609
        double lDetPva = GetVoltage75(ADDR_BASE_PVA);
610
        double lDetNva = GetVoltage75(ADDR_BASE_NVA);
611
        double lPva = GetVoltage75(ADDR_MAIN_PVA);
612
        double lNva = GetVoltage75(ADDR_MAIN_NVA);
613
        double l12V = GetVoltage(ADDR_MAIN_P12);
614
        double l33V = GetVoltage75(ADDR_MAIN_P33);
615
        double l50V = GetVoltage75(ADDR_MAIN_P50);
616
        double Temperature = GetDetectorTemperature();
617
        double lRampRate = GetRampRate();
618
 
619
        // Integration time
620
        int lItime = GetIntegrationTime();
621
 
622
        // Buffer memory used
623
        int lBufferWords = ReadSD4Register(ADDR_BUFFERWORDS);
624
 
625
        // Offsets
626
        double  lOffset1 = GetAdcOffsetInMv(ADDR_OFFSET1);
627
        double  lOffset2 = GetAdcOffsetInMv(ADDR_OFFSET2);
628
        double  lOffset3 = GetAdcOffsetInMv(ADDR_OFFSET3);
629
        double  lOffset4 = GetAdcOffsetInMv(ADDR_OFFSET4);
630
        double  lSumOffset = GetSumOffsetInMv();
631
 
632
        // Main CSR
633
        int csrMain = ReadSD4Register(ADDR_CSR_MAIN);
634
        int lPvaStatus = GetBit(csrMain, BIT_CSR_MAIN_PVA);
635
        int lNvaStatus = GetBit(csrMain, BIT_CSR_MAIN_NVA);
636
        int l12vStatus = GetBit(csrMain, BIT_CSR_MAIN_P12);
637
        int l33vStatus = GetBit(csrMain, BIT_CSR_MAIN_P33);
638
        int l5vStatus = GetBit(csrMain, BIT_CSR_MAIN_P50);
639
 
640
        // Trigger CSR
641
        // Assumes only one trigger source is active
642
        char lTriggerSource[0xFF];
643
        int csrTrigger = ReadSD4Register(ADDR_CSR_TRIGGER);
644
        if (GetBit(csrTrigger, BIT_CSR_TRIG_CONTINUOUS))
645
                sprintf_s(lTriggerSource, 0xFF, "CONTINUOUS");
646
        else if (GetBit(csrTrigger, BIT_CSR_TRIG_BURST))
647
                sprintf_s(lTriggerSource, 0xFF, "BURST");
648
        else if (GetBit(csrTrigger, BIT_CSR_TRIG_DISCR))
649
                sprintf_s(lTriggerSource, 0xFF, "DISCRIMINATOR");
650
        else if (GetBit(csrTrigger, BIT_CSR_TRIG_EXTERNAL))
651
                sprintf_s(lTriggerSource, 0xFF, "EXTERNAL");
652
        else
653
                sprintf_s(lTriggerSource, 0xFF, "OFF");
654
 
655
        // Event ID CSR
656
        int csrEventId = ReadSD4Register(ADDR_EVENTID);
657
        int addTimeStamp = GetBit(csrEventId, BIT_EVENTID_TIME);
658
        int addEventCount = GetBit(csrEventId, BIT_EVENTID_COUNT);
659
        int addChannelNum = GetBit(csrEventId, BIT_EVENTID_CHNUM);
660
        //lTimeStamp.Text = addTimeStamp ? "+" : "";
661
        //lEventCount.Text = addEventCount ? "+" : "";
662
        //lChannelNum.Text = addChannelNum ? "+" : "";
663
 
664
        // Trigger generator
665
        int lTriggerInterval = ReadSD4Register32(ADDR_TG_INTERVALHI, ADDR_TG_INTERVALLO) * 10;
666
        int lTrigCount = ReadSD4Register32(ADDR_TG_COUNTHI, ADDR_TG_COUNTLO);
667
        ushort dum = 0;
668
        WriteSD4Register(ADDR_TC_COUNTLO, dum);         // latch counters by writing to any counter register
669
        int lTriggers = ReadSD4Register32(ADDR_TC_COUNTHI, ADDR_TC_COUNTLO);
670
        int lTriggerRate = ReadSD4Register32(ADDR_TC_RATEHI, ADDR_TC_RATELO);
671
        int lAdcConversions = ReadSD4Register32(ADDR_CONV_COUNTHI, ADDR_CONV_COUNTLO);
672
        double lThreshold = GetThreshold();
673
        double lHvIlimit = GetHvIlimitSetting();
674
        double lHvVoltage = GetHvVoltageSetting();
675
 
676
        // Detector CSR
677
        int csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
678
        int lHvEnabled = GetBit(csrDetector, BIT_CSR_DET_HVENABLE);
679
        int lHvOn = GetBit(csrDetector, BIT_CSR_DET_HVGOOD);
680
        int lSumCoupling = GetBit(csrDetector, BIT_CSR_DET_SUMCOUPLING);
681
        int lSumGain =
682
                ((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN4) ? 1 : 0) << 3) |
683
                ((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN3) ? 1 : 0) << 2) |
684
                ((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN2) ? 1 : 0) << 1) |
685
                ((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN1) ? 1 : 0) << 0);
686
        int lAdcCoupling = GetBit(csrDetector, BIT_CSR_DET_ADCCOUPLING);
687
        int lAdcGain = ((GetBit(csrDetector, BIT_CSR_DET_ADCGAIN2) ? 1 : 0) << 1) |
688
                ((GetBit(csrDetector, BIT_CSR_DET_ADCGAIN1) ? 1 : 0) << 0);
689
        int lAmpEnabled = GetBit(csrDetector, BIT_CSR_DET_VAENABLE);
690
        int lAmpLevel = GetBit(csrDetector, BIT_CSR_DET_VAHIRNG);
691
        int lDetPvaStatus = GetBit(csrDetector, BIT_CSR_DET_PVAGOOD);
692
        int lDetNvaStatus = GetBit(csrDetector, BIT_CSR_DET_NVAGOOD);
693
        int lTemperatureOn = GetBit(csrDetector, BIT_CSR_DET_TEMPVALID);
694
}
695
 
696
 
697
 
698
//----------------------------------------
699
// Message list
700
//----------------------------------------
701
 
702
void AddMessage(const char * message)
703
{
704
        printf("%s\n", message);
705
}
706
 
707
 
708
 
709
 
710
 
711
//----------------------------------------
712
// MDU Events
713
//----------------------------------------
714
 /*
715
private void AitDeviceAttached(object sender, EventArgs e)
716
{
717
        MduManager.DeviceChangedEventArgs aitEventArgs = e as MduManager.DeviceChangedEventArgs;
718
        AddMessage(String.Format("Attached : Index={0}, ID={1:X8}", aitEventArgs.DeviceIndex, aitEventArgs.DeviceId));
719
        UpdateDeviceList();
720
}
721
 
722
private void AitDeviceRemoved(object sender, EventArgs e)
723
{
724
        MduManager.DeviceChangedEventArgs aitEventArgs = e as MduManager.DeviceChangedEventArgs;
725
        AddMessage(String.Format("Removed : Index={0}, ID={1:X8}", aitEventArgs.DeviceIndex, aitEventArgs.DeviceId));
726
        UpdateDeviceList();
727
}
728
 
729
*/
730
 
731
//----------------------------------------
732
// Device Control
733
//----------------------------------------
734
 
735
int UpdateDeviceList()
736
{
737
 
738
        deviceIndex = -1;
739
        deviceId = 0;
740
        int deviceCount = 0;
741
        uint * devIds = SD4_GetDeviceList(&deviceCount);
742
        for (int i = 0; i < deviceCount; i++) {
743
                printf("Device %d = 0x%8x\n", i, devIds[i]);
744
                deviceId = devIds[i];
745
                deviceIndex =     i;
746
        }
747
        return deviceCount;
748
}
749
 
750
void ResetDevice()
751
{
752
        if (deviceIndex >= 0)
753
        {
754
                AddMessage(statusReset);
755
                SD4_ResetFpga(deviceIndex);
756
                Sleep(500);
757
                UpdateDeviceList();
758
                AddMessage(statusReset);
759
                AddMessage(statusDone);
760
        }
761
        else
762
                AddMessage(statusNoDevice);
763
}
764
 
765
void ReconnectDevice()
766
{
767
        if (deviceIndex >= 0)
768
        {
769
                AddMessage(statusReconnect);
770
                SD4_Reconnect(deviceIndex);
771
                Sleep(500);
772
                AddMessage(statusReconnect);
773
                AddMessage(statusDone);
774
        }
775
        else
776
                AddMessage(statusNoDevice);
777
}
778
 
779
void ReconfigureDevice()
780
{
781
        if (deviceIndex >= 0)
782
        {
783
                AddMessage(statusReconfig);
784
                SD4_Reconfigure(deviceIndex);
785
                Sleep(500);
786
                SD4_ResetFpga(deviceIndex);
787
                UpdateDeviceList();
788
                AddMessage(statusReconfig);
789
                AddMessage(statusDone);
790
        }
791
        else
792
                AddMessage(statusNoDevice);
793
}
794
 
795
//----------------------------------------
796
// Initialize Device Connection
797
//----------------------------------------
798
 
799
void InitializeConnection()
800
{
801
        int ndevices = 0;
802
        unsigned int * devlist = SD4_FindDevices(&ndevices);
803
        printf("Found %d devices\n", ndevices);
804
        //SD4.DeviceAttached += new EventHandler(AitDeviceAttached);
805
        //SD4.DeviceRemoved += new EventHandler(AitDeviceRemoved);
806
        //tscbDeviceList.SelectedIndexChanged += new EventHandler(tscbDeviceList_SelectedIndexChanged);
807
        printf("Updated devices %d\n", UpdateDeviceList());
808
}
809
 
810
 
811
const int CHANNELS = 4;                 // 4-Channel DAQ
812
const int ADCMAX = 4096;                // 12-bit ADC
813
 
814
bool addTimeStamp = false;              // updated by ReadRegisters
815
bool addEventCount = false;             // updated by ReadRegisters
816
bool addChannelNum = false;             // updated by ReadRegisters
817
 
818
int TIMESTAMP_LSB = 10;                 // 10ns time stamp resolution
819
 
820
 
821
 
822
int GetAdcEventSize()
823
{
824
        int eventSize = CHANNELS;
825
        if (addTimeStamp == true)
826
                eventSize += 3;         // 3 16-bit words for time stamp
827
        if (addEventCount == true)
828
                eventSize += 2;         // 2 16-bit words for event count
829
        return eventSize;
830
}
831
 
832
int GetEventPosition(int eventNum)
833
{
834
        int adcBoardEventSize = GetAdcEventSize();
835
        return adcBoardEventSize * eventNum;
836
}
837
 
838
ushort ExtractAdcData(int eventNum, int channel)
839
{
840
        int index = GetEventPosition(eventNum) + channel;
841
        return adcBuffer[index];
842
}
843
 
844
long ExtractTimeStamp(int eventNum)
845
{
846
        int index = GetEventPosition(eventNum) + CHANNELS;
847
        long timestamp = 0;
848
        for (int i = 0; i < 3; i++)
849
                timestamp = (timestamp << 16) | adcBuffer[index++];
850
        return timestamp;
851
}
852
 
853
int ExtractEventCount(int eventNum)
854
{
855
        int offset = 0;
856
        if (addTimeStamp == true)
857
                offset += 3;
858
        int index = GetEventPosition(eventNum) + CHANNELS + offset;
859
        int eventCount = adcBuffer[index];
860
        eventCount = (eventCount << 16) | adcBuffer[index + 1];
861
        return eventCount;
862
}
863
 
864
void ShowEvent(int eventNumber)
865
{
866
        if (eventNumber < 1)
867
                return;
868
        eventNumber--;
869
        char lAdcTimeStamp[0xFF];
870
        char lAdcAbsTimeStamp[0xFF];
871
        char lAdcEventCount[0xFF];
872
        //tbAdcData.Clear();
873
        int eventPosition = GetEventPosition(eventNumber);
874
        for (int channel = 0; channel < CHANNELS; channel++)
875
        {
876
                int data = ExtractAdcData(eventNumber, channel);
877
                printf(" 0:%d  1:%d ", channel + 1, data);
878
                if (channel < (CHANNELS - 1))
879
                        printf("\n");
880
        }
881
        if (addTimeStamp == true)
882
        {
883
                long reference = ExtractTimeStamp(0);
884
                long timeStamp = ExtractTimeStamp(eventNumber);
885
                sprintf_s(lAdcTimeStamp, 0xFF, "%d", ((timeStamp - reference) * TIMESTAMP_LSB));
886
                sprintf_s(lAdcAbsTimeStamp, 0xFF, "%d", (timeStamp * TIMESTAMP_LSB));
887
        }
888
        else
889
        {
890
                sprintf_s(lAdcTimeStamp, 0xFF, "%s", "----");
891
                sprintf_s(lAdcAbsTimeStamp, 0xFF, "%s", "----");
892
        }
893
        if (addEventCount == true)
894
        {
895
                sprintf_s(lAdcEventCount, 0xFF, "%d", ExtractEventCount(eventNumber));
896
        }
897
        else
898
        {
899
                sprintf_s(lAdcEventCount, 0xFF, "%s", "----");
900
        }
901
        //SetTextboxToTop(tbAdcData);
902
}
903
 
904
int Acquire(int events)
905
{
906
        // Acquire
907
        adcBufferLen = GetAdcEventSize() * events;
908
        //adcBuffer = new ushort[adcBufferLen];
909
 
910
        //int wordsAcquired = ReadAdcByteBuffer();              //  use only to test byte buffer read operation
911
        int wordsAcquired = ReadAdcBuffer();
912
        if (wordsAcquired != adcBufferLen)
913
        {
914
                char msg[0xFF];
915
                sprintf_s(msg, "ERROR: Timeout with possible data loss (%d/%d words received; Block Error = %d)", wordsAcquired, adcBufferLen, SD4_BlockError());
916
                AddMessage(msg);
917
                /*
918
                if (cbAcquireContinuous.Checked == true)
919
                {
920
                        cbAcquireContinuous.Checked = false;
921
                        AddMessage("Acquisition disabled");
922
                }
923
                */
924
        }
925
 
926
        // Update UI
927
        double blocksize = adcBufferLen * 2.0;
928
        double microseconds = SD4_BlockTransferTime();
929
        double transferRate = blocksize / microseconds;
930
        /*
931
        lTransferRate.Text = String.Format("{0:f2}", transferRate);
932
        lAcquisitionSize.Text = String.Format("{0:f2}", blocksize / 1e6);               // block size in MB
933
        lAcquisitionTime.Text = String.Format("{0:f2}", microseconds / 1e6);
934
        */
935
        return events;
936
}
937
 
938
void GetStatistics(int events)
939
{
940
        ushort rawAdcData = 0;
941
        ushort adcData = 0;
942
        int channelReceived = 0;
943
        int channelExpected = 0;
944
        bool includeSaturated = 0; // cbIncludeSaturated.Checked;
945
        ushort * max = new ushort[CHANNELS];
946
        ushort * min = new ushort[CHANNELS];
947
        ushort * average = new ushort[CHANNELS];
948
        int*  total = new int[CHANNELS];
949
        for (int i = 0; i < CHANNELS; i++)
950
        {
951
                min[i] = 0xFFFF;
952
                max[i] = 0;
953
                total[i] = 0;
954
        }
955
        for (int eventNum = 0; eventNum < events; eventNum++)
956
        {
957
                for (int channel = 0; channel < CHANNELS; channel++)
958
                {
959
                        rawAdcData = ExtractAdcData(eventNum, channel);
960
                        if (addChannelNum == true)
961
                        {
962
                                channelReceived = (rawAdcData >> 12) & 0xF;
963
                                channelExpected = (channel & 0xF);
964
                                if (channelReceived != channelExpected)
965
                                {
966
                                        char msg[0xFF];
967
                                        sprintf_s(msg, "ERROR in Event %d : Expected channel %d, received %d -ANALYSIS STOPPED", eventNum, channelExpected, channelReceived);
968
                                        AddMessage(msg);
969
                                        //EnableRegisterScanTimer(true);
970
                                        return;
971
                                }
972
                        }
973
                        adcData = (ushort)(rawAdcData & 0x0FFF);                // remove channel number
974
                        if ((includeSaturated == true) || ((includeSaturated == false) && (adcData < (ADCMAX - 2))))
975
                                histograms[channel][adcData]++;
976
                        total[channel] = total[channel] + adcData;
977
                        if (adcData > max[channel])
978
                                max[channel] = adcData;
979
                        else if (adcData < min[channel])
980
                                min[channel] = adcData;
981
                }
982
                histogramTotalEvents++;
983
        }
984
        //tbAdcStatistics.Clear();
985
        for (int channel = 0; channel < CHANNELS; channel++)
986
        {
987
                average[channel] = (ushort)(total[channel] / events);
988
                char msg[0xFF];
989
                sprintf_s(msg, " {0:%d}  : {1:0x%04x}  {2:0x%04x}  {3:0x%04x}  {4:0x%04x}", channel + 1, min[channel], max[channel], max[channel] - min[channel], average[channel]);
990
                //if (channel < (CHANNELS - 1))
991
          //      tbAdcStatistics.AppendText(Environment.NewLine);
992
                AddMessage(msg);
993
        }
994
        //SetTextboxToTop(tbAdcStatistics);
995
}
996
 
997
void SetupAcquisition(int neve)
998
{
999
        //EnableRegisterScanTimer(false);
1000
        //nudEventSelect.Minimum = 0;
1001
        //nudEventSelect.Maximum = 0;
1002
        int eventsAcquired = Acquire(neve);
1003
        if (eventsAcquired < 1)
1004
                return;
1005
        GetStatistics(eventsAcquired);
1006
        ShowEvent(1);
1007
        //ShowHistograms();
1008
        //nudEventSelect.Minimum = 1;
1009
        //nudEventSelect.Maximum = eventsAcquired;
1010
        //EnableRegisterScanTimer(true);
1011
}
1012
 
1013
int main(int argc, _TCHAR* argv[])
1014
//int _tmain(int argc, _TCHAR* argv[])
1015
{
1016
 
1017
 
1018
        NE_Rainbow();
1019
        //-----------------------------------
1020
        char bla[100] = "abcd";
1021
        NE_Ptr2ByteArray(bla, strlen(bla));
1022
        //-----------------------------------
1023
        char data[1000] = { 1,0,0,1,0,0,0,0,1,1,1,1 };
1024
        int len = 0;
1025
        //char *data=NULL;
1026
        int *retval = (int *)NE_ByteArray2Ptr(data, &len);
1027
        int *idata = (int*)data;
1028
        printf("***NE_ByteArray2Ptr %d\n", len);
1029
        for (int i = 0; i < len; i++) printf("%d %d %d\n", i, idata[i], retval[i]);
1030
        printf("\n");
1031
        //-----------------------------------
1032
        char data1[100] = "NE_Ptr2String";
1033
        NE_Ptr2String(data1, strlen(data1));
1034
        //-----------------------------------
1035
        char data2[100] = "abcd";
1036
        int nb = NE_String2Ptr(data2);
1037
        //-----------------------------------
1038
 
1039
        printf("result = %d %s\n", nb, bla);
1040
        printf("string = %s\n", NE_String());
1041
 
1042
        //-----------------------------------
1043
        unsigned int *n = NE_UInt(&len);
1044
        printf("NE_UInt size = %d\n", len);
1045
        for (int i = 0; i < len; i++) printf("%d\t", n[i]);
1046
        printf("\n");
1047
        //-----------------------------------
1048
 
1049
        int events = 1000;
1050
        adcBufferLen = GetAdcEventSize() * events;
1051
        //adcBuffer = new ushort[GetAdcEventSize() * events];
1052
        for (int i = 0; i < 0xFFF; i++) {
1053
                for (int j = 0; j < 4; j++) histograms[j][i] = 0;
1054
        }
1055
        histogramTotalEvents = 0;
1056
        InitializeConnection();
1057
        QuickSetupContinuous();
1058
        ReadRegisters();
1059
        SetupAcquisition(1);
1060
 
1061
        return 0;
1062
}