Subversion Repositories f9daq

Compare Revisions

No changes between revisions

Ignore whitespace Rev 212 → Rev 213

/cvi/instr/AitSipmDAQ/AitSipmDAQDll/.vs/AitSipmDAQ/v14/.suo
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitMduManager.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQ.VC.db
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQ.sln
0,0 → 1,47

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AitSipmDAQDll", "UnmanagedDllInterface\AitSipmDAQDll.csproj", "{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AitSipmDAQApp", "AitSipmDAQApp\AitSipmDAQApp.vcxproj", "{A133C14A-192C-49DA-936C-0BC2FB5EB54E}"
ProjectSection(ProjectDependencies) = postProject
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8} = {A9829616-449C-4F04-AFF1-B7D11F6ED0C8}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|Win32 = Debug|Win32
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Debug|Win32.ActiveCfg = Debug|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Release|Any CPU.Build.0 = Release|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}.Release|Win32.ActiveCfg = Release|Any CPU
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Debug|Any CPU.ActiveCfg = Debug|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Debug|Mixed Platforms.ActiveCfg = Debug|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Debug|Mixed Platforms.Build.0 = Debug|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Debug|Win32.ActiveCfg = Debug|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Debug|Win32.Build.0 = Debug|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Release|Any CPU.ActiveCfg = Release|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Release|Mixed Platforms.ActiveCfg = Release|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Release|Mixed Platforms.Build.0 = Release|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Release|Win32.ActiveCfg = Release|Win32
{A133C14A-192C-49DA-936C-0BC2FB5EB54E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitMduManager.dll
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitMduManager.h
0,0 → 1,48
#ifndef AITMDUMANAGER_H
#define AITMDUMANAGER_H
#define DLLIMPORT __declspec(dllimport)
#ifdef _CVI_
#include <stdbool.h>
#endif
#ifdef __cplusplus
extern "C"
{
#endif
 
DLLIMPORT int SD4_BlockError();
DLLIMPORT unsigned int SD4_GetBlockTimeout();
DLLIMPORT void SD4_SetBlockTimeout(unsigned int);
DLLIMPORT long SD4_BlockTransferTime();
DLLIMPORT unsigned int SD4_GetDriverTimeout();
DLLIMPORT void SD4_SetDriverTimeout(unsigned int);
DLLIMPORT char * SD4_Version();
DLLIMPORT int SD4_WordsTransferred();
 
DLLIMPORT unsigned int* SD4_FindDevices(int * ndevices);
DLLIMPORT int SD4_GetDeviceCount();
DLLIMPORT unsigned int* SD4_GetDeviceList(int * ndevices);
DLLIMPORT char * SD4_GetUsbFirmwareVersionByDevice(unsigned int deviceId);
DLLIMPORT char * SD4_GetUsbFirmwareVersion(int index);
DLLIMPORT bool SD4_IsDeviceAttached(unsigned int deviceId);
DLLIMPORT bool SD4_ProgramFpgaFirmwareByDevice(unsigned int deviceId, char * fpgaFirmware);
DLLIMPORT bool SD4_ProgramFpgaFirmware(int index, char* fpgaFirmware);
DLLIMPORT bool SD4_ProgramUsbFirmware(int index, char* usbFirmware);
DLLIMPORT unsigned short SD4_Read(unsigned int deviceId, int address);
DLLIMPORT char * SD4_ReadByteArray(unsigned int deviceId, int address, int requestedsize, int * elementsread);
DLLIMPORT unsigned short * SD4_ReadUShortArray(unsigned int deviceId, int address, int requestedsize, int * elementsread );
DLLIMPORT void SD4_ReconfigureByDevice(unsigned int deviceId);
DLLIMPORT void SD4_Reconfigure(int index);
DLLIMPORT void SD4_ReconnectByDevice(unsigned int deviceId);
DLLIMPORT void SD4_Reconnect(int index);
DLLIMPORT void SD4_ResetFpga(int index);
DLLIMPORT void SD4_ResetFpgaByDevice(unsigned int deviceId);
DLLIMPORT void SD4_ResetUsb(int index);
DLLIMPORT void SD4_ResetUsbByDevice(unsigned int deviceId);
DLLIMPORT void SD4_Write(unsigned int deviceId, int address, unsigned short data);
DLLIMPORT int SD4_WriteArray(unsigned int deviceId, int address, unsigned short* data);
#ifdef __cplusplus
}
#endif
#endif
 
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitMduManager.lib
Cannot display: file marked as a binary type.
svn:mime-type = application/octet-stream
Property changes:
Added: svn:mime-type
+application/octet-stream
\ No newline at end of property
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitMduManager_DEF.h
0,0 → 1,114
#ifndef AITMDUMANAGER_DEF_H
#define AITMDUMANAGER_DEF_H
 
// Registers 0-15 ( RESERVED - DO NOT ACCESS
 
 
//----------------------------------------
// ADC Controller Registers
//----------------------------------------
 
#define ADDR_BASE ( 16)
#define ADDR_CSR_MAIN ( ADDR_BASE + 0) // Main CSR
#define ADDR_BUFFER ( ADDR_BASE + 1) // ADC event buffer
#define ADDR_BUFFERWORDS ( ADDR_BASE + 2) // 16-bit words available in the ADC event buffer
#define ADDR_EVENTID ( ADDR_BASE + 3) // Event ID CSR
#define ADDR_CSR_DETECTOR ( ADDR_BASE + 4) // Detector interface CSR
#define ADDR_TTLPORT ( ADDR_BASE + 5) // TTL I/O port
#define ADDR_ITIME ( ADDR_BASE + 6) // Integration time
#define ADDR_CSR_TRIGGER ( ADDR_BASE + 7) // Trigger CSR
#define ADDR_DEADTIME ( ADDR_BASE + 8) // Trigger dead time
#define ADDR_TG_INTERVALHI ( ADDR_BASE + 9) // Internal trigger generator interval 31:16
#define ADDR_TG_INTERVALLO ( ADDR_BASE + 10) // Internal trigger generator interval 15:0
#define ADDR_TG_COUNTHI ( ADDR_BASE + 11) // Internal trigger generator burst count 31:16
#define ADDR_TG_COUNTLO ( ADDR_BASE + 12) // Internal trigger generator burst count 15:0
#define ADDR_TC_COUNTHI ( ADDR_BASE + 13) // Trigger count 31:16
#define ADDR_TC_COUNTLO ( ADDR_BASE + 14) // Trigger count 15:0
#define ADDR_TC_RATEHI ( ADDR_BASE + 15) // Trigger rate 31:16
#define ADDR_TC_RATELO ( ADDR_BASE + 16) // Trigger rate 15:0
#define ADDR_CONV_COUNTHI ( ADDR_BASE + 17) // ADC conversion count 31:16
#define ADDR_CONV_COUNTLO ( ADDR_BASE + 18) // ADC conversion count 15:0
#define ADDR_CONV_RATEHI ( ADDR_BASE + 19) // ADC conversion rate 31:16
#define ADDR_CONV_RATELO ( ADDR_BASE + 20) // ADC conversion rate 15:0
#define ADDR_DISCR_OFFSET ( ADDR_BASE + 21) // Discriminator offset
#define ADDR_DISCR_THRESHOLD ( ADDR_BASE + 22) // Discriminator threshold
#define ADDR_MAIN_P12 ( ADDR_BASE + 23) // Main +1.2V power supply monitor
#define ADDR_RESERVED2 ( ADDR_BASE + 24) // RESERVED
#define ADDR_MAIN_P33 ( ADDR_BASE + 25) // Main +3.3V power supply monitor
#define ADDR_MAIN_P50 ( ADDR_BASE + 26) // Main +5.0V power supply monitor
#define ADDR_MAIN_PVA ( ADDR_BASE + 27) // Main power supply +VA voltage monitor
#define ADDR_MAIN_NVA ( ADDR_BASE + 28) // Main power supply -VA voltage monitor
#define ADDR_HV_MAX ( ADDR_BASE + 29) // HV maximum allowable control voltage
#define ADDR_HV_RAMPRATE ( ADDR_BASE + 30) // HV ramp rate
#define ADDR_HV_CTRL ( ADDR_BASE + 31) // HV control voltage
#define ADDR_HV_ILIMIT ( ADDR_BASE + 32) // HV current limit
#define ADDR_HV_VMON ( ADDR_BASE + 33) // HV output current monitor
#define ADDR_HV_IMON ( ADDR_BASE + 34) // HV output voltage monitor
#define ADDR_BASE_TEMPERATURE ( ADDR_BASE + 35) // Base temperature monitor
#define ADDR_BASE_PVA ( ADDR_BASE + 36) // Base +VA power supply monitor
#define ADDR_BASE_NVA ( ADDR_BASE + 37) // Base -VA power supply monitor
#define ADDR_OFFSET1 ( ADDR_BASE + 38) // ADC offset 1
#define ADDR_OFFSET2 ( ADDR_BASE + 39) // ADC offset 2
#define ADDR_OFFSET3 ( ADDR_BASE + 40) // ADC offset 3
#define ADDR_OFFSET4 ( ADDR_BASE + 41) // ADC offset 4
 
 
//----------------------------------------
// Main CSR bits
//----------------------------------------
 
// bit 0 ( RESERVED
#define BIT_CSR_MAIN_P12 ( 1) // +1.2V power supply status
// bit 2 ( RESERVED
#define BIT_CSR_MAIN_P33 ( 3) // +3.3V power supply status
#define BIT_CSR_MAIN_P50 ( 4) // +5.0V power supply status
#define BIT_CSR_MAIN_PVA ( 5) // +VA power supply status
#define BIT_CSR_MAIN_NVA ( 6) // -VA power supply status
// bits 12:7 ( RESERVED
#define BIT_CSR_MAIN_BFULL ( 13) // ADC buffer full status
#define BIT_CSR_MAIN_BEMPTY ( 14) // ADC buffer empty status
#define BIT_CSR_MAIN_ADCRESET ( 15) // Reset ADC
 
 
//----------------------------------------
// Event ID CSR bits
//----------------------------------------
 
#define BIT_EVENTID_COUNT ( 0) // Add event count to each Event Block (0(no, 1(yes)
#define BIT_EVENTID_TIME ( 1) // Add time stamp to each Event Block (0(no, 1(yes)
#define BIT_EVENTID_CHNUM ( 2) // Add channel number to each ADC data word (0(no, 1(yes)
// bits 15:3 ( RESERVED
 
 
//----------------------------------------
// Detector interface CSR bits
//----------------------------------------
 
#define BIT_CSR_DET_VAENABLE ( 0) // Detector Module +/-VA enable (0 ( disable, 1 ( enable)
#define BIT_CSR_DET_VAHIRNG ( 1) // Detector Module +/-VA output range (0 ( low range, 1 ( high range)
#define BIT_CSR_DET_HVENABLE ( 2) // Detector Module HV power supply (0 ( disable, 1 ( enable)
#define BIT_CSR_DET_HVRESET ( 3) // Detector Module HV power supply fault reset (0 ( reset off, 1 ( reset on)
#define BIT_CSR_DET_SUMCOUPLING ( 4) // Sum input coupling (0 ( DC, 1 ( AC)
#define BIT_CSR_DET_SUMGAIN1 ( 5) // Sum gain switch 1 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_SUMGAIN2 ( 6) // Sum gain switch 2 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_SUMGAIN3 ( 7) // Sum gain switch 3 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_SUMGAIN4 ( 8) // Sum gain switch 4 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_ADCCOUPLING ( 9) // ADC input coupling (0 ( DC, 1 ( AC)
#define BIT_CSR_DET_ADCGAIN1 ( 10) // ADC gain switch 1 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_ADCGAIN2 ( 11) // ADC gain switch 2 (0 ( open, 1 ( closed)
#define BIT_CSR_DET_HVGOOD ( 12) // Detector Module HV status (0 ( fault, 1 ( good)
#define BIT_CSR_DET_PVAGOOD ( 13) // Detector Module VA status (0 ( fault, 1 ( good)
#define BIT_CSR_DET_NVAGOOD ( 14) // Detector Module VA status (0 ( fault, 1 ( good)
#define BIT_CSR_DET_TEMPVALID ( 15) // Detector Module temperature status (0 ( fault, 1 ( connected)
 
 
//----------------------------------------
// Trigger CSR bits
//----------------------------------------
 
#define BIT_CSR_TRIG_CONTINUOUS ( 0) // Internal continuous trigger (0(off, 1(on)
#define BIT_CSR_TRIG_BURST ( 1) // Internal burst trigger (0(off, 0(on)
#define BIT_CSR_TRIG_DISCR ( 2) // Discriminator trigger (0(off, 0(on)
#define BIT_CSR_TRIG_EXTERNAL ( 3) // External trigger (0(off, 0(on)
// bits 15:4 ( RESERVED
#endif
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitSipmDAQApp.cpp
0,0 → 1,1062
// NativeExportsConsumerApp.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <string.h>
#include <windows.h>
#include "AitMduManager.h"
#include "AitMduManager_DEF.h"
 
typedef unsigned short ushort;
typedef unsigned int uint;
 
extern "C"
{
DLLIMPORT void NE_Rainbow();
 
DLLIMPORT int NE_Func(int a);
DLLIMPORT int NE_Ptr2ByteArray(char *, int len);
DLLIMPORT char * NE_ByteArray2Ptr(char *, int *);
DLLIMPORT int NE_Ptr2String(char *, int len);
DLLIMPORT int NE_String2Ptr(char *);
DLLIMPORT char * NE_String();
DLLIMPORT unsigned int * NE_UInt(int *);
}
 
#ifdef _DEBUG
#pragma comment(lib, "../UnmanagedDllInterface/bin/Debug/AitSipmDAQDll.lib")
#else
#pragma comment(lib, "../UnmanagedDllInterface/bin/Release/AitSipmDAQDll.lib")
#endif
 
uint deviceId = 0;
int deviceIndex = -1;
int adcBufferLen;
ushort * adcBuffer;
int histograms[4][0xFFF];
int histogramTotalEvents = 0;
 
const double MONADC_SCALE = 65535.0; // 16-bit monitor ADC
const double DAC_SCALE = 65535.0; // 16-bit DAC
const double MONADC_VRANGE = 2.5; // 2.5V ADC voltage range
const double DISCR_OFFSETRANGE = 250.0; // +/- 250mV discriminator offset range
const double DISCR_THRESHOLDRANGE = 1000.0; // 0-1000mV discriminator threshold range
const double HV_IRANGE = 5.0; // 0-5.0mA HV current monitor range
const double HV_VRANGE = 80.0; // 0-80V HV voltage control range
const int INTEGRATOR_LSB = 10; // 10ns integrator time resolution
const double RAMPRATESCALE = 61036.0; // Ramp rate register setting = (rate in V/s) / RAMPRATESCALE
const char statusNoDevice[0xFF] = "No Device Connected";
const char statusReconfig[0xFF] = "Reconfiguring Device ... ";
const char statusReset[0xFF] = "Resetting Device ... ";
const char statusReconnect[0xFF] = "Reconnecting Device ... ";
const char statusDone[0xFF] = "Done";
 
/*
void Sleep(int musec) {
 
}
*/
 
//----------------------------------------
// Utilities
//----------------------------------------
ushort SetBit(ushort data, int bitIndex, bool bitValue)
{
if (bitValue == true)
return (ushort)(data | (1 << bitIndex));
else
return (ushort)(data & ~(1 << bitIndex));
}
 
bool GetBit(int data, int bitIndex)
{
return (data & (1 << bitIndex)) != 0;
}
 
ushort ReadSD4Register(int reg)
{
return SD4_Read(deviceId, reg);
}
 
uint ReadSD4Register32(int addrHi, int addrLo)
{
uint dataHi = (uint)SD4_Read(deviceId, addrHi);
uint dataLo = (uint)SD4_Read(deviceId, addrLo);
return (dataHi << 16) | dataLo;
}
 
void WriteSD4Register(int address, ushort data)
{
SD4_Write(deviceId, address, data);
}
 
void WriteSD4Register32(int addrHi, int addrLo, uint data)
{
WriteSD4Register(addrHi, (ushort)(data >> 16));
WriteSD4Register(addrLo, (ushort)data);
}
 
 
void ReadModifyWrite(int reg, int bitIndex, bool bitValue)
{
ushort regData = ReadSD4Register(reg);
regData = SetBit(regData, bitIndex, bitValue);
WriteSD4Register(reg, regData);
}
 
double LimitSetting(double value, double min, double max)
{
double limited = value;
if (limited > max) limited = max;
if (limited < min) limited = min;
return limited;
}
 
 
 
int ReadAdcBuffer()
{
//if (adcBuffer == NULL)
// return -1;
int bytes = 0;
//printf("In\n%d\n%d\n%d\n", deviceId, ADDR_BUFFER, adcBufferLen);
adcBuffer = SD4_ReadUShortArray(deviceId, ADDR_BUFFER, adcBufferLen, &bytes);
return bytes;
}
// Equivalent to ReadAdcBuffer() except using byte buffer for acquisition
int ReadAdcByteBuffer()
{
if (adcBuffer == NULL)
return -1;
int bytes = 0;
char * byteBuffer = SD4_ReadByteArray(deviceId, ADDR_BUFFER, adcBufferLen * 2, &bytes);
int byteIndex = 0;
int words = bytes / 2;
ushort dataword = 0;
for (int i = 0; i < words; i++)
{
dataword = (ushort)(byteBuffer[byteIndex++] << 8);
adcBuffer[i] = (ushort)(dataword | byteBuffer[byteIndex++]);
}
return words;
}
 
 
 
 
 
 
//----------------------------------------
// Monitor ADC
//----------------------------------------
 
double GetVoltage(int reg)
{
return ReadSD4Register(reg) * MONADC_VRANGE / MONADC_SCALE;
}
 
double GetDetectorTemperature()
{
// Temperature = 500mV + 1mV per degree C
return (GetVoltage(ADDR_BASE_TEMPERATURE) - 0.5) / 0.01;
}
 
double GetHvVoltage(int reg)
{
return GetVoltage(reg) / MONADC_VRANGE * HV_VRANGE;
}
 
double GetHvCurrentInUa()
{
// 2.5V ADC input voltage = 5000 microamps
return GetVoltage(ADDR_HV_IMON) * 2000.0;
}
 
double GetVoltage75(int reg)
{
// 2.5V ADC input voltage = 7.5V monitor voltage
return GetVoltage(reg) * 3.0;
}
 
 
 
//----------------------------------------
// Discriminator, Sum
//----------------------------------------
 
void SetSumGain(int gain)
{
ushort csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
bool g1 = GetBit(gain, 0);
bool g2 = GetBit(gain, 1);
bool g3 = GetBit(gain, 2);
bool g4 = GetBit(gain, 3);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN1, g1);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN2, g2);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN3, g3);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_SUMGAIN4, g4);
WriteSD4Register(ADDR_CSR_DETECTOR, (ushort)csrDetector);
}
 
