COM + ARDUINO MEGA + DELPHI

ramtamtager
Offline
Зарегистрирован: 04.09.2013

Пример скетча для управления выходами ARDUINO MEGA.

Чтение  и запись Массива и отдельных ног.

формат записи:

Команда (0 1 2 3 4 5) - адрес выхода( в виде символа, код символа-1= коду ноги)

опционально символы 0 1 (HI LO для записи в порт) ~окончание строки

Пример: 2-!"#$~ (Прочитать выводы 32 33 34 35)  код символа -1

т.к. в Delphi #0 конец строки

Ответ: 1111~

String in_byte, out_byte;
int    opr, iEnd,iPos,iAdr;

void setup() {
                Serial.begin(9600); 
                in_byte="";
                out_byte="";
              }

// 0 set pin array 0-A1B0C1\
// 1 get pin array 1-ABSDEF\
// 2 set pin array HI 2-ABS\
// 3 set pin array LO 3-ABS\
// 4 set pin OUTPUT 4-ABCD\
// 5 set pin INPUT 5-ASD\ 34


void loop() {

while (Serial.available() == 0);
in_byte += char(Serial.read());
iEnd = in_byte.indexOf("~");

if (iEnd > 0) 
{
   out_byte="";
   opr = int(in_byte.charAt(0))-48;
   iPos = 2;
    
  while (iPos < iEnd)
    {
      iAdr  = int(in_byte.charAt(iPos))-1; // delphi #0 end string
      iPos++;
        switch (opr) 
            {
                case 0:
                  if (in_byte.charAt(iPos) == '0') {digitalWrite(iAdr,LOW);} else {digitalWrite(iAdr,HIGH);}                
                  iPos++;
                break;
                case 1: if (digitalRead(iAdr) == HIGH) {out_byte += '1'; } else {out_byte += '0'; } break;
                case 2: digitalWrite(iAdr,HIGH); break;
                case 3: digitalWrite(iAdr,LOW); break;
                case 4: pinMode(iAdr, OUTPUT); break;
                case 5: pinMode(iAdr, INPUT); break;
            }
      if (iPos == iEnd) break;
    }
      iEnd=0;
      iPos=0;
      opr=0;
      Serial.print(out_byte+"~");
      in_byte="";
      out_byte="";
}

}

 

ramtamtager
Offline
Зарегистрирован: 04.09.2013

Посты по всей видимости править нельзя.

Вот чуть улучшенный код без “indexOf”

Чуть позже размещу модуль на Delphi

Цель проекта программатор для 29СXXX и AT89C55 и любых других программируемых микросхем

 

String in_byte, out_byte;
int    opr, iEnd,iPos,iAdr,val;

void setup() {
                Serial.begin(9600); 
                in_byte="";
                out_byte="";
              }

// 0 set pin array 0-!1#0$0%1~
// 1 get pin array 1-!#$%&~
// 2 set pin array HI 2-!#$%&~
// 3 set pin array LO 3-!#$%&~
// 4 set pin OUTPUT 4-!#$%&~
// 5 set pin INPUT 5-!#$%&~


void loop() {

while (Serial.available() == 0);
val = Serial.read();
if (val == 126)
  {
      in_byte += char(val);
      iEnd = in_byte.length();
  }
  else {in_byte += char(val);}


if (iEnd > 0) 
{
   out_byte="";
   opr = int(in_byte.charAt(0))-48;
   iPos = 2;
    
  while (iPos < iEnd)
    {
      iAdr  = int(in_byte.charAt(iPos))-1; // delphi #0 end string
      iPos++;
        switch (opr) 
            {
                case 0: if (in_byte.charAt(iPos) == '0') {digitalWrite(iAdr,LOW);} else {digitalWrite(iAdr,HIGH);} iPos++; break;
                case 1: if (digitalRead(iAdr) == HIGH) {out_byte += '1'; } else {out_byte += '0'; } break;
                case 2: digitalWrite(iAdr,HIGH); break;
                case 3: digitalWrite(iAdr,LOW); break;
                case 4: pinMode(iAdr, OUTPUT); break;
                case 5: pinMode(iAdr, INPUT); break;
            }
      if (iPos+1 >= iEnd) break;
    }
      iEnd=0;
      iPos=0;
      opr=0;
      Serial.print(out_byte+"~");
      in_byte="";
      out_byte="";
}

}

 

