Hardware Access/es

From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) magyar (hu) 日本語 (ja) 한국어 (ko) polski (pl) português (pt) русский (ru) slovenčina (sk) 中文(中国大陆)‎ (zh_CN)

Descripción

Esta página es el comienzo de un tutorial que trata del acceso a dispositivos hardware. Estos dispositivos incluyen entre otros: ISA, PCI, USB, puerto paralelo, puerto serie, etc.

El acceso a dispositivos hardware no esta implementado en la modalidad multiplataforma ni para el Runtime ni para el LCL de Free Pascal, por lo que este tutorial básicamente cubrirá los métodos de acceso a hardware en las diferentes plataformas. El código puede ser compilado en diferentes entornos utilizando compilaciones condicionales, como las siguientes:

uses
 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
{$IFDEF WIN32}
  Windows;
{$ENDIF}
{$IFDEF Unix}
  ports;
{$ENDIF}

No se sabe todavía, hasta el momento, si MAC OS X/x86 permitirá el acceso hardware. Puede que lo permita, por lo que puede que con el tiempo aparezcan drivers como io.dll.

Comparación entre serie y paralelo

Las tarjetas ISA, PCI y el puerto paralelo se comunican con el ordenador utilizando un protocolo paralelo. El puerto serie y los dispositivos USB en cambio con un protocolo serie. Como tanto el procesador como todos los lenguajes de programación trabajan en una aproximación a datos en paralelo, el acceso a esta clase de protocolos es más fácil de implementar en la parte software. Por ejemplo, cuando se accede a una variable de tipo entero (Integer), es posible acceder a su valor asociado con un simple mandato. Con un protocolo serie, sin embargo, se puede conocer sólamente un bit en cada vez, y se hace necesario unir todos los bits para tener un dato con significado.

La comunicación serie es difícil de implementar directamente, pero puede resultar razonablemente sencillo si se utiliza un componente prediseñado. También se bastante difícil en la parte hardware, por lo que algunos dispositivos utilizan Cirtuitos Integrados especializados o incluso Microcontroladores para implementarlo.

A continuación se presenta una breve comparación de protocolos de acceso a hardware:


Velocidad Dificultad de implementación hardware
Puerto serie Muy lenta (< E5 bit/s) Media
Puerto Paralelo Lenta (~ E6 bit/s) Sencilla
Tarjeta ISA Media (~ E7 bit/s) Media
USB Media (~ E7 bit/s) Laboriosa
Tarjeta PCI Muy rápida (> E9 bit/s) Muy laboriosa

Parallel Communication

Usando inpout32.dll para Windows

Windows tiene diferentes modos de acceder a los dispositivos hardware en las series 9x y NT. En las series 9x (95,98,Me) los programas pueden acceder al hardware directamente, al igual que se hacía en DOS. En las series NT (Windows NT y XP), no es posible tal acceso directamente, por lo que se hace necesario un driver de dispositivo que permita el acceso a los puertos como un mecanismo de seguridad. Esto ocasiona que el desarrollo de un driver implique un aumento significativo en costes y tiempo empleado.

Afortunadamente existe una librería que resuelve este problema. Si se detecta un sistema con Windows NT se descomprime un controlador de dispositivo del kernel (HWInterface.sys) y lo instala, mientras que si detecta un sistema Windows 9x, entonces simplemente utiliza código en ensamblador para acceder al hardware.

Pero, ¿Como utilizo esta librería?, ¡ Simple ¡, tiene solamente dos funciones, Inp32 y Out32, y su uso es muy intuitivo.

Cargaremos la libreria dinámicamente, por lo que definiremos ambas funciones primero:


type
  TInp32 = function(Address: SmallInt): SmallInt; stdcall;
  TOut32 = procedure(Address: SmallInt; Data: SmallInt); stdcall;

  • Address representa la dirección del puerto que se desea acceder
  • Out32 envía datos al puerto que se especifica como dirección (Address)
  • Inp32 retorna un byte desde el puerto que se especifica como dirección (Address)

Ahora ya podemos cargar la librería. Esto puede implementarse en una sección como por ejemplo en el método OnCreate dentro del form principal:

type
  TMyForm = class(TForm)
  .........
  private
    { private declarations }
    Inpout32: THandle;  { tipo manejador para el puerto }
    Inp32: TInp32;
    Out32: TOut32;
  .........
implementation
  .........
procedure TMyForm.FormCreate(Sender: TObject);
begin
{$IFDEF WIN32}
  Inpout32 := LoadLibrary('inpout32.dll');
  if (Inpout32 <> 0) then
  begin
    // needs overtyping, plain Delphi's @Inp32 = GetProc... leads to compile errors
    Inp32 := TInp32(GetProcAddress(Inpout32, 'Inp32'));
    if (@Inp32 = nil) then Caption := 'Error';
    Out32 := TOut32(GetProcAddress(Inpout32, 'Out32'));
    if (@Out32 = nil) then Caption := 'Error';
  end
  else Caption := 'Error';
{$ENDIF}
end;

Si se carga la librería en la sección OnCreate no se debe olvidar descargarlo en la sección OnDestroy:

procedure TMyForm.FormDestroy(Sender: TObject);
begin
{$IFDEF WIN32}
  FreeLibrary(Inpout32);
{$ENDIF}
end;

Este es un simple ejemplo de como utilizar la función Inp32:

{$IFDEF WIN32}
  myLabel.Caption := IntToStr(Inp32($0220));
{$ENDIF}

Este código ha sido testeado con una tarjeta ISA en el puerto $0220, utilizando Lazarus 0.9.10 en Windows XP. Por supuesto es necesario tener Windows en la clausula uses para que funcione el código. Para el desarrollo solamente necesitas incluir "input32.dll" en el mismo directorio en que se encuentra la aplicación.

La página principal de esta librería se encuentra en: www.logix4u.net/inpout32.htm *ver discusión*

Using assembler on Windows 9x

On Windows 9x you can also use assembler code. Suppose you wish to write $CC to the $320 port. The following code will do it:

{$ASMMODE ATT}
...
   asm
       movl $0x320, %edx
       movb $0xCC, %al
       outb %al, %dx
   end ['EAX','EDX'];

Troubleshooting on Windows

One possible source of trouble using parallel hardware that does not support Plug And Play on Windows is that Windows may assign the port utilized by your hardware to another device. You can find instructions on the URL below about how to tell Windows not to assign the address of your device to Plug And Play devices:

http://support.microsoft.com/kb/135168

Using ioperm to access ports on Linux

The best way to access the hardware on Linux is throught device drivers, but, due to the complexity of the task of creating a driver, sometimes a quick method is very useful.

In order to use the "ports" unit under Linux your program must be run as root, and IOPerm must be called to set appropriate permissions on the port access. You can find documentation about the "ports" unit here.

The first thing to do is link to (g)libc and call IOPerm. A unit that links to the entire (g)libc exists on free pascal, but this unit gives problems when used directly by application and linking statically to the entire (g)libc library is not a very good idea because it changes often between version in an incompatible manner. Functions like ioperm, however, are unlikely to change.

{$IFDEF Linux}
function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external 'libc';
{$ENDIF}

  • "from" represents the first port to be accessed.
  • "num" is the number of ports after the first to be accessed, so ioperm($220, 8, 1) will give access for the program for all ports between and including $220 and $227.

After linking to IOPerm you can port[<Address>] to access the ports.

{$IFDEF Linux}
  i := ioperm($220, 8, 1);
  port[$220] := $00;
  myLabel.Caption := 'ioperm: ' + IntToStr(i);
  i := Integer(port[$220]);
  myOtherLabel.Caption := 'response: ' + IntToStr(i);
{$ENDIF}

This code was tested with a custom ISA card on port $0220, using Lazarus 0.9.10 on Mandriva Linux 2005 and Damn Small Linux 1.5

General UNIX Hardware Access

{$IFDEF Unix}
Uses Clib;   // retrieve libc library name.
{$ENDIF}

{$IFDEF Unix}
function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external clib;
{$ENDIF}


Note that FPC provides an abstraction for ioperm called "fpioperm" in unit x86, and also defines out and inport functions. These functions are currently implemented for Linux/x86 and FreeBSD/x86.

It is not recommended to link to libc unless absolutely necessary due to possible deployment and portability functions. Also manual linking to libc (by declaring ad hoc libc imports for functions that are available elsewhere) like done above is not recommended (e.g. the above libc import line will unnecessarily fail if the standard C lib is not called libc, like e.g. libroot on BeOS, or on platforms with a non standard C symbol mangling).

Note 2 Using _unit_ libc is not recommended under any circumstances other than Kylix compability. This because the unit is relatively unportable (due to excessive exposure of structures and other private symbols) and must only be modified as little as possible out of Kylix compability issues.

Serial Communication

The External Links section has UNIX and Windows serial port tutorials.

USB

libusb

A cross platform possibility for Linux, BSDs and Mac OS X is libusb.

Headers are listed in http://www.freepascal.org/contrib/db.php3?category=Miscellaneous:

name author version date link remarks
libusb.pp Uwe Zimmermann 0.1.12 2006-06-29 http://www.sciencetronics.com/download/fpc_libusb.tgz
libusb.pas Johann Glaser 2005-01-14 http://www.johann-glaser.at/projects/libusb.pas
fpcusb Joe Jared 0.11-14 2006-02-02 http://relays.osirusoft.com/fpcusb.tgz download link broken

FTDI

If you use one of the chips from FTDI, you can use their pascal headers for their dll interface to the chips.

External Links

Communication Protocols speed comparison:

  1. http://en.wikipedia.org/wiki/Serial_port#Speed
  2. http://www.lvr.com/jansfaq.htm - Jan Axelson's Parallel Port FAQ
  3. http://en.wikipedia.org/wiki/USB#Transfer_Speed
  4. http://en.wikipedia.org/wiki/PCI#Conventional_PCI_bus_specifications

Serial Communication Links:

  1. On UNIX: [1]
  2. On Windows: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/msdn_serial.asp
  3. Synaser component: http://synapse.ararat.cz/
  4. Comport Delphi package: http://sourceforge.net/projects/comport/

ISA Digital Oscilloscope - A example of hardware access with full source included:

[2]