void SetSumCoupling(bool acCoupling)
{
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_SUMCOUPLING, acCoupling);
}
 
void SetThreshold(double thresholdInMillivolts)
{
thresholdInMillivolts = LimitSetting(thresholdInMillivolts, -DISCR_THRESHOLDRANGE, DISCR_THRESHOLDRANGE);
WriteSD4Register(ADDR_DISCR_THRESHOLD, (ushort)(thresholdInMillivolts * DAC_SCALE / DISCR_THRESHOLDRANGE));
}
 
double GetThreshold()
{
return ReadSD4Register(ADDR_DISCR_THRESHOLD) / DAC_SCALE * DISCR_THRESHOLDRANGE;
}
 
double GetSumOffsetInMv()
{
// Sum offsets are with respect to the positive sum output polarity.
return (ReadSD4Register(ADDR_DISCR_OFFSET) / DAC_SCALE * (DISCR_OFFSETRANGE * 2)) - DISCR_OFFSETRANGE;
}
 
void SetSumOffset(double milliVolts)
{
// Sum offsets are with respect to the positive sum output polarity.
// Actual output offset is multiplied by the selectable gain stage.
WriteSD4Register(ADDR_DISCR_OFFSET, (ushort)((milliVolts + DISCR_OFFSETRANGE) * DAC_SCALE / (DISCR_OFFSETRANGE * 2)));
}
 
 
 