ramtamtager
Offline
Зарегистрирован: 04.09.2013
unit ComMainForm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, CPort, CPortCtl,text_rule,math;

type
  TForm1 = class(TForm)
    ComPort: TComPort;
    Button_Open: TButton;
    Button_Settings: TButton;
    Bt_Store: TButton;
    Bt_Load: TButton;
    Memo1: TMemo;
    Button1: TButton;
    Label1: TLabel;
    Button2: TButton;
    procedure Button_OpenClick(Sender: TObject);
    procedure Button_SettingsClick(Sender: TObject);
    procedure ComPortOpen(Sender: TObject);
    procedure ComPortClose(Sender: TObject);
    procedure Bt_LoadClick(Sender: TObject);
    procedure Bt_StoreClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  time_out:ttime;
    adressQ:array [0..17] of integer = (45,43,41,39,37,35,33,31,30,32,38,34,29,28,26,27,25,24); //A0,A1-An
    adressA:string;
    dataQ:array [0..7] of integer = (47,49,51,50,48,46,44,42);
    dataA:string;
    cntQ:array [0..2] of integer = (36,22,40); // OE WE CE
    const OE=0; WE=1;CE=2;
implementation

{$R *.DFM}
function HexToInt(Str : string): integer;
var i, r : integer;
begin
  val('$'+Trim(Str),r, i);
  if i<>0 then HexToInt := 0 {была ошибка в написании числа}
  else HexToInt := r;
end;
  // 0 set pin array 0-!1#0$0%1~
	// 1 get pin array 1-!#$%&~
	// 2 set pin array HI 2-!#$%&~
	// 3 set pin array LO 3-!#$%&~
	// 4 set pin OUTPUT 4-!#$%&~
	// 5 set pin INPUT 5-!#$%&

function PortWrite(a:string):string;
var st,data:string;
    i,j:integer;
    t1:tdatetime;
begin
  form1.ComPort.WriteStr(a);  // form1.memo1.Lines.Add(a);
  i:=0;
  data:='';
  t1:=now;
  while (i=0) do
  begin
    form1.ComPort.ReadStr(st,8);
    data:=data+st;
    i:=pos('~',data);
    if now-t1>time_out then abort;
  end;//  form1.memo1.Lines.Add('->'+data);
  result:=data;
end;

procedure WriteArr(a:string);begin PortWrite('0-'+a+'~');end;
procedure WriteHI(a:string); begin PortWrite('2-'+a+'~');end;
procedure WriteLO(a:string); begin PortWrite('3-'+a+'~');end;
procedure SetOutput(a:string);begin PortWrite('4-'+a+'~');end;
procedure SetInput(a:string); begin PortWrite('5-'+a+'~'); end;
function ReadArr(a:string):string; begin result:=PortWrite('1-'+a+'~'); end;
function pin(a:byte):char; begin  result:=chr(a+1); end;

function out2int(a:string):integer;
  var i:integer;
begin
    result:=0;
     for I := length(a) downto 1 do
      if a[i] in ['0','1'] then
        begin
         result:=result shl 1;
         if a[i]='1' then result:=result+1;
        end;
end;

function int2out(data:integer):string;
  var cn,inb:integer;
begin
     inb:=data; result:='';
     for cn := 0 to high(dataQ) do
     begin
      if inb and 1 = 1 then result:=result+pin(dataQ[cn])+'1' else result:=result+pin(dataQ[cn])+'0';
       inb:=inb shr 1;
     end;
end;

procedure setAdress(i:integer);
var result:string;
    cn,inb:integer;
begin
    result:='';inb:=i;
      for cn:=0 to high(adressQ) do
          begin
            if inb and 1 = 1 then result:=result+pin(adressQ[cn])+'1' else result:=result+pin(adressQ[cn])+'0';
             inb:=inb shr 1;
          end;
    WriteArr(result);
end;


function FL_Read(adr:integer):integer;
begin
    setAdress(adr);
      WriteArr(
               pin(cntQ[WE])+'1'+
               pin(cntQ[CE])+'1'+
               pin(cntQ[OE])+'1'+
               pin(cntQ[CE])+'0'+
               pin(cntQ[OE])+'0'
               );
{    WriteHI(pin(cntQ[WE])+pin(cntQ[OE])+pin(cntQ[CE]));
    WriteLO(pin(cntQ[CE]));
    WriteLO(pin(cntQ[OE])); }
    result:=out2int(ReadArr(dataA));
