unit ADCDevice;

interface

uses
  Windows, WakeDevice, Classes, SysUtils, Math;

//---------------------------------------------------------------------------
//  Коды команд
//---------------------------------------------------------------------------
const
  // $00..$03 - Стандартные коды команд протокола WAKE
  CMD_GETA = $04;                      // чтение АЦП.

  CHANNEL_COUNT  = 32;
  GAIN_COUNT     = 7;

type

//---------------------------------------------------------------------------
//    TADCDevice = class(TWakeDevice)
//---------------------------------------------------------------------------

  TADCDevice = class(TWakeDevice)
  private
  protected
  public
    constructor Create; override;

    // Список подключенных устройств
    procedure DiveceList(AList: TStrings); override;

    procedure ReadADC(AChannel: integer; AIndexGain: integer; out Value : double);

    function IndexToGain(Gain: integer):byte;

    function Disconnect:boolean;
  end; //  TADCDevice = class(TWakeDevice)

var
  Device: TADCDevice;

implementation

uses
  Config, Calib;

constructor TADCDevice.Create();
begin
  inherited Create;
  FDeviceName  := 'ADCU14-32';
  FBaudRateUSB := 500000;

end;

// Список устройств
procedure TADCDevice.DiveceList(AList: TStrings);
var
  i : integer;
begin
  inherited DiveceList(AList);
  i := 0;
  while i < AList.Count do
  begin
    if Pos('ADCU14-32', AList.Strings[i]) <> 1 then
        AList.Delete(i)
    else
        inc(i);
  end;
end;

function TADCDevice.Disconnect:boolean;
begin
  result := ClosePort;
end;

function TADCDevice.IndexToGain(Gain: integer):byte;
begin
  case Gain of
    0 : Result := 1;
    1 : Result := 2;
    2 : Result := 5;
    3 : Result := 10;
    4 : Result := 20;
    5 : Result := 50;
    6 : Result := 100;
    else
        result := 255;
  end;

end;

procedure TADCDevice.ReadADC(AChannel: integer; AIndexGain: integer; out Value : double);
var
  txData, rxData : TWakeData;
  Code : integer;
begin
  // Channel от 0 до 7
  txData[0] := AChannel;

  // Gain
  // 1,     2,    5,    10,   20,      50,      100
  // ±10 В, ±5 В, ±2 В, ±1 В, ±500 мВ, ±200 мВ, ±100 мВ
  txData[1] := IndexToGain(AIndexGain);

  ExeCmd(CMD_GETA, 2, txData, rxData);;

  Code := MakeWord(rxData[1], rxData[2]);

  if Code > $7FFF then
      Code := Code - $10000;
  Value := Calibration.Calib.K[AChannel, AIndexGain] * 10 * (Code / $7FFF) / IndexToGain(AIndexGain) + Calibration.Calib.S[AChannel, AIndexGain];
  Value := RoundTo(Value, (-1) * Configuration.General.Round[AChannel]);
end;


end.