//----------------------------------------
// Trigger
//----------------------------------------
 
void SetTriggerInterval(int triggerInterval)
{
WriteSD4Register32(ADDR_TG_INTERVALHI, ADDR_TG_INTERVALLO, (uint)(triggerInterval / INTEGRATOR_LSB));
}
 
void SetTriggerBurst(int triggerBurst)
{
WriteSD4Register32(ADDR_TG_COUNTHI, ADDR_TG_COUNTLO, (uint)triggerBurst);
}
 
void EnableTrigger(int bitIndex)
{
WriteSD4Register(ADDR_CSR_TRIGGER, SetBit(0, bitIndex, true));
}
 
void DisableTriggers()
{
WriteSD4Register(ADDR_CSR_TRIGGER, 0);
}
 
void SetDeadTime(int deadTimeInNs)
{
WriteSD4Register(ADDR_DEADTIME, (ushort)(deadTimeInNs / INTEGRATOR_LSB));
}
 
 
 
//----------------------------------------
// Integrators, ADCs
//----------------------------------------
 
void SetIntegrationTime(int integrationTime)
{
WriteSD4Register(ADDR_ITIME, (ushort)(integrationTime / INTEGRATOR_LSB));
}
 
int GetIntegrationTime()
{
return ReadSD4Register(ADDR_ITIME) * INTEGRATOR_LSB;
}
 
void SetAdcCoupling(bool acCoupling)
{
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_ADCCOUPLING, acCoupling);
}
 
void ResetAdc(bool reset)
{
ushort cmd = 0;
cmd = SetBit(cmd, BIT_CSR_MAIN_ADCRESET, reset);
WriteSD4Register(ADDR_CSR_MAIN, cmd);
}
 
double GetAdcOffsetInMv(int reg)
{
// ADC offset polarity is with respect to the positive ADC polarity (integrator output), not the main negative input signal polarity.
// Actual output offset is multiplied by the selectable gain stage.
return DISCR_OFFSETRANGE - (ReadSD4Register(reg) / DAC_SCALE * (DISCR_OFFSETRANGE * 2));
}
 
void SetAdcOffset(int reg, double milliVolts)
{
// ADC offset polarity is with respect to the positive ADC polarity (integrator output), not the main negative input signal polarity.
// Actual output offset is multiplied by the selectable gain stage.
WriteSD4Register(reg, (ushort)((DISCR_OFFSETRANGE - milliVolts) * DAC_SCALE / (DISCR_OFFSETRANGE * 2)));
}
 
 
 
//----------------------------------------
// Event ID
//----------------------------------------
 
void AddEventCount(bool addEventCount)
{
ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_COUNT, addEventCount);
}
 
void AddTimeStamp(bool addTimeStamp)
{
ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_TIME, addTimeStamp);
}
 
void AddChannelNumber(bool addChannelNumber)
{
ReadModifyWrite(ADDR_EVENTID, BIT_EVENTID_CHNUM, addChannelNumber);
}
 
 
 
//----------------------------------------
// Detector VA
//----------------------------------------
 
void SetDetectorVaOn(bool on)
{
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_VAENABLE, on);
}
 
void SetDetectorVaHiRange(bool range)
{
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_VAHIRNG, range);
}
 
 
 
//----------------------------------------
// High Voltage
//----------------------------------------
 
void SetHvCurrentLimit(double milliamps)
{
milliamps = LimitSetting(milliamps, 0, HV_IRANGE);
WriteSD4Register(ADDR_HV_ILIMIT, (ushort)(milliamps * DAC_SCALE / HV_IRANGE));
}
 
void SetHvVoltage(int reg, double volts)
{
volts = LimitSetting(volts, 0, HV_VRANGE);
WriteSD4Register(reg, (ushort)(volts * DAC_SCALE / HV_VRANGE));
}
 