end;

procedure FL_Write(adr:integer;data:integer);
begin
     setAdress(adr);
     WriteArr(int2out(data));
     WriteArr(
               pin(cntQ[CE])+'1'+
               pin(cntQ[OE])+'0'+
               pin(cntQ[WE])+'0'+
               pin(cntQ[CE])+'0'+
               pin(cntQ[OE])+'1'+
               pin(cntQ[WE])+'0'+
               pin(cntQ[WE])+'1'
             );

   { WriteHI(pin(cntQ[WE])+pin(cntQ[CE]));
    WriteLO(pin(cntQ[OE]));
    WriteLO(pin(cntQ[CE]));
    WriteLO(pin(cntQ[WE]));
    WriteHI(pin(cntQ[WE]));       }
end;


procedure FL_init();
var i:integer;
begin
  adressA:='';
  for i := 0 to high(adressQ) do
 adressA:=adressA+pin(adressQ[i]);

SetOUTPUT(adressA+pin(cntQ[WE])+pin(cntQ[OE])+pin(cntQ[CE]));
WriteLO(adressA+pin(cntQ[WE])+pin(cntQ[OE])+pin(cntQ[CE]));

dataA:='';
  for i := 0 to high(dataQ) do
  dataA:=dataA+pin(dataQ[i]);

WriteLO(dataA);
end;

procedure TForm1.Button1Click(Sender: TObject);
var  buff,dout,k:string;
  i,j,u,y,x:integer;
begin


FL_init();
{SetOUTPUT(dataA);
FL_Write(HexToInt('5555'),HexToInt('AA'));
FL_Write(HexToInt('2AAA'),HexToInt('55'));
FL_Write(HexToInt('5555'),HexToInt('80'));

FL_Write(HexToInt('5555'),HexToInt('AA'));
FL_Write(HexToInt('2AAA'),HexToInt('55'));
FL_Write(HexToInt('5555'),HexToInt('60'));  }
sleep(500);
SetINPUT(dataA);
buff:='';
//for i:=131072 downto 0 do

for i:=0 to 131072*2 do
begin
    if i mod 100 = 0 then
    begin
      label1.Caption:=inttostr(i);
     memo1.Text:=buff;
      application.ProcessMessages;
    end;

 // FL_Write(i,33);

//buff:=buff+' '+inttohex(FL_read(i),2);
  k:=chr(FL_read(i));

  if k[1] in ['a'..'z','A'..'Z','0'..'9','а'..'я','А'..'Я'] then buff:=buff+k[1];

end;
memo1.lines.Add(buff);
end;


procedure TForm1.Button2Click(Sender: TObject);
begin
SetOUTPUT(pin(cntQ[WE])+pin(cntQ[OE])+pin(cntQ[CE]));
    WriteHI(pin(cntQ[WE])+pin(cntQ[OE])+pin(cntQ[CE]));

end;

procedure TForm1.Button_OpenClick(Sender: TObject);
begin
  if ComPort.Connected then
    ComPort.Close
  else
    ComPort.Open;
end;

procedure TForm1.Button_SettingsClick(Sender: TObject);
begin
  ComPort.ShowSetupDialog;
end;

procedure TForm1.ComPortOpen(Sender: TObject);
begin
  Button_Open.Caption := 'Close';
end;

procedure TForm1.ComPortClose(Sender: TObject);
begin
  if Button_Open <> nil then
    Button_Open.Caption := 'Open';
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
time_out:=(1/24/60/60)*2;

end;

procedure TForm1.Bt_LoadClick(Sender: TObject);
begin
  ComPort.LoadSettings(stRegistry, 'HKEY_LOCAL_MACHINE\Software\Dejan');
//  ComPort.LoadSettings(stIniFile, 'e:\Test.ini');
end;

procedure TForm1.Bt_StoreClick(Sender: TObject);
begin
//  ComPort.StoreSettings(stIniFile, 'e:\Test.ini');
  ComPort.StoreSettings(stRegistry, 'HKEY_LOCAL_MACHINE\Software\Dejan');
end;

end.