Delphi & Pascal (česká wiki)
Přejít na: navigace, hledání
{ I2C.PAS                                                            }
{ Komunikacia I2C pre program teletext.                              }
{                                                                    }
{ Datum:14.12.2017                              http://www.trsek.com }
 
unit i2c_com;
interface
procedure i2c_start;
procedure i2c_stop;
procedure i2c_ack;
procedure i2c_noack;
function i2c_vystup (hodnota:Byte):boolean;
function i2c_cteni:Byte;
implementation
uses crt;
var temp:byte;
    ba:word;
 
function com_sel:word;
var v,code:word;
begin
if paramcount=0 then com_sel:=$2f8;
val(paramstr(1),v,code);
case v of
  1:com_sel:=$3f8;
  2:com_sel:=$2f8;
  3:com_sel:=$3e8;
  4:com_sel:=$2e8;
   else com_sel:=$2f8;
  end;
end;
 
procedure wait_SCL;
var del_count:word;
  begin
   for del_count:=0 to 255 do
  end;
 
procedure dela;
var del_count:word;
  begin
   for del_count:=0 to 255 do;
  end;
 
procedure i2c_start;
  begin
   port[ba+4]:=3;    {3 SDA 1, SCL 1}
   wait_SCL;
   port[ba+4]:=2;    {2 SDA 0, SCL 1}
   dela;
   port[ba+4]:=0;    {0 SDA 0, SCL 0}
   dela;
  end;
 
procedure i2c_stop;
  begin
   port[ba+4]:=0;    {0 SDA 0, SCL 0}
   dela;
   port[ba+4]:=2;    {2 SDA 0, SCL 1}
   wait_SCL;
   port[ba+4]:=3;    {3 SDA 1, SCL 1}
   dela;
  end;
 
procedure i2c_ack;
  begin
   port[ba+4]:=0;     {0 SDA 0, SCL 0}
   dela;
   port[ba+4]:=2;     {2 SDA 0, SCL 1}
   wait_SCL;
   port[ba+4]:=0;     {0 SDA 0, SCL 0}
   dela;
  end;
 
procedure i2c_noack;
  begin
   port[ba+4]:=1;     {1 SDA 1, SCL 0}
   dela;
   port[ba+4]:=3;     {3 SDA 1, SCL 1}
   wait_SCL;
   port[ba+4]:=1;     {1 SDA 1, SCL 0}
   dela;
  end;
 
function i2c_vystup(hodnota:byte):boolean;
var bit,portwert,n,m:byte;
  begin
   bit:=128;
   for n:= 1 to 8 do
    begin
     if (hodnota and bit)=bit then portwert:= 1 else portwert:=0;
     port[ba+4]:=portwert;   {SDA = bit, SCL 0}
     dela;
     port[ba+4]:=portwert+2; {SCL 1}
     wait_SCL;
     port[ba+4]:=portwert;   {SDA = bit, SCL 0}
     dela;
     bit:=bit div 2
    end;
   port[ba+4]:=1; {1 SDA 1, SCL 0}
   dela;
   port[ba+4]:=3; {3 SDA 1, SCL 1}
   wait_SCL;
   if (port[ba+6] and 16)=16 then  {TEST SDA}
    begin
     dela;
     i2c_vystup:=false;
     writeln('--Slave: ',hodnota,' not respond--');
    end
   else i2c_vystup:=true;
   port[ba+4]:=1; {1 SDA 1, SCL 0}
   dela;
  end;
 
function i2c_cteni:byte;
var bit,wert,n,m:Byte;
  begin
   port[ba+4]:=1; {1 SDA 1, SCL 0}
   dela;
   bit:=128;
   wert:=0;
   for n:= 1 to 8 do
    begin
     port[ba+4]:=3; {3 SDA 1, SCL 1}
     wait_SCL;
     if (port[ba+6] and 16)=16 then wert:=wert+bit; {TEST SDA}
     dela;
     port[ba+4]:=1; {1 SDA 1, SCL 0}
     dela;
     bit:= bit div 2;
    end;
   i2c_cteni:=wert;
  end;
 
begin
ba:=com_sel;
temp:=port[ba+6];
temp:=port[ba+6];
end.