double GetHvIlimitSetting()
{
return ReadSD4Register(ADDR_HV_ILIMIT) / DAC_SCALE * HV_IRANGE;
}
 
double GetHvVoltageSetting()
{
return ReadSD4Register(ADDR_HV_CTRL) / DAC_SCALE * HV_VRANGE;
}
 
void SetHvOn(bool hvOn)
{
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVENABLE, hvOn);
}
 
void SetMaximumHvSetting(double volts)
{
SetHvVoltage(ADDR_HV_MAX, volts);
}
 
void CycleHvReset()
{
// CAUTION: Holding HV in reset will force it to ignore the current limit
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVRESET, true);
ReadModifyWrite(ADDR_CSR_DETECTOR, BIT_CSR_DET_HVRESET, false);
}
 
void SetRampRate(double voltsPerSecond)
{
WriteSD4Register(ADDR_HV_RAMPRATE, (ushort)(RAMPRATESCALE / voltsPerSecond));
}
 
double GetRampRate()
{
return RAMPRATESCALE / (ReadSD4Register(ADDR_HV_RAMPRATE) + 1);
}
 
void SetAdcGain(int gain)
{
ushort csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
bool g1 = GetBit(gain, 0);
bool g2 = GetBit(gain, 1);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_ADCGAIN1, g1);
csrDetector = SetBit(csrDetector, BIT_CSR_DET_ADCGAIN2, g2);
WriteSD4Register(ADDR_CSR_DETECTOR, (ushort)csrDetector);
}
 
void SetAdcOffsets(int offsetInMv)
{
//nudOffset1.Value = offsetInMv;
//nudOffset2.Value = offsetInMv;
//nudOffset3.Value = offsetInMv;
//nudOffset4.Value = offsetInMv;
SetAdcOffset(ADDR_OFFSET1, offsetInMv);
SetAdcOffset(ADDR_OFFSET2, offsetInMv);
SetAdcOffset(ADDR_OFFSET3, offsetInMv);
SetAdcOffset(ADDR_OFFSET4, offsetInMv);
}
 
void QuickSetupContinuous()
{
// Set ADC reset
ResetAdc(true);
 
// Clear ADC reset
ResetAdc(false);
 
// Set trigger dead time to 200ns
SetDeadTime(200);
 
// Set event ID
AddTimeStamp(true);
AddEventCount(true);
AddChannelNumber(true);
 
// Enable detector amplifier voltage
SetDetectorVaHiRange(false);
SetDetectorVaOn(true);
 
/*
// Set HV current limit
double iLimit = 2.5;
nudHvIlimit.Value = (decimal)iLimit;
SetHvCurrentLimit(iLimit);
 
// Reset any HV faults
CycleHvReset();
 
// Enable bias voltage
SetHvOn(false);
SetHvOn(true);
 
// Set bias voltage
double hvVoltage = 30.0;
nudHvVoltage.Value = (decimal)hvVoltage;
SetHvVoltage(ADDR_HV_CTRL, hvVoltage);
*/
 
// Set integration time
int integrationTime = 350;
//nudIntegrationTime.Value = integrationTime;
SetIntegrationTime(integrationTime);
 
// Set discriminator threshold
int threshold = 50;
//nudThreshold.Value = threshold;
SetThreshold(threshold);
 
// Set sum coupling
SetSumCoupling(true);
 
// Set sum gain
int sumGain = 3;
//nudSumGain.Value = sumGain;
SetSumGain(sumGain);
 
// Set sum offset
int offset = 0;
//nudSumOffset.Value = offset;
SetSumOffset(offset);
 
// Set ADC coupling
SetAdcCoupling(false);
 
// Set ADC gains
int gain = 1;
//nudAdcGain.Value = gain;
SetAdcGain(gain);
 
// Set all ADC offsets
SetAdcOffsets(5);
 
// Set internal trigger interval
int triggerInterval = 1000;
//nudTriggerInterval.Value = triggerInterval;
SetTriggerInterval(triggerInterval);
 
// Enable continuous trigger
EnableTrigger(BIT_CSR_TRIG_CONTINUOUS);
 
// Begin continuous acquisition
//nudEventsPerAcquisition.Value = 50000;
//cbAcquireContinuous.Checked = true;
 
// Update histogram offsets
//SetAllHistogramOffsets(0);
}
 
 
void QuickSetupDiscriminator()
{
// Set ADC reset
ResetAdc(true);
 
// Clear ADC reset
ResetAdc(false);
 
// Set trigger dead time to 300ns
SetDeadTime(500);
 
// Set event ID
AddTimeStamp(true);
AddEventCount(true);
AddChannelNumber(true);
 
// Enable detector amplifier voltage
SetDetectorVaHiRange(true);
SetDetectorVaOn(true);
 
// Set HV current limit
double iLimit = 2.5;
//nudHvIlimit.Value = (decimal)iLimit;
SetHvCurrentLimit(iLimit);
 
// Reset any HV faults
CycleHvReset();
 
// Enable bias voltage
SetHvOn(false);
SetHvOn(true);
 
// Set bias voltage
double hvVoltage = 30.0;
//nudHvVoltage.Value = (decimal)hvVoltage;
SetHvVoltage(ADDR_HV_CTRL, hvVoltage);
 
// Set integration time
int integrationTime = 350;
//nudIntegrationTime.Value = integrationTime;
SetIntegrationTime(integrationTime);
 
// Set discriminator threshold
int threshold = 50;
//nudThreshold.Value = threshold;
SetThreshold(threshold);
 
// Set sum coupling
SetSumCoupling(true);
 
// Set sum gain
int sumGain = 3;
//nudSumGain.Value = sumGain;
SetSumGain(sumGain);
 
// Set sum offset
int offset = 0;
//nudSumOffset.Value = offset;
SetSumOffset(offset);
 
// Set ADC coupling
SetAdcCoupling(false);
 
// Set ADC gains
int gain = 1;
//nudAdcGain.Value = gain;
SetAdcGain(gain);
 
// Set all ADC offsets
SetAdcOffsets(5);
 
// Clear histograms
//ClearHistograms();
 
// Enable discriminator trigger
EnableTrigger(BIT_CSR_TRIG_DISCR);
 
// Begin continuous acquisition
//nudEventsPerAcquisition.Value = 1000;
//cbAcquireContinuous.Checked = true;
 
// Update histogram offsets
//SetAllHistogramOffsets(0);
}
 
void QuickSetupTriggerOff()
{
//cbAcquireContinuous.Checked = false;
DisableTriggers();
SetHvOn(false);
SetDetectorVaOn(false);
}
 
