Sign in Join
Wiki copytemporary

Lazarus on Raspberry Pi/es: what changed

Revision 3 to 4. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11La información que viene a continuación es una traducción lo más aproximada posible de la entrada en inglés (con alguna variación allí donde requiera ser más detallada o explicativa) y puede que las que se redacten en los otros idiomas alternativos de esta wiki. Cada uno que utilice esta información bajo su propio riesgo, puede contener errores. Antes de aplicar los ejemplos asegurarse que la información es aplicable (y se corresponde) con la placa sobre la que se va a trabajar dada la existencia de diferentes modelos en los cuales tanto los pines de conexión como su funcionalidad y voltaje pueden variar. Si no se tiene conocimiento de lo que se está haciendo mejor no aplicarlo. Por otro lado siempre que se trabaja con dispositivos electrónicos se deben guardar las medidas de seguridad apropiadas dado que un uso indebido de dicho hardware puede conllevar la pérdida de la garantía. Desde aquí no se dá garantía ni implícita ni explícita sobre el correcto funcionamiento de la información aquí mostrada. Antes de seguir este tutorial es recomendable tener conocimientos de electrónica (también para conocer los riesgos de manejar tensiones e intensidades), aunque los componentes empleados en los ejemplos son simples.
22
33![Lazarus on Raspbian Wheezy](/wiki-images/e/ef/Lazarus_on_Raspberry_Pi_Raspian_Wheezy_version_2012-10-28.png) *(Raspberry Pi only)*
44
55**Raspberry Pi** es un ordenador con una placa del tamaño de una tarjeta de crédito (ver fotos más abajo). Ha sido diseñada en Reino Unido (UK) por la Fundación Raspberry Pi con la intención de fomentar el aprendizaje básico de la computación en escuelas. Las Raspberry Pi se utilizan también para propósitos tan diversos como pueden ser servidores de medios, robótica e ingeniería de control.
66
77La Fundación Raspberry Pi recomienda [[Raspbian]] Wheezy como la distribución estandar a utilizar con su hardware. También se utilizan sistemas alternativos tales como RISC y distribuciones Linux variadas y [[Android]].
88
99Lazarus corre en modo nativo bajo la distro Raspbian con sistema operativo Linux.
1010
1111## Installando y compilando Lazarus
1212
1313### Instalación simple bajo Raspbian
1414
1515#### Raspberry Pi 1
1616
1717En la distro de Linux Raspbian es fácil instalar Lazarus y FreePascal. Para lograrlo simplemente abre una ventana de terminal y teclea lo siguiente:
1818
1919``` bash
2020sudo apt-get update
2121sudo apt-get upgrade
2222sudo apt-get install fpc
2323sudo apt-get install lazarus
2424```
2525
2626Esto instala una versión precompilada estable de FreePascal y Lazarus en la distro Raspbian que corre en el hardware Raspberry Pi. Por supuesto se necesita una conexión de red. La instalación puede llevar unos 30 minutos, pero la mayor parte de este proceso tiene lugar automáticamente. Después de la instalación ya se puede arrancar Lazarus desde la sección "Programming" en el menú de comienzo de LXDE.
2727
28-Install Lazarus Rasbian Part1 en.png\|Paso instalación 1 Install Lazarus Rasbian Part2 en.png\|Paso instalación 2 Install Lazarus Rasbian Part3 en.png\|Paso instalación 3 Install Lazarus Rasbian Part4 en.png\|Paso instalación 4
28+![](/wiki-images/0/02/Install_Lazarus_Rasbian_Part1_en.png)
2929
30+Paso instalación 1
31+
32+![](/wiki-images/4/4a/Install_Lazarus_Rasbian_Part2_en.png)
33+
34+Paso instalación 2
35+
36+![](/wiki-images/5/53/Install_Lazarus_Rasbian_Part3_en.png)
37+
38+Paso instalación 3
39+
40+![](/wiki-images/2/24/Install_Lazarus_Rasbian_Part4_en.png)
41+
42+Paso instalación 4
43+
3044Si necesitas una versión más nueva, o si Lazarus/FreePascal muestran errores durante la instalación puedes consultar más información [aquí](http://www.raspberrypi.org/forums/viewtopic.php?f=34&t=88145).
3145
3246#### Raspberry Pi 2
3347
3448Desde junio de 2015 el método de instalación regular "out of the box (listo para usar)" también funciona para Raspberry Pi 2 Modelo B. La versión que lleva instalada es, por tanto, demasiado antigua. Para aquellos que busquen construir los últimos IDE de FreePascal y Lazarus mejor ver [este artículo](http://www.tweaking4all.com/hardware/raspberry-pi/install-lazarus-pascal-on-raspberry-pi-2/).
3549
36-<File:Lazarus> 0 9 30 4 on RPi 2.png\|Lazarus "out of the box" en Raspberry Pi 2
50+![](/wiki-images/c/cc/Lazarus_0_9_30_4_on_RPi_2.png)
3751
52+Lazarus "out of the box" en Raspberry Pi 2
53+
3854160
3955
4056#### Raspberry Pi 3
4157
4258Ver Raspberry Pi 2.
4359
4460![](/wiki-images/5/50/RaspBerryPi3B%2B.png)
4561
46-<File:RaspBerryPi3B+_img1.png>
62+![](/wiki-images/1/12/RaspBerryPi3B%2B_img1.png)
4763
48-<File:RaspBerryPi3B+_img2.png>
64+![](/wiki-images/5/56/RaspBerryPi3B%2B_img2.png)
4965
5066Como se puede observar tiene más pines de los cuales se debe consultar la funcionalidad de cada uno antes de conectar algo.
5167
5268![](/wiki-images/f/f3/RaspBerryPi3B%2B_img3.png)
5369
5470### Compilación cruzada (cross compiling) para Raspberry Pi desde Windows
5571
56721\. Utilizando fpcup
5773
5874Un camino es utilizar fpcup para configurar un compilador cruzado; seguir estas instrucciones:
5975
6076[[fpcup|fpcup#Linux_ARM_cross_compiler]]
6177
62782\. Utilizando scripts
6379
6480Alternativamente, para una aproximación más manual, y utilizando ficheros de proceso por lotes, puedes seguir los siguientes pasos.
6581
66822.1 Prerequisitos
6783
6884`FPC 2.7.1 or higher installed with sourcecode`\
6985`Install the Windows version from the Linaro binutils for linux gnueabihf into %FPCPATH%/bin/win32-armhf-linux `[`1`](https://launchpad.net/linaro-toolchain-binaries/trunk/2013.10/+download/gcc-linaro-arm-linux-gnueabihf-4.8-2013.10_win32.zip)
7086
71872.2 Script ejemplo para construir (adaptar los trayectos a como se necesiten)
7288
7389``` bat
7490set PATH=C:\pp\bin\i386-win32;%PATH%;
7591set FPCMAKEPATH=C:/pp
7692set FPCPATH=C:/pp
7793set OUTPATH=C:/pp271
7894%FPCMAKEPATH%/bin/i386-win32/make distclean OS_TARGET=linux CPU_TARGET=arm CROSSBINDIR=%FPCPATH%/bin/win32-armhf-linux CROSSOPT="-CpARMV6 -CfVFPV2 -OoFASTMATH" FPC=%FPCPATH%/bin/i386-win32/ppc386.exe
7995
8096%FPCMAKEPATH%/bin/i386-win32/make all OS_TARGET=linux CPU_TARGET=arm CROSSBINDIR=%FPCPATH%/bin/win32-armhf-linux CROSSOPT="-CpARMV6 -CfVFPV2 -OoFASTMATH" FPC=%FPCPATH%/bin/i386-win32/ppc386.exe
8197if errorlevel 1 goto quit
8298%FPCMAKEPATH%/bin/i386-win32/make crossinstall CROSSBINDIR=%FPCPATH%/bin/win32-armhf-linux CROSSOPT="-CpARMV6 -CfVFPV2 -OoFASTMATH" OS_TARGET=linux CPU_TARGET=arm FPC=%FPCPATH%/bin/i386-win32/ppc386.exe INSTALL_BASEDIR=%OUTPATH%
8399
84100:quit
85101pause
86102```
87103
88104Con el resultado de ppcrossarm.exe y ARM RTL deberias ser capaz de construir una versión de Lazarus para plataforma cruzada como habitualmente y compilar proyectos FPC para Raspberry Pi y otros dispositivos armhf. Recuerda que no todas las librerias, - especialmente en Windows - se encuentran disponibles para Linux arm.
89105
90106### Compilando desde el código fuente
91107
92108Puede que necesites compilar Lazarus a partir de sus fuentes subverion. Ver \[<http://www.michellcomputing.co.uk/blog/?p=72>: Michell Computing: Lazarus en la Raspberry Pi\] para más detalles..
93109
94-<File:Start> Menu with Lazarus en.png\|Como arrancar Lazarus en Raspbian Wheezy <File:Lazarus> on Raspberry Pi.jpg\|Lazarus bajo Raspberry Pi <File:rpi> gpio pins.png\|Numeración de los pines GPIO
110+![](/wiki-images/8/8d/Start_Menu_with_Lazarus_en.png)
111+
112+Como arrancar Lazarus en Raspbian Wheezy
113+
114+![](/wiki-images/8/87/Lazarus_on_Raspberry_Pi.jpg)
115+
116+Lazarus bajo Raspberry Pi
117+
118+![](/wiki-images/c/c7/Rpi_gpio_pins.png)
119+
120+Numeración de los pines GPIO
95121
96122Compilando desde las fuentes en Raspberry con Gentoo (y otra distro)
97123
98124------------------------------------------------------------------------
99125
100126Si necesitas instalar la última release estable de fpc y, adicional y aisladamente, el compilador fpc del trunk entonces puedes leer la siguiente guía.
101127
102128Esto se escribió utilizando Gentoo, pero esta guía debería ser de utilidad para cualquier otra distro: [[Install fpc on Raspberry with Gentoo]]
103129
104130## Accediendo a hardware externo
105131
106132![](/wiki-images/f/f2/Rpi_pinout_all_50.png)
107133
108134Una de las finalidades en el desarrollo de Raspberry Pi fue la de facilitar el acceso sin esfuerzo a dispositivos externos tales como sensores y actuadores. A nivel de sofware desde FreePascal y Lazarus además presenta varias modalidades de acceso de E/S (Entrada/Salida) / (I/O (Input/Output):
109135
1101361. [[Lazarus on Raspberry Pi|Direct access]] Utilizando la unidad [[BaseUnix]].
1111372. Acceso a través de [[Lazarus on Raspberry Pi|encapsulated shell calls]]
1121383. Acceso a través de [[Lazarus on Raspberry Pi|wiringPi library]].
1131394. Acceso a través de la unidad [[Lazarus on Raspberry Pi|rpi_hal]].
1141405. Acceso a través de la unidad [[Lazarus on Raspberry Pi|PiGpio]].
1151416. Acceso a través de la librería [PascalIO](https://github.com/SAmeis/pascalio).
1161427. Acceso a través de la librería [PXL](http://asphyre.net/products/pxl).
117143
118144### Acceso nativo al hardware
119145
120146![ Programa simple de testeo que permite el acceso al puerto GPIO en Raspberry Pi\|thumb\|300px\|right](/wiki-images/d/d2/Testprogram_for_GPIO_on_RPI_annotated.png) ![Circuito de test para acceso GPIO con el programa asociado\|thumb\|300px\|right](/wiki-images/7/7c/Rpi_testcircuit_1d.png) ![Demo simple con la implementación del circuito propuesto en una placa de prototipos\|thumb\|300px\|right](/wiki-images/7/7e/Rpi_testcircuit_1p_annotaded.png) Este método provee acceso a hardware externo que no requiere librerías adicionales. El único requerimiento es la librería BaseUnix que es parte de la RTL de FreePascal.
121147
122148#### Conmutando un dispositivo a través de un puerto GPIO
123149
124150El siguiente ejemplo lista un programa simple que controla el pin 17 GPIO establecido como salida para conmutar el estado de un LED, transistor o relé. Este programa contiene un [[doc:lcl/stdctrls/ttogglebox.html|ToggleBox]] with name *GPIO17ToggleBox* y para logging retorna códigos a un [[doc:lcl/stdctrls/tmemo.html|TMemo]] llamado *LogMemo*.
125151
126152Para el ejemplo, el ánodo del LED se ha conectado al Pin 11 del conector Pi (que a su vez su correspondencia es con el pin 17 del chip BCM2835 SOC) y por otro lado el cátodo del LED se ha conectado al pin 6 del conector (que corresponde a masa (GND: Ground) pero poniendo una resistencia entre medias de 68 Ohm (R1 en el esquema) tal como se describió previamente por Upton and Halfacree (esto nos permite limitar convenientemente la intensidad que circula por el LED). Subsecuentemente el LED puede ser conmutado entre dos estados ON / OFF mediante el toggle box de la aplicación.
127153
128154El código puede requerir en un principio que se ejecute como root, i.e. adicionalmente con una cuenta tipo root (no recomendado) o a través del mandato **su** antepuesto al nombre del programa lo que nos promocionará el acceso como super usuario (su: super user). Una mejor opción es añadir el usuario con el que trabajemos a los grupos gpio, i2c y spi tal como se indica a continuación:
129155
130156``` bash
131157sudo adduser pi gpio
132158sudo adduser pi i2c
133159sudo adduser pi spi
134160```
135161
136162*Unidad de control:*
137163
138164``` pascal
139165unit Unit1;
140166
141167{Demo application for GPIO on Raspberry Pi}
142168{Inspired by the Python input/output demo application by Gareth Halfacree}
143169{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
144170
145171{$mode objfpc}{$H+}
146172
147173interface
148174
149175uses
150176 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
151177 Unix, BaseUnix;
152178
153179type
154180
155181 { TForm1 }
156182
157183 TForm1 = class(TForm)
158184 LogMemo: TMemo;
159185 GPIO17ToggleBox: TToggleBox;
160186 procedure FormActivate(Sender: TObject);
161187 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
162188 procedure GPIO17ToggleBoxChange(Sender: TObject);
163189 private
164190 { private declarations }
165191 public
166192 { public declarations }
167193 end;
168194
169195const
170196 PIN_17: PChar = '17';
171197 PIN_ON: PChar = '1';
172198 PIN_OFF: PChar = '0';
173199 OUT_DIRECTION: PChar = 'out';
174200
175201var
176202 Form1: TForm1;
177203 gReturnCode: longint; {stores the result of the IO operation}
178204
179205implementation
180206
181207{$R *.lfm}
182208
183209{ TForm1 }
184210
185211procedure TForm1.FormActivate(Sender: TObject);
186212var
187213 fileDesc: integer;
188214begin
189215 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
190216 try
191217 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
192218 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
193219 LogMemo.Lines.Add(IntToStr(gReturnCode));
194220 finally
195221 gReturnCode := fpclose(fileDesc);
196222 LogMemo.Lines.Add(IntToStr(gReturnCode));
197223 end;
198224 { Set SoC pin 17 as output: }
199225 try
200226 fileDesc := fpopen('/sys/class/gpio/gpio17/direction', O_WrOnly);
201227 gReturnCode := fpwrite(fileDesc, OUT_DIRECTION[0], 3);
202228 LogMemo.Lines.Add(IntToStr(gReturnCode));
203229 finally
204230 gReturnCode := fpclose(fileDesc);
205231 LogMemo.Lines.Add(IntToStr(gReturnCode));
206232 end;
207233end;
208234
209235procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
210236var
211237 fileDesc: integer;
212238begin
213239 { Free SoC pin 17: }
214240 try
215241 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
216242 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
217243 LogMemo.Lines.Add(IntToStr(gReturnCode));
218244 finally
219245 gReturnCode := fpclose(fileDesc);
220246 LogMemo.Lines.Add(IntToStr(gReturnCode));
221247 end;
222248end;
223249
224250procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
225251var
226252 fileDesc: integer;
227253begin
228254 if GPIO17ToggleBox.Checked then
229255 begin
230256 { Swith SoC pin 17 on: }
231257 try
232258 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
233259 gReturnCode := fpwrite(fileDesc, PIN_ON[0], 1);
234260 LogMemo.Lines.Add(IntToStr(gReturnCode));
235261 finally
236262 gReturnCode := fpclose(fileDesc);
237263 LogMemo.Lines.Add(IntToStr(gReturnCode));
238264 end;
239265 end
240266 else
241267 begin
242268 { Switch SoC pin 17 off: }
243269 try
244270 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
245271 gReturnCode := fpwrite(fileDesc, PIN_OFF[0], 1);
246272 LogMemo.Lines.Add(IntToStr(gReturnCode));
247273 finally
248274 gReturnCode := fpclose(fileDesc);
249275 LogMemo.Lines.Add(IntToStr(gReturnCode));
250276 end;
251277 end;
252278end;
253279
254280end.
255281```
256282
257283*Programa principal:*
258284
259285``` pascal
260286program io_test;
261287
262288{$mode objfpc}{$H+}
263289
264290uses
265291 {$IFDEF UNIX}{$IFDEF UseCThreads}
266292 cthreads,
267293 {$ENDIF}{$ENDIF}
268294 Interfaces, // this includes the LCL widgetset
269295 Forms, Unit1
270296 { puedes añadir unidades después de esto };
271297
272298{$R *.res}
273299
274300begin
275301 Application.Initialize;
276302 Application.CreateForm(TForm1, Form1);
277303 Application.Run;
278304end.
279305```
280306
281307#### Leyendo el estado de un pin
282308
283309![Programa de desmostración para la lectura del estado de un pin GPIO\|thumb\|300px\|right](/wiki-images/7/73/2013-04-28-193243_1280x1024_scrot.png) ![Circuito de chequeo para acceso GPIO mediante el programa mostrado\|thumb\|300px\|right](/wiki-images/f/f4/Rpi_testcircuit_2d.png) ![Posible implementación de este circuito de chequeo mediante el uso de placa de prototipos\|thumb\|300px\|right](/wiki-images/2/2f/Rpi_testcircuit_2p_annotaded.png)
284310
285311Por supuesto también es posible leer el estado de un pulsador conectado a un puerto GPIO (General Porpouse Inpunt Output).
286312
287313El siguiente ejemplo es muy similar al anterior. Controla el pin GPIO 18 como entrada para un dispositivo binario tal como un pulsador, un transistor o un relé. Este programa contiene un [[doc:lcl/stdctrls/tcheckbox.html|CheckBox]] con el nombre *GPIO18CheckBox* y un [[doc:lcl/stdctrls/tmemo.html|TMemo]] llamado *LogMemo* para los códigos retornados de logging.
288314
289315Para el ejemplo se ha conectado un pulsador al Pin 12 del conector de la Pi (correspondiente al pin GPIO 18 del SOC BCM2835) a través de una resistencia de 10 KOhm conectada al pin 1 (+3.3V, ver diagrama de cableado). El otro polo se ha cableado al pin 6 del conector (corresponde a la masa o GND). El programa detecta el estado del pulsador y commuta correlativamente a On u Off según el estado del mismo.
290316
291317Ten en cuenta que el potencial del pin 18 es "alto" (gracias a la conexión al pin 1 mediate la resistencia) si el pulsador está sin pulsar y "bajo" si se encuentra pulsado (porque en esta situación el pin 18 se encuentra conectado a masa (GND) a través del pulsador). Por tanto, el pin GPIO marca 0 si el botón está presionado y 1 si está sin pulsar.
292318
293319Este programa tiene que ser ejecutado también como usuario root.
294320
295321*Unidad de control:*
296322
297323``` pascal
298324unit Unit1;
299325
300326{Demo application for GPIO on Raspberry Pi}
301327{Inspired by the Python input/output demo application by Gareth Halfacree}
302328{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
303329
304330{This application reads the status of a push-button}
305331
306332{$mode objfpc}{$H+}
307333
308334interface
309335
310336uses
311337 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
312338 ButtonPanel, Unix, BaseUnix;
313339
314340type
315341
316342 { TForm1 }
317343
318344 TForm1 = class(TForm)
319345 ApplicationProperties1: TApplicationProperties;
320346 GPIO18CheckBox: TCheckBox;
321347 LogMemo: TMemo;
322348 procedure ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
323349 procedure FormActivate(Sender: TObject);
324350 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
325351 private
326352 { private declarations }
327353 public
328354 { public declarations }
329355 end;
330356
331357const
332358 PIN_18: PChar = '18';
333359 IN_DIRECTION: PChar = 'in';
334360
335361var
336362 Form1: TForm1;
337363 gReturnCode: longint; {stores the result of the IO operation}
338364
339365implementation
340366
341367{$R *.lfm}
342368
343369{ TForm1 }
344370
345371procedure TForm1.FormActivate(Sender: TObject);
346372var
347373 fileDesc: integer;
348374begin
349375 { Prepare SoC pin 18 (pin 12 on GPIO port) for access: }
350376 try
351377 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
352378 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
353379 LogMemo.Lines.Add(IntToStr(gReturnCode));
354380 finally
355381 gReturnCode := fpclose(fileDesc);
356382 LogMemo.Lines.Add(IntToStr(gReturnCode));
357383 end;
358384 { Set SoC pin 18 as input: }
359385 try
360386 fileDesc := fpopen('/sys/class/gpio/gpio18/direction', O_WrOnly);
361387 gReturnCode := fpwrite(fileDesc, IN_DIRECTION[0], 2);
362388 LogMemo.Lines.Add(IntToStr(gReturnCode));
363389 finally
364390 gReturnCode := fpclose(fileDesc);
365391 LogMemo.Lines.Add(IntToStr(gReturnCode));
366392 end;
367393end;
368394
369395procedure TForm1.ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
370396var
371397 fileDesc: integer;
372398 buttonStatus: string[1] = '1';
373399begin
374400 try
375401 { Open SoC pin 18 (pin 12 on GPIO port) in read-only mode: }
376402 fileDesc := fpopen('/sys/class/gpio/gpio18/value', O_RdOnly);
377403 if fileDesc > 0 then
378404 begin
379405 { Read status of this pin (0: button pressed, 1: button released): }
380406 gReturnCode := fpread(fileDesc, buttonStatus[1], 1);
381407 LogMemo.Lines.Add(IntToStr(gReturnCode) + ': ' + buttonStatus);
382408 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
383409 if buttonStatus = '0' then
384410 GPIO18CheckBox.Checked := true
385411 else
386412 GPIO18CheckBox.Checked := false;
387413 end;
388414 finally
389415 { Close SoC pin 18 (pin 12 on GPIO port) }
390416 gReturnCode := fpclose(fileDesc);
391417 LogMemo.Lines.Add(IntToStr(gReturnCode));
392418 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
393419 end;
394420end;
395421
396422procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
397423var
398424 fileDesc: integer;
399425begin
400426 { Free SoC pin 18: }
401427 try
402428 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
403429 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
404430 LogMemo.Lines.Add(IntToStr(gReturnCode));
405431 finally
406432 gReturnCode := fpclose(fileDesc);
407433 LogMemo.Lines.Add(IntToStr(gReturnCode));
408434 end;
409435end;
410436
411437end.
412438```
413439
414440El programa main es idéntico al del ejemplo de arriba.
415441
416442### Acceso hardware mediante llamadas encapsuladas del shell
417443
418444Otro modo de acceder al hardware es mediante el encapsulamiento de mandatos a través del shell. Esto se consigue mediante el uso de la función [[Executing External Programs|fpsystem]]. Este método permite el acceso a funciones que no están soportadas por la unidad BaseUnix. El siguiente código implementa un programa que tiene la misma funcionalidad que as the program resulting from the first listing above.
419445
420446*Controlling unit:*
421447
422448``` pascal
423449unit Unit1;
424450
425451{Demo application for GPIO on Raspberry Pi}
426452{Inspired by the Python input/output demo application by Gareth Halfacree}
427453{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
428454
429455{$mode objfpc}{$H+}
430456
431457interface
432458
433459uses
434460 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Unix;
435461
436462type
437463
438464 { TForm1 }
439465
440466 TForm1 = class(TForm)
441467 LogMemo: TMemo;
442468 GPIO17ToggleBox: TToggleBox;
443469 procedure FormActivate(Sender: TObject);
444470 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
445471 procedure GPIO17ToggleBoxChange(Sender: TObject);
446472 private
447473 { private declarations }
448474 public
449475 { public declarations }
450476 end;
451477
452478var
453479 Form1: TForm1;
454480 gReturnCode: longint; {stores the result of the IO operation}
455481
456482implementation
457483
458484{$R *.lfm}
459485
460486{ TForm1 }
461487
462488procedure TForm1.FormActivate(Sender: TObject);
463489begin
464490 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
465491 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/export');
466492 LogMemo.Lines.Add(IntToStr(gReturnCode));
467493 { Set SoC pin 17 as output: }
468494 gReturnCode := fpsystem('echo "out" > /sys/class/gpio/gpio17/direction');
469495 LogMemo.Lines.Add(IntToStr(gReturnCode));
470496end;
471497
472498procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
473499begin
474500 { Free SoC pin 17: }
475501 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/unexport');
476502 LogMemo.Lines.Add(IntToStr(gReturnCode));
477503end;
478504
479505procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
480506begin
481507 if GPIO17ToggleBox.Checked then
482508 begin
483509 { Swith SoC pin 17 on: }
484510 gReturnCode := fpsystem('echo "1" > /sys/class/gpio/gpio17/value');
485511 LogMemo.Lines.Add(IntToStr(gReturnCode));
486512 end
487513 else
488514 begin
489515 { Switch SoC pin 17 off: }
490516 gReturnCode := fpsystem('echo "0" > /sys/class/gpio/gpio17/value');
491517 LogMemo.Lines.Add(IntToStr(gReturnCode));
492518 end;
493519end;
494520
495521end.
496522```
497523
498524El programa main es idéntico al del ejemplo de arriba. Este programa necesita ejecutarse con privilegios de root también.
499525
500526### Procedimientos y funciones de wiringPi
501527
502528Alex Schaller's wrapper unit for Gordon Henderson's Arduino compatible wiringPi library provides a numbering scheme that resembles that of Arduino boards.
503529
504530**Function wiringPiSetup:longint:** Initializes wiringPi system using the wiringPi pin numbering scheme.
505531
506532**Procedure wiringPiGpioMode(mode:longint):** Initializes wiringPi system with the Broadcom GPIO pin numbering scheme.
507533
508534**Procedure pullUpDnControl(pin:longint;** pud:longint): controls the internal pull-up/down resistors on a GPIO pin.
509535
510536**Procedure pinMode(pin:longint; mode:longint):** sets the mode of a pin to either INPUT, OUTPUT, or PWM_OUTPUT.
511537
512538**Procedure digitalWrite(pin:longint; value:longint):** sets an output bit.
513539
514540**Procedure pwmWrite(pin:longint; value:longint):** sets an output PWM value between 0 and 1024.
515541
516542**Function digitalRead(pin:longint):longint:** reads the value of a given Pin, returning 1 or 0.
517543
518544**Procedure delay(howLong:dword):** waits for at least howLong milliseconds.
519545
520546**Procedure delayMicroseconds(howLong:dword):** waits for at least howLong microseconds.
521547
522548**Function millis:dword:** returns the number of milliseconds since the program called one of the wiringPiSetup functions.
523549
524550### rpi_hal-Hardware Abstraction Library (funciones y procedimientos GPIO, I2C y SPI de la librería de abstracción hardware de la RaspBerry Pi)
525551
526552Esta unidad con cerca de 1700 líneas de código aportada por Stefan Fischer, aporta procedimientos y funciones para acceso HW I2C, SPI y GPIO en la RaspBerry Pi:
527553
528554Justamente un extracto de los procedimientos y funciones disponibles:
529555
530556**procedure gpio_set_pin (pin:longword;highlevel:boolean);** { Establece RPi GPIO pin a nivel alto o bajo; Velocidad @ 700MHz -\> 0.65MHz }
531557
532558**function gpio_get_PIN (pin:longword):boolean;** { Get RPi GPIO pin Level is true when Pin level is '1'; false when '0'; Speed @ 700MHz -\> 1.17MHz }
533559
534560**procedure gpio_set_input (pin:longword);** { Establece RPi GPIO pin en modo entrada }
535561
536562**procedure gpio_set_output(pin:longword);** { Establece RPi GPIO pin en modo salida}
537563
538564**procedure gpio_set_alt (pin,altfunc:longword);** { Establece RPi GPIO pin to alternate function nr. 0..5 }
539565
540566**procedure gpio_set_gppud (mask:longword);** { Establece RPi GPIO Pull-up/down Register (GPPUD) with mask }
541567
542568...
543569
544570**function rpi_snr :string;** { Emtrega el SNR: 0000000012345678 }
545571
546572**function rpi_hw :string;** { Entrega el tipo de procesador: BCM2708 }
547573
548574**function rpi_proc:string;** { ARMv6-compatible processor rev 7 (v6l) }
549575
550576...
551577
552578**function i2c_bus_write(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
553579
554580**function i2c_bus_read (baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
555581
556582**function i2c_string_read(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : string;**
557583
558584**function i2c_string_write(baseadr,reg:word; s:string; testnr:integer) : integer;**
559585
560586...
561587
562588**procedure SPI_Write(devnum:byte; reg,data:word);**
563589
564590**function SPI_Read(devnum:byte; reg:word) : byte;**
565591
566592**procedure SPI_BurstRead2Buffer (devnum,start_reg:byte; xferlen:longword);**
567593
568594**procedure SPI_BurstWriteBuffer (devnum,start_reg:byte; xferlen:longword);** { Write 'len' Bytes from Buffer SPI Dev startig at address 'reg' }
569595
570596...
571597
572598*Test Program (testrpi.pas):*
573599
574600``` pascal
575601//Progama simple de chequeo, el cual utiliza rpi_hal;
576602
577603 program testrpi;
578604 uses rpi_hal;
579605 begin
580606 writeln('Show CPU-Info, RPI-HW-Info and Registers:');
581607 rpi_show_all_info;
582608 writeln('Let Status LED Blink. Using GPIO functions:');
583609 GPIO_PIN_TOGGLE_TEST;
584610 writeln('Test SPI Read function. (piggy back board with installed RFM22B Module is required!)');
585611 Test_SPI;
586612 end.
587613```
588614
589615### Unidad nativa PiGpio de bajo nivel escrita en pascal (control GPIO en lugar de la librería c de wiringPi)
590616
591617*Esta unit (pigpio.pas[2](https://docs.google.com/file/d/0B-b-5ooIWPvGN1BIcEJzRDgyeUE/edit?usp=sharing)) de 270 líneas de código aportada por Gabor Szollosi, funciona muy rápido (para ex. GPIO pin output conmutando a una frecuencia de 8 MHz) :*
592618
593619``` pascal
594620
595621unit PiGpio;
596622{
597623 BCM2835 GPIO Registry Driver, also can use to manipulate cpu other registry areas
598624
599625 This code is tested only Broadcom bcm2835 cpu, different arm cpus may need different
600626 gpio driver implementation
601627
602628 2013 Gabor Szollosi
603629}
604630{$mode objfpc}{$H+}
605631
606632interface
607633
608634uses
609635 Classes, SysUtils;
610636
611637const
612638 REG_GPIO = $3F000;// bcm2835 gpio register 0x2000 0000 (RPi1), 0x3F00 0000 (RPi2)
613639 // new fpMap uses page offset, one page is 4096 bytes = 0x1000 so simply calculate 0x2000 0000 / 0x1000 = 0x2000 0
614640 PAGE_SIZE = 4096;
615641 BLOCK_SIZE = 4096;
616642 // The BCM2835 has 54 GPIO pins.
617643 // BCM2835 data sheet, Page 90 onwards.
618644 // There are 6 control registers, each control the functions of a block
619645 // of 10 pins.
620646
621647 CLOCK_BASE = (REG_GPIO + $101);
622648 GPIO_BASE = (REG_GPIO + $200);
623649 GPIO_PWM = (REG_GPIO + $20C);
624650
625651 INPUT = 0;
626652 OUTPUT = 1;
627653 PWM_OUTPUT = 2;
628654 LOW = False;
629655 HIGH = True;
630656 PUD_OFF = 0;
631657 PUD_DOWN = 1;
632658 PUD_UP = 2;
633659
634660 // PWM
635661
636662 PWM_CONTROL = 0;
637663 PWM_STATUS = 4;
638664 PWM0_RANGE = 16;
639665 PWM0_DATA = 20;
640666 PWM1_RANGE = 32;
641667 PWM1_DATA = 36;
642668
643669 PWMCLK_CNTL = 160;
644670 PWMCLK_DIV = 164;
645671
646672 PWM1_MS_MODE = $8000; // Run in MS mode
647673 PWM1_USEFIFO = $2000; // Data from FIFO
648674 PWM1_REVPOLAR = $1000; // Reverse polarity
649675 PWM1_OFFSTATE = $0800; // Ouput Off state
650676 PWM1_REPEATFF = $0400; // Repeat last value if FIFO empty
651677 PWM1_SERIAL = $0200; // Run in serial mode
652678 PWM1_ENABLE = $0100; // Channel Enable
653679
654680 PWM0_MS_MODE = $0080; // Run in MS mode
655681 PWM0_USEFIFO = $0020; // Data from FIFO
656682 PWM0_REVPOLAR = $0010; // Reverse polarity
657683 PWM0_OFFSTATE = $0008; // Ouput Off state
658684 PWM0_REPEATFF = $0004; // Repeat last value if FIFO empty
659685 PWM0_SERIAL = $0002; // Run in serial mode
660686 PWM0_ENABLE = $0001; // Channel Enable
661687
662688type
663689
664690 { TIoPort }
665691
666692 TIoPort = class // IO bank object
667693 private //
668694
669695 //function get_pinDirection(aPin: TGpIoPin): TGpioPinConf;
670696
671697 public
672698 FGpio: ^LongWord;
673699 FClk: ^LongWord;
674700 FPwm: ^LongWord;
675701 procedure SetPinMode(gpin, mode: byte);
676702 function GetBit(gpin : byte):boolean;inline; // gets pin bit}
677703 procedure ClearBit(gpin : byte);inline;// write pin to 0
678704 procedure SetBit(gpin : byte);inline;// write pin to 1
679705 procedure SetPullMode(gpin, mode: byte);
680706 procedure PwmWrite(gpin : byte; value : LongWord);inline;// write pin to pwm value
681707 end;
682708
683709 { TIoDriver }
684710
685711 TIoDriver = class
686712 private
687713
688714 public
689715 destructor Destroy;override;
690716 function MapIo:boolean;// creates io memory mapping
691717 procedure UnmapIoRegisrty(FMap: TIoPort);// close io memory mapping
692718 function CreatePort(PortGpio, PortClk, PortPwm: LongWord):TIoPort; // create new IO port
693719 end;
694720
695721var
696722
697723 fd: integer;// /dev/mem file handle
698724procedure delayNanoseconds (howLong : LongWord);
699725
700726implementation
701727
702728uses
703729 baseUnix, Unix;
704730
705731procedure delayNanoseconds (howLong : LongWord);
706732var
707733 sleeper, dummy : timespec;
708734begin
709735 sleeper.tv_sec := 0 ;
710736 sleeper.tv_nsec := howLong ;
711737 fpnanosleep (@sleeper,@dummy) ;
712738end;
713739{ TIoDriver }
714740//*******************************************************************************
715741destructor TIoDriver.Destroy;
716742begin
717743 inherited Destroy;
718744end;
719745//*******************************************************************************
720746function TIoDriver.MapIo: boolean;
721747begin
722748 Result := True;
723749 fd := fpopen('/dev/mem', O_RdWr or O_Sync); // Open the master /dev/memory device
724750 if fd < 0 then
725751 begin
726752 Result := False; // unsuccessful memory mapping
727753 end;
728754 //
729755end;
730756//*******************************************************************************
731757procedure TIoDriver.UnmapIoRegisrty(FMap:TIoPort);
732758begin
733759 if FMap.FGpio <> nil then
734760 begin
735761 fpMUnmap(FMap.FGpio,PAGE_SIZE);
736762 FMap.FGpio := Nil;
737763 end;
738764 if FMap.FClk <> nil then
739765 begin
740766 fpMUnmap(FMap.FClk,PAGE_SIZE);
741767 FMap.FClk := Nil;
742768 end;
743769 if FMap.FPwm <> nil then
744770 begin
745771 fpMUnmap(FMap.FPwm ,PAGE_SIZE);
746772 FMap.FPwm := Nil;
747773 end;
748774end;
749775//*******************************************************************************
750776function TIoDriver.CreatePort(PortGpio, PortClk, PortPwm: LongWord): TIoPort;
751777begin
752778 Result := TIoPort.Create;// new io port, pascal calls new fpMap, where offst is page sized 4096 bytes!!!
753779 Result.FGpio := FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortGpio); // port config gpio memory
754780 Result.FClk:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortClk);; // port clk
755781 Result.FPwm:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortPwm);; // port pwm
756782end;
757783//*******************************************************************************
758784procedure TIoPort.SetPinMode(gpin, mode: byte);
759785var
760786 fSel, shift, alt : byte;
761787 gpiof, clkf, pwmf : ^LongWord;
762788begin
763789 fSel := (gpin div 10)*4 ; //Select Gpfsel 0 to 5 register
764790 shift := (gpin mod 10)*3 ; //0-9 pin shift
765791 gpiof := Pointer(LongWord(Self.FGpio)+fSel);
766792 if (mode = INPUT) then
767793 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) //7 shl shift komplemens - Sets bits to zero = input
768794 else if (mode = OUTPUT) then
769795 begin
770796 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (1 shl shift);
771797 end
772798 else if (mode = PWM_OUTPUT) then
773799 begin
774800 Case gpin of
775801 12,13,40,41,45 : alt:= 4 ;
776802 18,19 : alt:= 2 ;
777803 else alt:= 0 ;
778804 end;
779805 If alt > 0 then
780806 begin
781807 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (alt shl shift);
782808 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
783809 clkf^ := $5A000011 or (1 shl 5) ; //stop clock
784810 delayNanoseconds(200);
785811 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_DIV);
786812 clkf^ := $5A000000 or (32 shl 12) ; // set pwm clock div to 32 (19.2/3 = 600KHz)
787813 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
788814 clkf^ := $5A000011 ; //start clock
789815 Self.ClearBit(gpin);
790816 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
791817 pwmf^ := 0 ; // Disable PWM
792818 delayNanoseconds(200);
793819 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_RANGE);
794820 pwmf^ := $400 ; //max: 1023
795821 delayNanoseconds(200);
796822 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_RANGE);
797823 pwmf^ := $400 ; //max: 1023
798824 delayNanoseconds(200);
799825 // Enable PWMs
800826 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_DATA);
801827 pwmf^ := 0 ; //start value
802828 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_DATA);
803829 pwmf^ := 0 ; //start value
804830 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
805831 pwmf^ := PWM0_ENABLE or PWM1_ENABLE ;
806832 end;
807833 end;
808834end;
809835//*******************************************************************************
810836procedure TIoPort.SetBit(gpin : byte);
811837var
812838 gpiof : ^LongWord;
813839begin
814840 gpiof := Pointer(LongWord(Self.FGpio) + 28 + (gpin shr 5) shl 2);
815841 gpiof^ := 1 shl gpin;
816842end;
817843//*******************************************************************************
818844procedure TIoPort.ClearBit(gpin : byte);
819845var
820846 gpiof : ^LongWord;
821847begin
822848 gpiof := Pointer(LongWord(Self.FGpio) + 40 + (gpin shr 5) shl 2);
823849 gpiof^ := 1 shl gpin;
824850end;
825851//*******************************************************************************
826852function TIoPort.GetBit(gpin : byte):boolean;
827853var
828854 gpiof : ^LongWord;
829855begin
830856 gpiof := Pointer(LongWord(Self.FGpio) + 52 + (gpin shr 5) shl 2);
831857 if (gpiof^ and (1 shl gpin)) = 0 then Result := False else Result := True;
832858end;
833859//*******************************************************************************
834860procedure TIoPort.SetPullMode(gpin, mode: byte);
835861var
836862 pudf, pudclkf : ^LongWord;
837863begin
838864 pudf := Pointer(LongWord(Self.FGpio) + 148 );
839865 pudf^ := mode; //mode = 0, 1, 2 :Off, Down, Up
840866 delayNanoseconds(200);
841867 pudclkf := Pointer(LongWord(Self.FGpio) + 152 + (gpin shr 5) shl 2);
842868 pudclkf^ := 1 shl gpin ;
843869 delayNanoseconds(200);
844870 pudf^ := 0 ;
845871 pudclkf^ := 0 ;
846872end;
847873//*******************************************************************************
848874procedure TIoPort.PwmWrite(gpin : byte; value : Longword);
849875var
850876 pwmf : ^LongWord;
851877 port : byte;
852878begin
853879 Case gpin of
854880 12,18,40 : port:= PWM0_DATA ;
855881 13,19,41,45 : port:= PWM1_DATA ;
856882 else exit;
857883 end;
858884 pwmf := Pointer(LongWord(Self.FPwm) + port);
859885 pwmf^ := value and $FFFFFBFF; // $400 complemens
860886end;
861887//*******************************************************************************
862888end.
863889```
864890
865891*Controlling Lazarus unit:(Project files[3](https://drive.google.com/folderview?id=0B-b-5ooIWPvGU043ZTZ0cUc2YkE&usp=sharing))*
866892
867893``` pascal
868894unit Unit1;
869895
870896{Demo application for GPIO on Raspberry Pi}
871897{Inspired by the Python input/output demo application by Gareth Halfacree}
872898{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
873899
874900{$mode objfpc}{$H+}
875901
876902interface
877903
878904uses
879905 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
880906 ExtCtrls, Unix, PiGpio;
881907
882908type
883909
884910 { TForm1 }
885911
886912 TForm1 = class(TForm)
887913 GPIO25In: TButton;
888914 SpeedButton: TButton;
889915 LogMemo: TMemo;
890916 GPIO23switch: TToggleBox;
891917 Timer1: TTimer;
892918 GPIO18Pwm: TToggleBox;
893919 Direction: TToggleBox;
894920 procedure DirectionChange(Sender: TObject);
895921 procedure GPIO18PwmChange(Sender: TObject);
896922 procedure GPIO25InClick(Sender: TObject);
897923 procedure FormActivate(Sender: TObject);
898924 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
899925 procedure GPIO23switchChange(Sender: TObject);
900926 procedure SpeedButtonClick(Sender: TObject);
901927 procedure Timer1Timer(Sender: TObject);
902928 private
903929 { private declarations }
904930 public
905931 { public declarations }
906932 end;
907933
908934const
909935 INPUT = 0;
910936 OUTPUT = 1;
911937 PWM_OUTPUT = 2;
912938 LOW = False;
913939 HIGH = True;
914940 PUD_OFF = 0;
915941 PUD_DOWN = 1;
916942 PUD_UP = 2;
917943 // Convert Raspberry Pi P1 pins (Px) to GPIO port
918944 P3 = 0;
919945 P5 = 1;
920946 P7 = 4;
921947 P8 = 14;
922948 P10 = 15;
923949 P11 = 17;
924950 P12 = 18;
925951 P13 = 21;
926952 P15 = 22;
927953 P16 = 23;
928954 P18 = 24;
929955 P19 = 10;
930956 P21 = 9;
931957 P22 = 25;
932958 P23 = 11;
933959 P24 = 8;
934960 P26 = 7;
935961
936962var
937963 Form1: TForm1;
938964 GPIO_Driver: TIoDriver;
939965 GpF: TIoPort;
940966 PWM :Boolean;
941967 i, d : integer;
942968 Pin,Pout,Ppwm : byte;
943969
944970implementation
945971
946972{$R *.lfm}
947973
948974{ TForm1 }
949975
950976procedure TForm1.FormActivate(Sender: TObject);
951977begin
952978 if not GPIO_Driver.MapIo then
953979 begin
954980 LogMemo.Lines.Add('Error mapping gpio registry');
955981 end
956982 else
957983 begin
958984 GpF := GpIo_Driver.CreatePort(GPIO_BASE, CLOCK_BASE, GPIO_PWM);
959985 end ;
960986 Timer1.Enabled:= True;
961987 Timer1.Interval:= 25; //25 ms controll interval
962988 Pin := P22;
963989 Pout := P16;
964990 Ppwm := P12;
965991 i:=1;
966992 GpF.SetPinMode(Pout,OUTPUT);
967993 GpF.SetPinMode(Pin,INPUT);
968994 GpF.SetPullMode(Pin,PUD_Up); // Input PullUp High level
969995end;
970996
971997procedure TForm1.GPIO25InClick(Sender: TObject);
972998begin
973999 If GpF.GetBit(Pin) then LogMemo.Lines.Add('In: '+IntToStr(1))
9741000 else LogMemo.Lines.Add('In: '+IntToStr(0));
9751001end;
9761002
9771003procedure TForm1.GPIO18PwmChange(Sender: TObject);
9781004begin
9791005 if GPIO18Pwm.Checked then
9801006 begin
9811007 GpF.SetPinMode(Ppwm,PWM_OUTPUT);
9821008 PWM := True; //PWM on
9831009 end
9841010 else
9851011 begin
9861012 GpF.SetPinMode(Ppwm,INPUT);
9871013 PWM := False; //PWM off
9881014 end;
9891015end;
9901016
9911017procedure TForm1.DirectionChange(Sender: TObject);
9921018begin
9931019 if Direction.Checked then d:=10 else d:=-10;
9941020end;
9951021
9961022
9971023procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
9981024begin
9991025 GpF.SetPinMode(Ppwm,INPUT);
10001026 GpF.ClearBit(Pout);
10011027 GpIo_Driver.UnmapIoRegisrty(GpF);
10021028end;
10031029
10041030procedure TForm1.GPIO23switchChange(Sender: TObject);
10051031
10061032Begin
10071033 Timer1.Enabled := False;
10081034 if GPIO23switch.Checked then
10091035 begin
10101036 GpF.SetBit(Pout); //Turn LED on
10111037 end
10121038 else
10131039 begin
10141040 GpF.ClearBit(Pout); //Turn LED off
10151041 end;
10161042 Timer1.Enabled := True;
10171043end;
10181044
10191045procedure TForm1.SpeedButtonClick(Sender: TObject);
10201046var
10211047 i,p,k,v: longint;
10221048 ido:TDateTime;
10231049begin
10241050 ido:= Time;
10251051 k:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10261052 LogMemo.Lines.Add('Start: '+TimeToStr(ido));
10271053 p:=10000000 ;
10281054 For i:=1 to p do Begin
10291055 GpF.SetBit(P16);
10301056 GpF.ClearBit(P16);
10311057 end;
10321058 ido:= Time;
10331059 v:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10341060 LogMemo.Lines.Add('Stop: '+TimeToStr(ido)+' Frequency: '+
10351061 IntToStr(p div (v-k))+' kHz');
10361062end;
10371063
10381064procedure TForm1.Timer1Timer(Sender: TObject);
10391065begin
10401066 If PWM then Begin
10411067 If (d > 0) and (i+d < 1024) then begin
10421068 i:=i+d;
10431069 GpF.PwmWrite(Ppwm,i);
10441070 end ;
10451071 If (d < 0) and (i+d > -1) then begin
10461072 i:=i+d;
10471073 GpF.PwmWrite(Ppwm,i);
10481074 end;
10491075 end;
10501076end;
10511077
10521078
10531079end.
10541080```
10551081
10561082### PXL (Platform eXtended Library) for low level native access to GPIO, I²C, SPI, PWM, UART, V4L2, displays and sensors
10571083
10581084- Fácil y rápido acceso a GPIO, I²C, SPI, PWM, UART y timer de alta preción de la CPU.
10591085- V4L2 captura de video/imagen utilizando los conectores dedicados de la placa y cámaras USB. Por ejemplo cámaras serie como VC0706 y LSY201.
10601086- OpenGL ES hardware de renderizado con y sin servidor X. Software de renderizado.
10611087- Pantallas I²C y SPI tales como SSD1306, SSD1351, PCB8544 (Nokia), HX8357 y ILI9340.
10621088- LCD de caracteres con cableado de pines directo.
10631089- Suporte para software SPI y UART (bit-banging).
10641090- Suporte para SC16IS7x0 (controladora UART conectada a través de I²C o SPI), incluyendo pins GPIO extra.
10651091- Soporte para sensores tales como BMP180, DHT22, L3GD20, LSM303 y SHT10.
10661092- Otras características como networking, math, transformación de imágenes, efectos, dibujo de primitivas gráficas...
10671093
10681094*Más información y descargas de la [librería PXL](http://asphyre.net/products/pxl).*
10691095
10701096## Referencias
10711097
10721098- Eben Upton and Gareth Halfacree. Raspberry Pi User Guide. John Wiley and Sons, Chichester 2012, ISBN 111846446X
10731099- B. J. Rao (2013) The Raspberry Pi, Pi Vision and Lazarus/FPC. [Blaise Pascal Magazine](http://www.blaisepascal.eu). 29: 14-21.
10741100
10751101## External Links
10761102
10771103- [Raspberry Pi Foundation](http://www.raspberrypi.org)
10781104- [Raspberry Pi Spy: Raspberry Pi tutorials, scripts, help and downloads](http://www.raspberrypi-spy.co.uk)
10791105- [Lazarus wrapper unit for Gordon Henderson's wiringPi C library](http://www.lazarus.freepascal.org/index.php/topic,17404.0.html)
10801106- [Pin layout of the wiringPi library](https://projects.drogon.net/raspberry-pi/wiringpi/pins/)
10811107- [Additional information on Lazarus and Raspberry Pi at eLinux.org](http://www.elinux.org/Lazarus_on_RPi)
10821108- [Getting Started with Pascal on the Pi](http://www.pp4s.co.uk/main/gs-pi-intro.html)
10831109- [Lazberry Pi: Comprehensive information on Lazarus on the Raspberry Pi computer](http://superbitysoft.co.uk/lazberrypi/).
10841110- [Stefan Fischer's Lazarus unit rpi_hal](http://www.lazarus.freepascal.org/index.php/topic,20991.0.html).
10851111- [Improved Lazarus Unit for fast access to GPIO](http://www.meltonisl.com/software.html).
10861112- [PXL - Platform eXtended Library](http://asphyre.net/products/pxl).
10871113
10881114---
10891115*From the Free Pascal wiki, page "Lazarus on Raspberry Pi/es", as it stood on 2020-02-19 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