Sign in Join
Wiki copytemporary

Hardware Access/pl: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Hardware Access/pl

OldNewLine
1+## Wstęp
2+
3+Ta strona stanowi początek podręcznika o uzyskiwaniu dostępu do urządzeń sprzętowych w Lazarus. Urządzenia te to między innymi: ISA, PCI, USB, port równoległy, port szeregowy.
4+
5+Jednolity wieloplatformowy dostęp do urządzeń sprzętowych nie jest zaimplementowany ani we Free Pascal Runtime Library, ani w LCL. Podręcznik ten więc przede wszystkim obejmuje metody dostępu do sprzętu na różnych platformach. Kod może być kompilowany w różnych środowiskach za pomocą warunkowej kompilacji, np:
6+
7+``` pascal
8+ uses
9+ Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
10+ {$IFDEF WIN32}
11+ Windows;
12+ {$ENDIF}
13+ {$IFDEF Unix}
14+ ports;
15+ {$ENDIF}
16+```
17+
18+W tej chwili jeszcze nie wiadomo, czy macOS/x86 pozwoli uzyskać dostęp do sprzętu. System może na to nie pozwalać, aczkolwiek można przypuszczać że stosowne sterowniki jak io.dll z czasem się pojawią.
19+
20+## Porównanie portów Równoległych i Szeregowych
21+
22+ISA Cards, PCI Cards and the Parallel Port communicate with the computer using a **parallel** protocol. The Serial Port and USB devices work with a **serial** protocol. Because the processor and thus programming languages all work on a parallel approach to data, access to this kinds of protocols is easier to be implemented on the software side. When you access an Integer variable, for example, you can access it's value with a single command. With a serial protocol, however, you can only know one bit at a time, and you need to glue the pieces together to understand the data.
23+
24+Komunikacja szeregowa jest trudna w implementacji bezpośrednio, ale może być całkiem łatwa, jeśli użyjesz gotowego komponentu. Jeszcze trudniej jest od strony sprzętowej, więc wiele urządzeń używa specjalizowanych układów scalonych, a nawet mikrokontrolerów do jego realizacji.
25+
26+Przedstawmy krótko porównanie protokołów urządzeń i dostępu do nich:
27+
28+| | Prędkość | Stopień trudności implementacji |
29+|-----------------|----------------------------|---------------------------------|
30+| Port szeregowy | bardzo niska (\< E5 bit/s) | średnio trudny |
31+| Port równoległy | niska (~ E6 bit/s) | łatwy |
32+| Karta ISA | średnia (~ E7 bit/s) | średnio trudny |
33+| USB | średnia (~ E7 bit/s) | trudny |
34+| Karta PCI | bardzo duża (\> E9 bit/s) | bardzo trudny |
35+
36+## Komunikacja Równoległa
37+
38+### Korzystanie z biblioteki inpout32.dll w Windows
39+
40+Windows ma różne sposoby dostępu do urządzeń sprzętowych z serii 9x na serię NT. W serii 9x (95, 98, Me) programy mogą mieć dostęp do sprzętu bezpośrednio, tak jak zrobili na DOS. Seria NT (Windows NT i XP), jednak nie pozwalają na takie podejście. Na tej architekturze, cała komunikacja z portami sprzętu musi być obsługiwana przez sterownik urządzenia. Jest to mechanizm bezpieczeństwa, ale rozwijanie sterownika może kosztować zbyt wiele pod względem czasu i pieniędzy dla małych projektów.
41+
42+Happily there is a library that solves this problem. If Windows NT is detected, it decompresses HWInterface.sys kernel device driver and installs it. If Windows 9x is detected, it simply uses assembler opcodes to access the hardware.
43+
44+Ale jak korzystać z tej biblioteki? Proste! Ma ona tylko dwie funkcje, Inp32 i Out32, a ich wykorzystanie jest dość intuicyjne. Będziemy załadowywać biblioteki dynamicznie, więc potrzeba zdefiniować obie te funkcje:
45+
46+``` pascal
47+ type
48+ TInp32 = function(Address: SmallInt): SmallInt; stdcall;
49+ TOut32 = procedure(Address: SmallInt; Data: SmallInt); stdcall;
50+```
51+
52+- Address represents the address of the port you desire to access
53+- Out32 wysyła dane do portu który można określić na podstawie adresów
54+- Inp32 zwraca bajt z portu który można określić na podstawie adresów
55+
56+Now we can load the library. This can be implemented in a place like the OnCreate method of your program's main form:
57+
58+``` pascal
59+ type
60+ TMyForm = class(TForm)
61+ .........
62+ private
63+ { private declarations }
64+ Inpout32: THandle;
65+ Inp32: TInp32;
66+ Out32: TOut32;
67+ .........
68+ implementation
69+ .........
70+ procedure TMyForm.FormCreate(Sender: TObject);
71+ begin
72+ {$IFDEF WIN32}
73+ Inpout32 := LoadLibrary('inpout32.dll');
74+ if (Inpout32 <> 0) then
75+ begin
76+ // needs overtyping, plain Delphi's @Inp32 = GetProc... leads to compile errors
77+ Inp32 := TInp32(GetProcAddress(Inpout32, 'Inp32'));
78+ if (@Inp32 = nil) then Caption := 'Error';
79+ Out32 := TOut32(GetProcAddress(Inpout32, 'Out32'));
80+ if (@Out32 = nil) then Caption := 'Error';
81+ end
82+ else Caption := 'Error';
83+ {$ENDIF}
84+ end;
85+```
86+
87+Jeśli załadowano biblioteki na onCreate tylko nie zapomnij, aby zwolnić je w OnDestroy:
88+
89+``` pascal
90+ procedure TMyForm.FormDestroy(Sender: TObject);
91+ begin
92+ {$IFDEF WIN32}
93+ FreeLibrary(Inpout32);
94+ {$ENDIF}
95+ end;
96+```
97+
98+Oto prosty przykład jak używać funkcji Inp32:
99+
100+``` pascal
101+ {$IFDEF WIN32}
102+ myLabel.Caption := IntToStr(Inp32($0220));
103+ {$ENDIF}
104+```
105+
106+This code was tested with a custom ISA card on port \$0220, using Lazarus 0.9.10 on Windows XP. Of course you will need to have Windows on your uses clause in order for this code to run. For deployment you only need to include "inpout32.dll" in the same directory of our application.
107+
108+This is the homepage for the library: [www.logix4u.net/inpout32.htm](http://www.logix4u.net/inpout32.htm) *see discussion*
109+
110+### Korzystanie z asemblera w systemie Windows 9x
111+
112+W Windows 9x można również użyć kodu asemblera. Załóżmy, że chcemy zapisać \$ CC do portu \$ 320 .Poniższy kod to wykona:
113+
114+``` pascal
115+ {$ASMMODE ATT}
116+ ...
117+ asm
118+ movl $0x320, %edx
119+ movb $0xCC, %al
120+ outb %al, %dx
121+ end ['EAX','EDX'];
122+```
123+
124+### Rozwiązywanie problemów w systemie Windows
125+
126+Jednym z możliwych źródłem kłopotów przy użyciu równoległego sprzętu, który nie obsługuje technologii Plug and Play w systemie Windows jest to, że Windows może przypisać port wykorzystywany przez sprzęt do innego urządzenia. 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:
127+
128+<http://support.microsoft.com/kb/135168>
129+
130+### Uzyskiwanie dostępu do portów w systemie Linux za pomocą ioperm
131+
132+Najlepszym sposobem, aby uzyskać dostęp do sprzętu w systemie Linux jest użycie sterowników urządzeń, ale ponieważ tworzenie sterowników jest kłopotliwe, czasami szybka metoda jest bardziej przydatna.
133+
134+Aby użyć modułu "[[doc:rtl/ports|ports]]" w systemie Linux, twój program musi być uruchomiony jako root, a funkcja IOPerm musi być wywołana w celu ustawienia uprawnień w dostępie do portu. Dokumentację do modułu "[[doc:rtl/ports|ports]]" znajdziesz [tutaj](http://www.freepascal.org/docs-html/rtl/ports/index.html).
135+
136+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.
137+
138+``` pascal
139+ {$IFDEF Linux}
140+ function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external 'libc';
141+ {$ENDIF}
142+```
143+
144+- "from" reprezentuje pierwszy port, który ma być dostępny.
145+- "num" to liczba portów jaka ma być dostępna licząc od pierwszego, np. ioperm(\$220, 8, 1) daje programowi dostęp do wszystkich portów licząc od \$220 do \$227.
146+
147+Po podłączeniu do ioperm można użyć port\[\<adres\>\], aby uzyskać dostęp do portu o podanym adresie.
148+
149+``` pascal
150+ {$IFDEF Linux}
151+ i := ioperm($220, 8, 1);
152+ port[$220] := $00;
153+ myLabel.Caption := 'ioperm: ' + IntToStr(i);
154+ i := Integer(port[$220]);
155+ myOtherLabel.Caption := 'response: ' + IntToStr(i);
156+ {$ENDIF}
157+```
158+
159+Ten kod został przetestowany na zwyczajnej karcie ISA na porcie \$0220, przy użyciu Lazarus 0.9.10 w systemie Mandriva Linux 2005 i Damn Small Linux 1.5
160+
161+### General UNIX Hardware Access
162+
163+``` pascal
164+{$IFDEF Unix}
165+Uses Clib; // retrieve libc library name.
166+{$ENDIF}
167+
168+{$IFDEF Unix}
169+function ioperm(from: Cardinal; num: Cardinal; turn_on: Integer): Integer; cdecl; external clib;
170+{$ENDIF}
171+```
172+
173+**Note** that FPC provides an abstraction for ioperm called "fpioperm" in [[doc:rtl/x86/index.html|unit x86]], and also defines fpIOPL and out-/inport functions. These functions are currently implemented for Linux/x86 and FreeBSD/x86.
174+
175+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).
176+
177+**Note 2** Using **unit** libc is not recommended under any circumstances other than Kylix compatibility. See [[libc unit]]
178+
179+## Komunikacja Szeregowa
180+
181+Jest bardzo łatwa do budowania komunikacji szeregowej przy wykorzystaniu [Synaser library](http://synapse.ararat.cz/doku.php). Przykład przy stosowaniu [Synaser documentation](http://synapse.ararat.cz/doc/help/synaser.html) should be trivial to understand. The most important part is TBlockSerial.Config to configure the speed (in bits per second), data bits, parity bits, stop bits and handshake protocol, if any. The following code was tested with a serial mouse connected to COM 1.
182+
183+``` pascal
184+program comm;
185+
186+{$apptype console}
187+
188+uses
189+ Classes, SysUtils, Synaser;
190+
191+var
192+ ser: TBlockSerial;
193+begin
194+ ser:=TBlockSerial.Create;
195+ try
196+ ser.Connect('COM1');
197+ ser.config(1200, 7, 'N', SB1, False, False);
198+ while True do
199+ Write(IntToHex(ser.RecvByte(10000), 2), ' ');
200+ finally
201+ ser.free;
202+ end;
203+end.
204+```
205+
206+The following code-example is an alternative version of the example above. The example above seems to have a critically fault in its main concept, to be exactly, it is the part with "while true do...". On the Test - System (Asus A6T Laptop with Digitus USB to RS232 Adapter, Ubuntu 8.04.1), this part caused the following error: The application ran only one time successfully per session, when the application was started again, the application was unable to connect to the serial port. Thus, a reboot was necessary everytime the user tried to relaunch the application, which is/was a really annoying bug.
207+
208+The reason is not difficult to understand: The application is in the while true do - loop, which is, to be more precisely, an endless loop. There is no abort-condition, so the only way to close the application is to close the terminal or to press CTRL-C. But if you quit the application this way, the important part with "ser.free", which frees the serial port, will never be called. This problem is described in the following thread in the German Lazarus-Forum [<http://www.lazarusforum.de/viewtopic.php?f=10&t=2082>](http://www.lazarusforum.de/viewtopic.php?f=10&t=2082)
209+
210+There is a bit code around the main application to make every user clear, not to press CTRL-C. If anyone is worrying, why /dev/ttyUSB0 is used for com-port: this is due to the USB to Serial Adapter (from Digitus) on the test-system. If you have an built-in serial port, please use the 'Com0' - declaration like in the code - example above.
211+
212+``` pascal
213+
214+program serialtest;
215+
216+{$mode objfpc}{$H+}
217+
218+uses
219+ {$IFDEF UNIX}{$IFDEF UseCThreads}
220+ cthreads,
221+ {$ENDIF}{$ENDIF}
222+ Classes,SysUtils,Synaser,Crt
223+ { you can add units after this };
224+
225+ var l:boolean;
226+
227+ function check_affirmation():boolean;
228+ var k:string;
229+ begin
230+ Writeln('To quit the application please do NOT use CTRL-C! Instead, please press any key to quit the application! '+
231+ 'Please confirm this notification before the application continues! '+
232+ '[0]=Quit, [1]=Confirm, please continue! ');
233+ Writeln('Your decision: ');
234+ Read(k);
235+ if StrtoInt(k) = 1 then
236+ begin
237+ check_affirmation:=true;
238+ Writeln('OK, application continues ...');
239+ end
240+ else
241+ begin
242+ check_affirmation:=false;
243+ Writeln('Abort');
244+ end
245+ end;
246+
247+ procedure RS232_connect;
248+ var
249+ ser: TBlockSerial;
250+ begin
251+ ser:=TBlockSerial.Create;
252+ try
253+ ser.Connect('/dev/ttyUSB0'); //ComPort
254+ Sleep(1000);
255+ ser.config(1200, 7, 'N', SB1, False, False);
256+ Write('Device: ' + ser.Device + ' Status: ' + ser.LastErrorDesc +' '+
257+ Inttostr(ser.LastError));
258+ Sleep(1000);
259+ repeat
260+ Write(IntToHex(ser.RecvByte(10000), 2), ' ');
261+ until keypressed; //Important!!!
262+ finally
263+ Writeln('Serial Port will be freed...');
264+ ser.free;
265+ Writeln('Serial Port was freed successfully!');
266+ end;
267+ end;
268+
269+ begin
270+ l:=check_affirmation();
271+ if l=true then
272+ RS232_connect()
273+ else
274+ Writeln('Program quit! ');
275+ end.
276+```
277+
278+Ponadto,[[Hardware Access/pl|Zewnętrzne Linki]] sekcja ma tutoriale portów szeregowych UNIX i Windows.
279+
280+It is also worth noting the function of the TBlockSerial.LinuxLock parameter under linux. When set to default of True, a connect will try to create a lock file (eg. "LCK..ttyUSB0") under /var/lock and fail if a lock already exists for the requested port. The lock file will be left over if Free was not called. Setting LinuxLock to False will make Synaser ignore port locking.
281+
282+Alternatives to Synaser:
283+
284+There is also a Visual component [5dpo](http://wiki.lazarus.freepascal.org/5dpo) that is based in Synaser.
285+
286+Another very simple fpc Serial unit is now part of freepascal (at least in version 2.2.2), just put Serial in your Uses list however there does not seem to be any documentation other than the Serial.pp source file.
287+
288+## USB
289+
290+### libusb
291+
292+A cross platform possibility for Linux, BSDs and macOS is [libusb](http://libusb.sourceforge.net/).
293+
294+Headers are listed in <http://www.freepascal.org/contrib/db.php3?category=Miscellaneous>:
295+
296+| name | author | version | date | link | remarks |
297+|----|----|----|----|----|----|
298+| libusb.pp | nowrap \| Uwe Zimmermann | 0.1.12 | nowrap \| 2006-06-29 | <http://www.sciencetronics.com/download/fpc_libusb.tgz> | |
299+| libusb.pas | Johann Glaser | | nowrap \| 2005-01-14 | <http://www.johann-glaser.at/projects/libusb.pas> | |
300+| fpcusb | Joe Jared | 0.11-14 | nowrap \| 2006-02-02 | <http://relays.osirusoft.com/fpcusb.tgz> | nowrap \| download link broken |
301+| libusb.pp | Marko Medic | 1.0 | nowrap \| 2010-12-14 | <http://www.lazarus.freepascal.org/index.php/topic,11435.0.html> | |
302+
303+### FTDI
304+
305+If you use one of the chips from [FTDI](http://www.ftdichip.com/), you can use their pascal headers for their dll interface to the chips.
306+
307+## Zobacz również
308+
309+- [[Target NativeNT]]
310+- [[Networking]]
311+
312+## Zewnętrzne Linki
313+
314+- Communication Protocols speed comparison:
315+
316+1. <http://en.wikipedia.org/wiki/Serial_port#Speed>
317+2. <http://www.lvr.com/jansfaq.htm> - Jan Axelson's Parallel Port FAQ
318+3. <http://en.wikipedia.org/wiki/USB#Transfer_Speed>
319+4. <http://en.wikipedia.org/wiki/PCI#Conventional_PCI_bus_specifications>
320+
321+- Serial Communication Links:
322+
323+1. On UNIX: [1](http://www.easysw.com/~mike/serial/serial.html)
324+2. On Windows: <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/msdn_serial.asp>
325+3. Synaser component: <http://synapse.ararat.cz/>
326+4. Comport Delphi package: <http://sourceforge.net/projects/comport/>
327+
328+- [Digital Oscilloscope](http://eletronicalivre.incubadora.fapesp.br/portal/english/oscilloscope/%7CISA) - A example of hardware access with full source included.
329+
330+---
331+*From the Free Pascal wiki, page "Hardware Access/pl", as it stood on 2020-02-16 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history