void ReadRegisters()
{
if (deviceIndex < 0)
return;
 
// Voltages
double lHvImon = GetHvCurrentInUa();
double HvVmon = GetHvVoltage(ADDR_HV_VMON);
double HvVmax = GetHvVoltage(ADDR_HV_MAX);
double lDetPva = GetVoltage75(ADDR_BASE_PVA);
double lDetNva = GetVoltage75(ADDR_BASE_NVA);
double lPva = GetVoltage75(ADDR_MAIN_PVA);
double lNva = GetVoltage75(ADDR_MAIN_NVA);
double l12V = GetVoltage(ADDR_MAIN_P12);
double l33V = GetVoltage75(ADDR_MAIN_P33);
double l50V = GetVoltage75(ADDR_MAIN_P50);
double Temperature = GetDetectorTemperature();
double lRampRate = GetRampRate();
 
// Integration time
int lItime = GetIntegrationTime();
 
// Buffer memory used
int lBufferWords = ReadSD4Register(ADDR_BUFFERWORDS);
 
// Offsets
double lOffset1 = GetAdcOffsetInMv(ADDR_OFFSET1);
double lOffset2 = GetAdcOffsetInMv(ADDR_OFFSET2);
double lOffset3 = GetAdcOffsetInMv(ADDR_OFFSET3);
double lOffset4 = GetAdcOffsetInMv(ADDR_OFFSET4);
double lSumOffset = GetSumOffsetInMv();
 
// Main CSR
int csrMain = ReadSD4Register(ADDR_CSR_MAIN);
int lPvaStatus = GetBit(csrMain, BIT_CSR_MAIN_PVA);
int lNvaStatus = GetBit(csrMain, BIT_CSR_MAIN_NVA);
int l12vStatus = GetBit(csrMain, BIT_CSR_MAIN_P12);
int l33vStatus = GetBit(csrMain, BIT_CSR_MAIN_P33);
int l5vStatus = GetBit(csrMain, BIT_CSR_MAIN_P50);
 
// Trigger CSR
// Assumes only one trigger source is active
char lTriggerSource[0xFF];
int csrTrigger = ReadSD4Register(ADDR_CSR_TRIGGER);
if (GetBit(csrTrigger, BIT_CSR_TRIG_CONTINUOUS))
sprintf_s(lTriggerSource, 0xFF, "CONTINUOUS");
else if (GetBit(csrTrigger, BIT_CSR_TRIG_BURST))
sprintf_s(lTriggerSource, 0xFF, "BURST");
else if (GetBit(csrTrigger, BIT_CSR_TRIG_DISCR))
sprintf_s(lTriggerSource, 0xFF, "DISCRIMINATOR");
else if (GetBit(csrTrigger, BIT_CSR_TRIG_EXTERNAL))
sprintf_s(lTriggerSource, 0xFF, "EXTERNAL");
else
sprintf_s(lTriggerSource, 0xFF, "OFF");
 
// Event ID CSR
int csrEventId = ReadSD4Register(ADDR_EVENTID);
int addTimeStamp = GetBit(csrEventId, BIT_EVENTID_TIME);
int addEventCount = GetBit(csrEventId, BIT_EVENTID_COUNT);
int addChannelNum = GetBit(csrEventId, BIT_EVENTID_CHNUM);
//lTimeStamp.Text = addTimeStamp ? "+" : "";
//lEventCount.Text = addEventCount ? "+" : "";
//lChannelNum.Text = addChannelNum ? "+" : "";
 
// Trigger generator
int lTriggerInterval = ReadSD4Register32(ADDR_TG_INTERVALHI, ADDR_TG_INTERVALLO) * 10;
int lTrigCount = ReadSD4Register32(ADDR_TG_COUNTHI, ADDR_TG_COUNTLO);
ushort dum = 0;
WriteSD4Register(ADDR_TC_COUNTLO, dum); // latch counters by writing to any counter register
int lTriggers = ReadSD4Register32(ADDR_TC_COUNTHI, ADDR_TC_COUNTLO);
int lTriggerRate = ReadSD4Register32(ADDR_TC_RATEHI, ADDR_TC_RATELO);
int lAdcConversions = ReadSD4Register32(ADDR_CONV_COUNTHI, ADDR_CONV_COUNTLO);
double lThreshold = GetThreshold();
double lHvIlimit = GetHvIlimitSetting();
double lHvVoltage = GetHvVoltageSetting();
 
// Detector CSR
int csrDetector = ReadSD4Register(ADDR_CSR_DETECTOR);
int lHvEnabled = GetBit(csrDetector, BIT_CSR_DET_HVENABLE);
int lHvOn = GetBit(csrDetector, BIT_CSR_DET_HVGOOD);
int lSumCoupling = GetBit(csrDetector, BIT_CSR_DET_SUMCOUPLING);
int lSumGain =
((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN4) ? 1 : 0) << 3) |
((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN3) ? 1 : 0) << 2) |
((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN2) ? 1 : 0) << 1) |
((GetBit(csrDetector, BIT_CSR_DET_SUMGAIN1) ? 1 : 0) << 0);
int lAdcCoupling = GetBit(csrDetector, BIT_CSR_DET_ADCCOUPLING);
int lAdcGain = ((GetBit(csrDetector, BIT_CSR_DET_ADCGAIN2) ? 1 : 0) << 1) |
((GetBit(csrDetector, BIT_CSR_DET_ADCGAIN1) ? 1 : 0) << 0);
int lAmpEnabled = GetBit(csrDetector, BIT_CSR_DET_VAENABLE);
int lAmpLevel = GetBit(csrDetector, BIT_CSR_DET_VAHIRNG);
int lDetPvaStatus = GetBit(csrDetector, BIT_CSR_DET_PVAGOOD);
int lDetNvaStatus = GetBit(csrDetector, BIT_CSR_DET_NVAGOOD);
int lTemperatureOn = GetBit(csrDetector, BIT_CSR_DET_TEMPVALID);
}
 
 
 
//----------------------------------------
// Message list
//----------------------------------------
 
void AddMessage(const char * message)
{
printf("%s\n", message);
}
 
 
 
 
 
//----------------------------------------
// MDU Events
//----------------------------------------
/*
private void AitDeviceAttached(object sender, EventArgs e)
{
MduManager.DeviceChangedEventArgs aitEventArgs = e as MduManager.DeviceChangedEventArgs;
AddMessage(String.Format("Attached : Index={0}, ID={1:X8}", aitEventArgs.DeviceIndex, aitEventArgs.DeviceId));
UpdateDeviceList();
}
 
private void AitDeviceRemoved(object sender, EventArgs e)
{
MduManager.DeviceChangedEventArgs aitEventArgs = e as MduManager.DeviceChangedEventArgs;
AddMessage(String.Format("Removed : Index={0}, ID={1:X8}", aitEventArgs.DeviceIndex, aitEventArgs.DeviceId));
UpdateDeviceList();
}
 
*/
 
//----------------------------------------
// Device Control
//----------------------------------------
 
int UpdateDeviceList()
{
deviceIndex = -1;
deviceId = 0;
int deviceCount = 0;
uint * devIds = SD4_GetDeviceList(&deviceCount);
for (int i = 0; i < deviceCount; i++) {
printf("Device %d = 0x%8x\n", i, devIds[i]);
deviceId = devIds[i];
deviceIndex = i;
}
return deviceCount;
}
 
void ResetDevice()
{
if (deviceIndex >= 0)
{
AddMessage(statusReset);
SD4_ResetFpga(deviceIndex);
Sleep(500);
UpdateDeviceList();
AddMessage(statusReset);
AddMessage(statusDone);
}
else
AddMessage(statusNoDevice);
}
 
void ReconnectDevice()
{
if (deviceIndex >= 0)
{
AddMessage(statusReconnect);
SD4_Reconnect(deviceIndex);
Sleep(500);
AddMessage(statusReconnect);
AddMessage(statusDone);
}
else
AddMessage(statusNoDevice);
}
 
void ReconfigureDevice()
{
if (deviceIndex >= 0)
{
AddMessage(statusReconfig);
SD4_Reconfigure(deviceIndex);
Sleep(500);
SD4_ResetFpga(deviceIndex);
UpdateDeviceList();
AddMessage(statusReconfig);
AddMessage(statusDone);
}
else
AddMessage(statusNoDevice);
}
 
//----------------------------------------
// Initialize Device Connection
//----------------------------------------
 
void InitializeConnection()
{
int ndevices = 0;
unsigned int * devlist = SD4_FindDevices(&ndevices);
printf("Found %d devices\n", ndevices);
//SD4.DeviceAttached += new EventHandler(AitDeviceAttached);
//SD4.DeviceRemoved += new EventHandler(AitDeviceRemoved);
//tscbDeviceList.SelectedIndexChanged += new EventHandler(tscbDeviceList_SelectedIndexChanged);
printf("Updated devices %d\n", UpdateDeviceList());
}
 
 
const int CHANNELS = 4; // 4-Channel DAQ
const int ADCMAX = 4096; // 12-bit ADC
 
bool addTimeStamp = false; // updated by ReadRegisters
bool addEventCount = false; // updated by ReadRegisters
bool addChannelNum = false; // updated by ReadRegisters
 
int TIMESTAMP_LSB = 10; // 10ns time stamp resolution
 
 
 
int GetAdcEventSize()
{
int eventSize = CHANNELS;
if (addTimeStamp == true)
eventSize += 3; // 3 16-bit words for time stamp
if (addEventCount == true)
eventSize += 2; // 2 16-bit words for event count
return eventSize;
}
 
int GetEventPosition(int eventNum)
{
int adcBoardEventSize = GetAdcEventSize();
return adcBoardEventSize * eventNum;
}
 
ushort ExtractAdcData(int eventNum, int channel)
{
int index = GetEventPosition(eventNum) + channel;
return adcBuffer[index];
}
 
long ExtractTimeStamp(int eventNum)
{
int index = GetEventPosition(eventNum) + CHANNELS;
long timestamp = 0;
for (int i = 0; i < 3; i++)
timestamp = (timestamp << 16) | adcBuffer[index++];
return timestamp;
}
 
int ExtractEventCount(int eventNum)
{
int offset = 0;
if (addTimeStamp == true)
offset += 3;
int index = GetEventPosition(eventNum) + CHANNELS + offset;
int eventCount = adcBuffer[index];
eventCount = (eventCount << 16) | adcBuffer[index + 1];
return eventCount;
}
 
void ShowEvent(int eventNumber)
{
if (eventNumber < 1)
return;
eventNumber--;
char lAdcTimeStamp[0xFF];
char lAdcAbsTimeStamp[0xFF];
char lAdcEventCount[0xFF];
//tbAdcData.Clear();
int eventPosition = GetEventPosition(eventNumber);
for (int channel = 0; channel < CHANNELS; channel++)
{
int data = ExtractAdcData(eventNumber, channel);
printf(" 0:%d 1:%d ", channel + 1, data);
if (channel < (CHANNELS - 1))
printf("\n");
}
if (addTimeStamp == true)
{
long reference = ExtractTimeStamp(0);
long timeStamp = ExtractTimeStamp(eventNumber);
sprintf_s(lAdcTimeStamp, 0xFF, "%d", ((timeStamp - reference) * TIMESTAMP_LSB));
sprintf_s(lAdcAbsTimeStamp, 0xFF, "%d", (timeStamp * TIMESTAMP_LSB));
}
else
{
sprintf_s(lAdcTimeStamp, 0xFF, "%s", "----");
sprintf_s(lAdcAbsTimeStamp, 0xFF, "%s", "----");
}
if (addEventCount == true)
{
sprintf_s(lAdcEventCount, 0xFF, "%d", ExtractEventCount(eventNumber));
}
else
{
sprintf_s(lAdcEventCount, 0xFF, "%s", "----");
}
//SetTextboxToTop(tbAdcData);
}
 
int Acquire(int events)
{
// Acquire
adcBufferLen = GetAdcEventSize() * events;
//adcBuffer = new ushort[adcBufferLen];
 
//int wordsAcquired = ReadAdcByteBuffer(); // use only to test byte buffer read operation
int wordsAcquired = ReadAdcBuffer();
if (wordsAcquired != adcBufferLen)
{
char msg[0xFF];
sprintf_s(msg, "ERROR: Timeout with possible data loss (%d/%d words received; Block Error = %d)", wordsAcquired, adcBufferLen, SD4_BlockError());
AddMessage(msg);
/*
if (cbAcquireContinuous.Checked == true)
{
cbAcquireContinuous.Checked = false;
AddMessage("Acquisition disabled");
}
*/
}
 
// Update UI
double blocksize = adcBufferLen * 2.0;
double microseconds = SD4_BlockTransferTime();
double transferRate = blocksize / microseconds;
/*
lTransferRate.Text = String.Format("{0:f2}", transferRate);
lAcquisitionSize.Text = String.Format("{0:f2}", blocksize / 1e6); // block size in MB
lAcquisitionTime.Text = String.Format("{0:f2}", microseconds / 1e6);
*/
return events;
}
 
void GetStatistics(int events)
{
ushort rawAdcData = 0;
ushort adcData = 0;
int channelReceived = 0;
int channelExpected = 0;
bool includeSaturated = 0; // cbIncludeSaturated.Checked;
ushort * max = new ushort[CHANNELS];
ushort * min = new ushort[CHANNELS];
ushort * average = new ushort[CHANNELS];
int* total = new int[CHANNELS];
for (int i = 0; i < CHANNELS; i++)
{
min[i] = 0xFFFF;
max[i] = 0;
total[i] = 0;
}
for (int eventNum = 0; eventNum < events; eventNum++)
{
for (int channel = 0; channel < CHANNELS; channel++)
{
rawAdcData = ExtractAdcData(eventNum, channel);
if (addChannelNum == true)
{
channelReceived = (rawAdcData >> 12) & 0xF;
channelExpected = (channel & 0xF);
if (channelReceived != channelExpected)
{
char msg[0xFF];
sprintf_s(msg, "ERROR in Event %d : Expected channel %d, received %d -ANALYSIS STOPPED", eventNum, channelExpected, channelReceived);
AddMessage(msg);
//EnableRegisterScanTimer(true);
return;
}
}
adcData = (ushort)(rawAdcData & 0x0FFF); // remove channel number
if ((includeSaturated == true) || ((includeSaturated == false) && (adcData < (ADCMAX - 2))))
histograms[channel][adcData]++;
total[channel] = total[channel] + adcData;
if (adcData > max[channel])
max[channel] = adcData;
else if (adcData < min[channel])
min[channel] = adcData;
}
histogramTotalEvents++;
}
//tbAdcStatistics.Clear();
for (int channel = 0; channel < CHANNELS; channel++)
{
average[channel] = (ushort)(total[channel] / events);
char msg[0xFF];
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]);
//if (channel < (CHANNELS - 1))
// tbAdcStatistics.AppendText(Environment.NewLine);
AddMessage(msg);
}
//SetTextboxToTop(tbAdcStatistics);
}
 
void SetupAcquisition(int neve)
{
//EnableRegisterScanTimer(false);
//nudEventSelect.Minimum = 0;
//nudEventSelect.Maximum = 0;
int eventsAcquired = Acquire(neve);
if (eventsAcquired < 1)
return;
GetStatistics(eventsAcquired);
ShowEvent(1);
//ShowHistograms();
//nudEventSelect.Minimum = 1;
//nudEventSelect.Maximum = eventsAcquired;
//EnableRegisterScanTimer(true);
}
 
int main(int argc, _TCHAR* argv[])
//int _tmain(int argc, _TCHAR* argv[])
{
 
 
NE_Rainbow();
//-----------------------------------
char bla[100] = "abcd";
NE_Ptr2ByteArray(bla, strlen(bla));
//-----------------------------------
char data[1000] = { 1,0,0,1,0,0,0,0,1,1,1,1 };
int len = 0;
//char *data=NULL;
int *retval = (int *)NE_ByteArray2Ptr(data, &len);
int *idata = (int*)data;
printf("***NE_ByteArray2Ptr %d\n", len);
for (int i = 0; i < len; i++) printf("%d %d %d\n", i, idata[i], retval[i]);
printf("\n");
//-----------------------------------
char data1[100] = "NE_Ptr2String";
NE_Ptr2String(data1, strlen(data1));
//-----------------------------------
char data2[100] = "abcd";
int nb = NE_String2Ptr(data2);
//-----------------------------------
 
printf("result = %d %s\n", nb, bla);
printf("string = %s\n", NE_String());
 
//-----------------------------------
unsigned int *n = NE_UInt(&len);
printf("NE_UInt size = %d\n", len);
for (int i = 0; i < len; i++) printf("%d\t", n[i]);
printf("\n");
//-----------------------------------
 
int events = 1000;
adcBufferLen = GetAdcEventSize() * events;
//adcBuffer = new ushort[GetAdcEventSize() * events];
for (int i = 0; i < 0xFFF; i++) {
for (int j = 0; j < 4; j++) histograms[j][i] = 0;
}
histogramTotalEvents = 0;
InitializeConnection();
QuickSetupContinuous();
ReadRegisters();
SetupAcquisition(1);
 
return 0;
}
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitSipmDAQApp.filters
0,0 → 1,39
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="stdafx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="AitMduManager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="AitMduManager_DEF.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="AitSipmDAQApp.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stdafx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitSipmDAQApp.user
0,0 → 1,4
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/AitSipmDAQApp.vcxproj
0,0 → 1,104
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A133C14A-192C-49DA-936C-0BC2FB5EB54E}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>NativeExportsConsumerApp</RootNamespace>
<ProjectName>AitSipmDAQApp</ProjectName>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<CLRSupport>true</CLRSupport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EntryPointSymbol>
</EntryPointSymbol>
</Link>
<PostBuildEvent>
<Command>copy "..\UnmanagedDllInterface\bin\$(ConfigurationName)\AitSipmDAQDll.dll" "$(TargetDir)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
<PostBuildEvent>
<Command>copy "..\NativeExports\bin\$(ConfigurationName)\NativeExports.dll" "$(TargetDir)"</Command>
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="AitMduManager.h" />
<ClInclude Include="AitMduManager_DEF.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="AitSipmDAQApp.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/ReadMe.txt
0,0 → 1,40
========================================================================
CONSOLE APPLICATION : NativeExportsConsumerApp Project Overview
========================================================================
 
AppWizard has created this NativeExportsConsumerApp application for you.
 
This file contains a summary of what you will find in each of the files that
make up your NativeExportsConsumerApp application.
 
 
NativeExportsConsumerApp.vcxproj
This is the main project file for VC++ projects generated using an Application Wizard.
It contains information about the version of Visual C++ that generated the file, and
information about the platforms, configurations, and project features selected with the
Application Wizard.
 
NativeExportsConsumerApp.vcxproj.filters
This is the filters file for VC++ projects generated using an Application Wizard.
It contains information about the association between the files in your project
and the filters. This association is used in the IDE to show grouping of files with
similar extensions under a specific node (for e.g. ".cpp" files are associated with the
"Source Files" filter).
 
NativeExportsConsumerApp.cpp
This is the main application source file.
 
/////////////////////////////////////////////////////////////////////////////
Other standard files:
 
StdAfx.h, StdAfx.cpp
These files are used to build a precompiled header (PCH) file
named NativeExportsConsumerApp.pch and a precompiled types file named StdAfx.obj.
 
/////////////////////////////////////////////////////////////////////////////
Other notes:
 
AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.
 
/////////////////////////////////////////////////////////////////////////////
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/stdafx.cpp
0,0 → 1,8
// stdafx.cpp : source file that includes just the standard includes
// NativeExportsConsumerApp.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
 
#include "stdafx.h"
 
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/stdafx.h
0,0 → 1,15
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
 
#pragma once
 
#include "targetver.h"
 
#include <stdio.h>
#include <tchar.h>
 
 
 
// TODO: reference additional headers your program requires here
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/AitSipmDAQApp/targetver.h
0,0 → 1,8
#pragma once
 
// Including SDKDDKVer.h defines the highest available Windows platform.
 
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
 
#include <SDKDDKVer.h>
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/UnmanagedDllInterface/AitSipmDAQDll.csproj
0,0 → 1,78
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A9829616-449C-4F04-AFF1-B7D11F6ED0C8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AitSipmDAQDll</RootNamespace>
<AssemblyName>AitSipmDAQDll</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="AitMduManager">
<HintPath>..\AitMduManager.dll</HintPath>
</Reference>
<Reference Include="RGiesecke.DllExport.Metadata, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f52d83c1a22df51, processorArchitecture=MSIL">
<HintPath>..\packages\UnmanagedExports.1.2.7\lib\net\RGiesecke.DllExport.Metadata.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="../packages/UnmanagedExports.1.2.7/tools/RGiesecke.DllExport.targets" Condition="Exists('../packages/UnmanagedExports.1.2.7/tools/RGiesecke.DllExport.targets')" />
</Project>
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/UnmanagedDllInterface/Program.cs
0,0 → 1,500
using RGiesecke.DllExport;
using System;
using System.Text;
using System.Runtime.InteropServices;
 
using AitMduManager;
 
/*
#region Assembly AitMduManager, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null
// AitMduManager.dll
#endregion
*/
 
// https://blogs.msdn.microsoft.com/jaredpar/2008/11/05/dereference-a-double-intptr/
 
 
namespace NativeExports
{
class Program
{
 
static MduManager SD4 = new MduManager();
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int SD4_BlockError()
{
return SD4.BlockError;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_SetBlockTimeout(uint a)
{
SD4.BlockTimeout = a;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static uint SD4_GetBlockTimeout()
{
return SD4.BlockTimeout;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static long SD4_BlockTransferTime()
{
return SD4.BlockTransferTime;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static uint SD4_GetDriverTimeout()
{
return SD4.DriverTimeout;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_SetDriverTimeout(uint tout)
{
SD4.DriverTimeout = tout;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_Version()
{
return Marshal.StringToHGlobalAnsi(SD4.Version);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int SD4_WordsTransferred()
{
return SD4.WordsTransferred;
}
 
/*
 
public event EventHandler DeviceAttached;
public event EventHandler DeviceRemoved;
public event EventHandler FirmwareStatusChanged;
*/
 
static IntPtr SD4_ArrayToIntPtr(int[] retval)
{
int len = retval.Length * Marshal.SizeOf(typeof(int));
SD4_AllocateMemory(len);
Marshal.Copy(retval, 0, _unmanagedMemory, retval.Length);
return _unmanagedMemory;
}
 
static IntPtr SD4_ArrayToIntPtr(ushort[] retval)
{
int len = retval.Length * Marshal.SizeOf(typeof(ushort));
SD4_AllocateMemory(len);
Marshal.Copy((short[])(object) retval, 0, _unmanagedMemory, retval.Length);
return _unmanagedMemory;
}
 
static IntPtr SD4_ArrayToIntPtr(uint[] retval)
{
int len = retval.Length * Marshal.SizeOf(typeof(uint));
SD4_AllocateMemory(len);
Marshal.Copy((int[])(object) retval, 0, _unmanagedMemory, retval.Length);
return _unmanagedMemory;
}
 
static IntPtr SD4_ArrayToIntPtr(byte[] retval)
{
int len = retval.Length * Marshal.SizeOf(typeof(byte));
SD4_AllocateMemory(len);
Marshal.Copy(retval, 0, _unmanagedMemory, retval.Length);
return _unmanagedMemory;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_FindDevices( ref int len)
{
uint[] devices = SD4.FindDevices();
if (devices == null)
{
len = 0;
return IntPtr.Zero;
}
else
{
len = devices.Length;
return SD4_ArrayToIntPtr(devices);
}
 
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int SD4_GetDeviceCount()
{
return SD4.GetDeviceCount();
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_GetDeviceList( ref int len)
{
uint[] devices = SD4.GetDeviceList();
if (devices == null)
{
len = 0;
return IntPtr.Zero;
}
else
{
len = devices.Length;
return SD4_ArrayToIntPtr(devices);
}
}
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_GetUsbFirmwareVersionByDevice(uint deviceId)
{
return Marshal.StringToHGlobalAnsi(SD4.GetUsbFirmwareVersion(deviceId));
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_GetUsbFirmwareVersion(int index)
{
return Marshal.StringToHGlobalAnsi(SD4.GetUsbFirmwareVersion(index));
}
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static bool SD4_IsDeviceAttached(uint deviceId)
{
return SD4.IsDeviceAttached(deviceId);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static bool SD4_ProgramFpgaFirmwareByDevice(uint deviceId, IntPtr data, int len)
{
byte[] fpgaFirmware = new byte[len];
Marshal.Copy(data, fpgaFirmware, 0, len);
return SD4.ProgramFpgaFirmware(deviceId, fpgaFirmware);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static bool SD4_ProgramFpgaFirmware(int index, IntPtr data, int len)
{
byte[] fpgaFirmware = new byte[len];
Marshal.Copy(data, fpgaFirmware, 0, len);
return SD4.ProgramFpgaFirmware(index, fpgaFirmware);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static bool SD4_ProgramUsbFirmware(int index, IntPtr data, int len)
{
byte[] usbFirmware = new byte[len];
Marshal.Copy(data, usbFirmware, 0, len);
return SD4.ProgramUsbFirmware(index, usbFirmware);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static ushort SD4_Read(uint deviceId, int address)
{
return SD4.Read(deviceId, address);
}
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_ReadByteArray(uint deviceId, int address, int requested_elements , ref int len)
{
SD4_AllocateByteBuffer(requested_elements);
SD4.Read(deviceId, address, SD4_ByteBuffer);
_unmanagedMemory = SD4_ArrayToIntPtr(SD4_ByteBuffer);
len = _unmanagedMemoryLength;
return _unmanagedMemory;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr SD4_ReadUShortArray(uint deviceId, int address, int requested_elements, ref int len)
{
/*
System.Console.WriteLine("SD4_ReadUShortArray");
System.Console.WriteLine(deviceId);
System.Console.WriteLine(address);
System.Console.WriteLine(requested_elements);
*/
SD4_AllocateUshortBuffer(requested_elements);
SD4.Read(deviceId, address, SD4_UShortBuffer);
_unmanagedMemory = SD4_ArrayToIntPtr(SD4_UShortBuffer);
len = _unmanagedMemoryLength;
return _unmanagedMemory;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ReconfigureByDevice(uint deviceId)
{
SD4.Reconfigure(deviceId);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_Reconfigure(int index)
{
SD4.Reconfigure(index);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ReconnectByDevice(uint deviceId)
{
SD4.Reconnect(deviceId);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_Reconnect(int index)
{
SD4.Reconnect(index);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ResetFpga(int index)
{
SD4.ResetFpga(index);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ResetFpgaByDevice(uint deviceId)
{
SD4.ResetFpga(deviceId);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ResetUsb(int index)
{
SD4.ResetUsb(index);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_ResetUsbByDevice(uint deviceId)
{
SD4.ResetUsb(deviceId);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void SD4_Write(uint deviceId, int address, ushort data)
{
SD4.Write(deviceId, address, data);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int SD4_WriteArray(uint deviceId, int address, IntPtr data, int len)
{
ushort[] udata = new ushort[len];
Marshal.Copy( data, (int[])(object) udata,0, len);
return SD4.Write(deviceId, address, udata);
}
/*
public sealed class DeviceChangedEventArgs : EventArgs
{
public DeviceChangedEventArgs();
 
public uint DeviceId { get; set; }
public int DeviceIndex { get; set; }
}
public sealed class FirmwareStatusEventArgs : EventArgs
{
public FirmwareStatusEventArgs();
 
public uint DeviceId { get; set; }
public int DeviceIndex { get; set; }
public string FirmwareStatus { get; set; }
}
*/
 
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int NE_Ptr2String(IntPtr c, int len)
{
string d = Marshal.PtrToStringAnsi(c);
Console.WriteLine(d);
return 0;
}
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int NE_Ptr2ByteArray(IntPtr c, int len)
{
System.Console.WriteLine(len);
byte[] b = new byte[len];
Marshal.Copy(c, b, 0, len);
foreach (byte element in b)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
return b.Length;
}
 
//-----------------------------------
// http://stackoverflow.com/questions/14934016/unmanaged-exports-with-arrays
// https://github.com/kbilsted/NotepadPlusPlusPluginPack.Net/blob/master/Visual%20Studio%20Project%20Template%20C%23/PluginInfrastructure/UnmanagedExports.cs
static IntPtr _unmanagedMemory = IntPtr.Zero;
static int _unmanagedMemoryLength = 0;
 
static void SD4_AllocateMemory(int len)
{
 
if (_unmanagedMemoryLength < len)
{
if (_unmanagedMemory != IntPtr.Zero)
Marshal.FreeHGlobal(_unmanagedMemory);
_unmanagedMemory = Marshal.AllocHGlobal(len);
_unmanagedMemoryLength = len;
 
}
}
 
 
static ushort[] SD4_UShortBuffer = null;
static ushort[] SD4_AllocateUshortBuffer(int len) {
if (SD4_UShortBuffer == null || SD4_UShortBuffer.Length < len) {
Array.Resize(ref SD4_UShortBuffer, len);
}
return SD4_UShortBuffer;
}
 
static byte[] SD4_ByteBuffer = null;
static byte[] SD4_AllocateByteBuffer(int len)
{
if (SD4_ByteBuffer == null || SD4_ByteBuffer.Length < len)
{
Array.Resize(ref SD4_ByteBuffer, len);
}
return SD4_ByteBuffer;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr NE_ByteArray2Ptr(ref IntPtr unmanagedArray, out int length)
{
var valueList = new[] { 1, 2, 3, 3, 2, 1, 12, 11, 10 };
System.Console.WriteLine("NE_ByteArray2Ptr");
 
foreach (var element in valueList)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
 
length = valueList.Length;
int len = valueList.Length * Marshal.SizeOf(typeof(int));
SD4_AllocateMemory(len);
Marshal.Copy(valueList, 0, _unmanagedMemory, length);
//
//unmanagedArray = Marshal.AllocHGlobal(len);
//Marshal.Copy(valueList, 0, unmanagedArray, length);
return _unmanagedMemory;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int NE_ByteArray2Ptr1(ref IntPtr dest, ref int len)
//static int NE_ByteArray2Ptr( ref byte[] src, ref int len)
{
len = 5;
//Marshal.AllocHGlobal(len);
byte[] src = new byte[len];
for (int i = 0; i < len; i++)
{
src[i] = Convert.ToByte(i);
//Marshal.WriteByte(dest, i, src[i] );
}
System.Console.WriteLine("NE_ByteArray2Ptr");
System.Console.WriteLine(len);
foreach (byte element in src)
{
System.Console.WriteLine(element);
}
System.Console.WriteLine();
 
// Marshal.Copy(src, 0, dest, len);
 
return src.Length;
}
 
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static int NE_String2Ptr(ref IntPtr c)
{
 
 
 
// Copy the array to unmanaged memory.
//c = Marshal.StringToHGlobalAnsi(d);
string inputStr = Marshal.PtrToStringAnsi(c);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(inputStr);
 
 
string outputStr = "NE_String2Ptr";
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(outputStr);
Console.ForegroundColor = ConsoleColor.White;
 
// http://stackoverflow.com/questions/21378132/export-managed-c-sharp-function-to-return-changed-char-parameter-to-unmanaged-c
byte[] outputBytes = Encoding.Default.GetBytes(outputStr);
//problemi Marshal.Copy(outputBytes, 0, c, outputBytes.Length);
 
 
return outputStr.Length;
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr NE_String()
{
string d = "NE_String";
 
 
// Copy the array to unmanaged memory.
//c = Marshal.StringToHGlobalAnsi(d);
 
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(d);
Console.ForegroundColor = ConsoleColor.White;
 
return Marshal.StringToHGlobalAnsi(d);
}
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static IntPtr NE_UInt(ref int len)
{
len = 10;
uint[] b = new uint[len];
for (uint i = 0; i < len; i++)
{
b[i] = i;
}
//PrintBytes(b);
IntPtr p = Marshal.AllocHGlobal(len * 4);
Marshal.Copy((int[])(object)b, 0, p, len);
return p;
}
 
 
[DllExport(CallingConvention = CallingConvention.Cdecl)]
static void NE_Rainbow()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write('R');
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Write('a');
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write('i');
Console.ForegroundColor = ConsoleColor.Green;
Console.Write('n');
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write('b');
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write('o');
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write('w');
 
Console.ResetColor();
Console.WriteLine();
}
}
}
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/UnmanagedDllInterface/Properties/AssemblyInfo.cs
0,0 → 1,36
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AitSipmDAQDll")]
[assembly: AssemblyDescription("Unamanaged interface to the NET AIT SIPMDAQ4 library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jozef Stefan Institute")]
[assembly: AssemblyProduct("AitSipmDAQDll")]
[assembly: AssemblyCopyright("Copyright Rok Pestotnik © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("576f7d1f-2ff9-4181-9e87-2946da78f3eb")]
 
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
/cvi/instr/AitSipmDAQ/AitSipmDAQDll/UnmanagedDllInterface/packages.config
0,0 → 1,4
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="UnmanagedExports" version="1.2.7" targetFramework="net451" />
</packages>