Sign in Join
Wiki copytemporary

Lazarus on Raspberry Pi/es: what changed

Revision 4 to 5. 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
2828![](/wiki-images/0/02/Install_Lazarus_Rasbian_Part1_en.png)
2929
3030Paso instalación 1
3131
3232![](/wiki-images/4/4a/Install_Lazarus_Rasbian_Part2_en.png)
3333
3434Paso instalación 2
3535
3636![](/wiki-images/5/53/Install_Lazarus_Rasbian_Part3_en.png)
3737
3838Paso instalación 3
3939
4040![](/wiki-images/2/24/Install_Lazarus_Rasbian_Part4_en.png)
4141
4242Paso instalación 4
4343
4444Si 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).
4545
4646#### Raspberry Pi 2
4747
4848Desde 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/).
4949
5050![](/wiki-images/c/cc/Lazarus_0_9_30_4_on_RPi_2.png)
5151
5252Lazarus "out of the box" en Raspberry Pi 2
5353
5454160
5555
5656#### Raspberry Pi 3
5757
5858Ver Raspberry Pi 2.
5959
6060![](/wiki-images/5/50/RaspBerryPi3B%2B.png)
6161
6262![](/wiki-images/1/12/RaspBerryPi3B%2B_img1.png)
6363
6464![](/wiki-images/5/56/RaspBerryPi3B%2B_img2.png)
6565
6666Como se puede observar tiene más pines de los cuales se debe consultar la funcionalidad de cada uno antes de conectar algo.
6767
6868![](/wiki-images/f/f3/RaspBerryPi3B%2B_img3.png)
6969
7070### Compilación cruzada (cross compiling) para Raspberry Pi desde Windows
7171
72721\. Utilizando fpcup
7373
7474Un camino es utilizar fpcup para configurar un compilador cruzado; seguir estas instrucciones:
7575
7676[[fpcup|fpcup#Linux_ARM_cross_compiler]]
7777
78782\. Utilizando scripts
7979
8080Alternativamente, para una aproximación más manual, y utilizando ficheros de proceso por lotes, puedes seguir los siguientes pasos.
8181
82822.1 Prerequisitos
8383
84-`FPC 2.7.1 or higher installed with sourcecode`\
85-`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)
84+```text
85+FPC 2.7.1 or higher installed with sourcecode
86+Install the Windows version from the Linaro binutils for linux gnueabihf into %FPCPATH%/bin/win32-armhf-linux [https://launchpad.net/linaro-toolchain-binaries/trunk/2013.10/+download/gcc-linaro-arm-linux-gnueabihf-4.8-2013.10_win32.zip]
87+```
8688
87892.2 Script ejemplo para construir (adaptar los trayectos a como se necesiten)
8890
8991``` bat
9092set PATH=C:\pp\bin\i386-win32;%PATH%;
9193set FPCMAKEPATH=C:/pp
9294set FPCPATH=C:/pp
9395set OUTPATH=C:/pp271
9496%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
9597
9698%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
9799if errorlevel 1 goto quit
98100%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%
99101
100102:quit
101103pause
102104```
103105
104106Con 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.
105107
106108### Compilando desde el código fuente
107109
108110Puede 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..
109111
110112![](/wiki-images/8/8d/Start_Menu_with_Lazarus_en.png)
111113
112114Como arrancar Lazarus en Raspbian Wheezy
113115
114116![](/wiki-images/8/87/Lazarus_on_Raspberry_Pi.jpg)
115117
116118Lazarus bajo Raspberry Pi
117119
118120![](/wiki-images/c/c7/Rpi_gpio_pins.png)
119121
120122Numeración de los pines GPIO
121123
122124Compilando desde las fuentes en Raspberry con Gentoo (y otra distro)
123125
124126------------------------------------------------------------------------
125127
126128Si necesitas instalar la última release estable de fpc y, adicional y aisladamente, el compilador fpc del trunk entonces puedes leer la siguiente guía.
127129
128130Esto se escribió utilizando Gentoo, pero esta guía debería ser de utilidad para cualquier otra distro: [[Install fpc on Raspberry with Gentoo]]
129131
130132## Accediendo a hardware externo
131133
132134![](/wiki-images/f/f2/Rpi_pinout_all_50.png)
133135
134136Una 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):
135137
1361381. [[Lazarus on Raspberry Pi|Direct access]] Utilizando la unidad [[BaseUnix]].
1371392. Acceso a través de [[Lazarus on Raspberry Pi|encapsulated shell calls]]
1381403. Acceso a través de [[Lazarus on Raspberry Pi|wiringPi library]].
1391414. Acceso a través de la unidad [[Lazarus on Raspberry Pi|rpi_hal]].
1401425. Acceso a través de la unidad [[Lazarus on Raspberry Pi|PiGpio]].
1411436. Acceso a través de la librería [PascalIO](https://github.com/SAmeis/pascalio).
1421447. Acceso a través de la librería [PXL](http://asphyre.net/products/pxl).
143145
144146### Acceso nativo al hardware
145147
146148![ 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.
147149
148150#### Conmutando un dispositivo a través de un puerto GPIO
149151
150152El 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*.
151153
152154Para 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.
153155
154156El 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:
155157
156158``` bash
157159sudo adduser pi gpio
158160sudo adduser pi i2c
159161sudo adduser pi spi
160162```
161163
162164*Unidad de control:*
163165
164166``` pascal
165167unit Unit1;
166168
167169{Demo application for GPIO on Raspberry Pi}
168170{Inspired by the Python input/output demo application by Gareth Halfacree}
169171{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
170172
171173{$mode objfpc}{$H+}
172174
173175interface
174176
175177uses
176178 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
177179 Unix, BaseUnix;
178180
179181type
180182
181183 { TForm1 }
182184
183185 TForm1 = class(TForm)
184186 LogMemo: TMemo;
185187 GPIO17ToggleBox: TToggleBox;
186188 procedure FormActivate(Sender: TObject);
187189 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
188190 procedure GPIO17ToggleBoxChange(Sender: TObject);
189191 private
190192 { private declarations }
191193 public
192194 { public declarations }
193195 end;
194196
195197const
196198 PIN_17: PChar = '17';
197199 PIN_ON: PChar = '1';
198200 PIN_OFF: PChar = '0';
199201 OUT_DIRECTION: PChar = 'out';
200202
201203var
202204 Form1: TForm1;
203205 gReturnCode: longint; {stores the result of the IO operation}
204206
205207implementation
206208
207209{$R *.lfm}
208210
209211{ TForm1 }
210212
211213procedure TForm1.FormActivate(Sender: TObject);
212214var
213215 fileDesc: integer;
214216begin
215217 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
216218 try
217219 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
218220 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
219221 LogMemo.Lines.Add(IntToStr(gReturnCode));
220222 finally
221223 gReturnCode := fpclose(fileDesc);
222224 LogMemo.Lines.Add(IntToStr(gReturnCode));
223225 end;
224226 { Set SoC pin 17 as output: }
225227 try
226228 fileDesc := fpopen('/sys/class/gpio/gpio17/direction', O_WrOnly);
227229 gReturnCode := fpwrite(fileDesc, OUT_DIRECTION[0], 3);
228230 LogMemo.Lines.Add(IntToStr(gReturnCode));
229231 finally
230232 gReturnCode := fpclose(fileDesc);
231233 LogMemo.Lines.Add(IntToStr(gReturnCode));
232234 end;
233235end;
234236
235237procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
236238var
237239 fileDesc: integer;
238240begin
239241 { Free SoC pin 17: }
240242 try
241243 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
242244 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
243245 LogMemo.Lines.Add(IntToStr(gReturnCode));
244246 finally
245247 gReturnCode := fpclose(fileDesc);
246248 LogMemo.Lines.Add(IntToStr(gReturnCode));
247249 end;
248250end;
249251
250252procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
251253var
252254 fileDesc: integer;
253255begin
254256 if GPIO17ToggleBox.Checked then
255257 begin
256258 { Swith SoC pin 17 on: }
257259 try
258260 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
259261 gReturnCode := fpwrite(fileDesc, PIN_ON[0], 1);
260262 LogMemo.Lines.Add(IntToStr(gReturnCode));
261263 finally
262264 gReturnCode := fpclose(fileDesc);
263265 LogMemo.Lines.Add(IntToStr(gReturnCode));
264266 end;
265267 end
266268 else
267269 begin
268270 { Switch SoC pin 17 off: }
269271 try
270272 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
271273 gReturnCode := fpwrite(fileDesc, PIN_OFF[0], 1);
272274 LogMemo.Lines.Add(IntToStr(gReturnCode));
273275 finally
274276 gReturnCode := fpclose(fileDesc);
275277 LogMemo.Lines.Add(IntToStr(gReturnCode));
276278 end;
277279 end;
278280end;
279281
280282end.
281283```
282284
283285*Programa principal:*
284286
285287``` pascal
286288program io_test;
287289
288290{$mode objfpc}{$H+}
289291
290292uses
291293 {$IFDEF UNIX}{$IFDEF UseCThreads}
292294 cthreads,
293295 {$ENDIF}{$ENDIF}
294296 Interfaces, // this includes the LCL widgetset
295297 Forms, Unit1
296298 { puedes añadir unidades después de esto };
297299
298300{$R *.res}
299301
300302begin
301303 Application.Initialize;
302304 Application.CreateForm(TForm1, Form1);
303305 Application.Run;
304306end.
305307```
306308
307309#### Leyendo el estado de un pin
308310
309311![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)
310312
311313Por supuesto también es posible leer el estado de un pulsador conectado a un puerto GPIO (General Porpouse Inpunt Output).
312314
313315El 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.
314316
315317Para 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.
316318
317319Ten 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.
318320
319321Este programa tiene que ser ejecutado también como usuario root.
320322
321323*Unidad de control:*
322324
323325``` pascal
324326unit Unit1;
325327
326328{Demo application for GPIO on Raspberry Pi}
327329{Inspired by the Python input/output demo application by Gareth Halfacree}
328330{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
329331
330332{This application reads the status of a push-button}
331333
332334{$mode objfpc}{$H+}
333335
334336interface
335337
336338uses
337339 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
338340 ButtonPanel, Unix, BaseUnix;
339341
340342type
341343
342344 { TForm1 }
343345
344346 TForm1 = class(TForm)
345347 ApplicationProperties1: TApplicationProperties;
346348 GPIO18CheckBox: TCheckBox;
347349 LogMemo: TMemo;
348350 procedure ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
349351 procedure FormActivate(Sender: TObject);
350352 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
351353 private
352354 { private declarations }
353355 public
354356 { public declarations }
355357 end;
356358
357359const
358360 PIN_18: PChar = '18';
359361 IN_DIRECTION: PChar = 'in';
360362
361363var
362364 Form1: TForm1;
363365 gReturnCode: longint; {stores the result of the IO operation}
364366
365367implementation
366368
367369{$R *.lfm}
368370
369371{ TForm1 }
370372
371373procedure TForm1.FormActivate(Sender: TObject);
372374var
373375 fileDesc: integer;
374376begin
375377 { Prepare SoC pin 18 (pin 12 on GPIO port) for access: }
376378 try
377379 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
378380 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
379381 LogMemo.Lines.Add(IntToStr(gReturnCode));
380382 finally
381383 gReturnCode := fpclose(fileDesc);
382384 LogMemo.Lines.Add(IntToStr(gReturnCode));
383385 end;
384386 { Set SoC pin 18 as input: }
385387 try
386388 fileDesc := fpopen('/sys/class/gpio/gpio18/direction', O_WrOnly);
387389 gReturnCode := fpwrite(fileDesc, IN_DIRECTION[0], 2);
388390 LogMemo.Lines.Add(IntToStr(gReturnCode));
389391 finally
390392 gReturnCode := fpclose(fileDesc);
391393 LogMemo.Lines.Add(IntToStr(gReturnCode));
392394 end;
393395end;
394396
395397procedure TForm1.ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
396398var
397399 fileDesc: integer;
398400 buttonStatus: string[1] = '1';
399401begin
400402 try
401403 { Open SoC pin 18 (pin 12 on GPIO port) in read-only mode: }
402404 fileDesc := fpopen('/sys/class/gpio/gpio18/value', O_RdOnly);
403405 if fileDesc > 0 then
404406 begin
405407 { Read status of this pin (0: button pressed, 1: button released): }
406408 gReturnCode := fpread(fileDesc, buttonStatus[1], 1);
407409 LogMemo.Lines.Add(IntToStr(gReturnCode) + ': ' + buttonStatus);
408410 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
409411 if buttonStatus = '0' then
410412 GPIO18CheckBox.Checked := true
411413 else
412414 GPIO18CheckBox.Checked := false;
413415 end;
414416 finally
415417 { Close SoC pin 18 (pin 12 on GPIO port) }
416418 gReturnCode := fpclose(fileDesc);
417419 LogMemo.Lines.Add(IntToStr(gReturnCode));
418420 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
419421 end;
420422end;
421423
422424procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
423425var
424426 fileDesc: integer;
425427begin
426428 { Free SoC pin 18: }
427429 try
428430 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
429431 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
430432 LogMemo.Lines.Add(IntToStr(gReturnCode));
431433 finally
432434 gReturnCode := fpclose(fileDesc);
433435 LogMemo.Lines.Add(IntToStr(gReturnCode));
434436 end;
435437end;
436438
437439end.
438440```
439441
440442El programa main es idéntico al del ejemplo de arriba.
441443
442444### Acceso hardware mediante llamadas encapsuladas del shell
443445
444446Otro 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.
445447
446448*Controlling unit:*
447449
448450``` pascal
449451unit Unit1;
450452
451453{Demo application for GPIO on Raspberry Pi}
452454{Inspired by the Python input/output demo application by Gareth Halfacree}
453455{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
454456
455457{$mode objfpc}{$H+}
456458
457459interface
458460
459461uses
460462 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Unix;
461463
462464type
463465
464466 { TForm1 }
465467
466468 TForm1 = class(TForm)
467469 LogMemo: TMemo;
468470 GPIO17ToggleBox: TToggleBox;
469471 procedure FormActivate(Sender: TObject);
470472 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
471473 procedure GPIO17ToggleBoxChange(Sender: TObject);
472474 private
473475 { private declarations }
474476 public
475477 { public declarations }
476478 end;
477479
478480var
479481 Form1: TForm1;
480482 gReturnCode: longint; {stores the result of the IO operation}
481483
482484implementation
483485
484486{$R *.lfm}
485487
486488{ TForm1 }
487489
488490procedure TForm1.FormActivate(Sender: TObject);
489491begin
490492 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
491493 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/export');
492494 LogMemo.Lines.Add(IntToStr(gReturnCode));
493495 { Set SoC pin 17 as output: }
494496 gReturnCode := fpsystem('echo "out" > /sys/class/gpio/gpio17/direction');
495497 LogMemo.Lines.Add(IntToStr(gReturnCode));
496498end;
497499
498500procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
499501begin
500502 { Free SoC pin 17: }
501503 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/unexport');
502504 LogMemo.Lines.Add(IntToStr(gReturnCode));
503505end;
504506
505507procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
506508begin
507509 if GPIO17ToggleBox.Checked then
508510 begin
509511 { Swith SoC pin 17 on: }
510512 gReturnCode := fpsystem('echo "1" > /sys/class/gpio/gpio17/value');
511513 LogMemo.Lines.Add(IntToStr(gReturnCode));
512514 end
513515 else
514516 begin
515517 { Switch SoC pin 17 off: }
516518 gReturnCode := fpsystem('echo "0" > /sys/class/gpio/gpio17/value');
517519 LogMemo.Lines.Add(IntToStr(gReturnCode));
518520 end;
519521end;
520522
521523end.
522524```
523525
524526El programa main es idéntico al del ejemplo de arriba. Este programa necesita ejecutarse con privilegios de root también.
525527
526528### Procedimientos y funciones de wiringPi
527529
528530Alex Schaller's wrapper unit for Gordon Henderson's Arduino compatible wiringPi library provides a numbering scheme that resembles that of Arduino boards.
529531
530532**Function wiringPiSetup:longint:** Initializes wiringPi system using the wiringPi pin numbering scheme.
531533
532534**Procedure wiringPiGpioMode(mode:longint):** Initializes wiringPi system with the Broadcom GPIO pin numbering scheme.
533535
534536**Procedure pullUpDnControl(pin:longint;** pud:longint): controls the internal pull-up/down resistors on a GPIO pin.
535537
536538**Procedure pinMode(pin:longint; mode:longint):** sets the mode of a pin to either INPUT, OUTPUT, or PWM_OUTPUT.
537539
538540**Procedure digitalWrite(pin:longint; value:longint):** sets an output bit.
539541
540542**Procedure pwmWrite(pin:longint; value:longint):** sets an output PWM value between 0 and 1024.
541543
542544**Function digitalRead(pin:longint):longint:** reads the value of a given Pin, returning 1 or 0.
543545
544546**Procedure delay(howLong:dword):** waits for at least howLong milliseconds.
545547
546548**Procedure delayMicroseconds(howLong:dword):** waits for at least howLong microseconds.
547549
548550**Function millis:dword:** returns the number of milliseconds since the program called one of the wiringPiSetup functions.
549551
550552### rpi_hal-Hardware Abstraction Library (funciones y procedimientos GPIO, I2C y SPI de la librería de abstracción hardware de la RaspBerry Pi)
551553
552554Esta 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:
553555
554556Justamente un extracto de los procedimientos y funciones disponibles:
555557
556558**procedure gpio_set_pin (pin:longword;highlevel:boolean);** { Establece RPi GPIO pin a nivel alto o bajo; Velocidad @ 700MHz -\> 0.65MHz }
557559
558560**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 }
559561
560562**procedure gpio_set_input (pin:longword);** { Establece RPi GPIO pin en modo entrada }
561563
562564**procedure gpio_set_output(pin:longword);** { Establece RPi GPIO pin en modo salida}
563565
564566**procedure gpio_set_alt (pin,altfunc:longword);** { Establece RPi GPIO pin to alternate function nr. 0..5 }
565567
566568**procedure gpio_set_gppud (mask:longword);** { Establece RPi GPIO Pull-up/down Register (GPPUD) with mask }
567569
568570...
569571
570572**function rpi_snr :string;** { Emtrega el SNR: 0000000012345678 }
571573
572574**function rpi_hw :string;** { Entrega el tipo de procesador: BCM2708 }
573575
574576**function rpi_proc:string;** { ARMv6-compatible processor rev 7 (v6l) }
575577
576578...
577579
578580**function i2c_bus_write(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
579581
580582**function i2c_bus_read (baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
581583
582584**function i2c_string_read(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : string;**
583585
584586**function i2c_string_write(baseadr,reg:word; s:string; testnr:integer) : integer;**
585587
586588...
587589
588590**procedure SPI_Write(devnum:byte; reg,data:word);**
589591
590592**function SPI_Read(devnum:byte; reg:word) : byte;**
591593
592594**procedure SPI_BurstRead2Buffer (devnum,start_reg:byte; xferlen:longword);**
593595
594596**procedure SPI_BurstWriteBuffer (devnum,start_reg:byte; xferlen:longword);** { Write 'len' Bytes from Buffer SPI Dev startig at address 'reg' }
595597
596598...
597599
598600*Test Program (testrpi.pas):*
599601
600602``` pascal
601603//Progama simple de chequeo, el cual utiliza rpi_hal;
602604
603605 program testrpi;
604606 uses rpi_hal;
605607 begin
606608 writeln('Show CPU-Info, RPI-HW-Info and Registers:');
607609 rpi_show_all_info;
608610 writeln('Let Status LED Blink. Using GPIO functions:');
609611 GPIO_PIN_TOGGLE_TEST;
610612 writeln('Test SPI Read function. (piggy back board with installed RFM22B Module is required!)');
611613 Test_SPI;
612614 end.
613615```
614616
615617### Unidad nativa PiGpio de bajo nivel escrita en pascal (control GPIO en lugar de la librería c de wiringPi)
616618
617-*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) :*
619+*Esta unit (pigpio.pas[1](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) :*
618620
619621``` pascal
620622
621623unit PiGpio;
622624{
623625 BCM2835 GPIO Registry Driver, also can use to manipulate cpu other registry areas
624626
625627 This code is tested only Broadcom bcm2835 cpu, different arm cpus may need different
626628 gpio driver implementation
627629
628630 2013 Gabor Szollosi
629631}
630632{$mode objfpc}{$H+}
631633
632634interface
633635
634636uses
635637 Classes, SysUtils;
636638
637639const
638640 REG_GPIO = $3F000;// bcm2835 gpio register 0x2000 0000 (RPi1), 0x3F00 0000 (RPi2)
639641 // new fpMap uses page offset, one page is 4096 bytes = 0x1000 so simply calculate 0x2000 0000 / 0x1000 = 0x2000 0
640642 PAGE_SIZE = 4096;
641643 BLOCK_SIZE = 4096;
642644 // The BCM2835 has 54 GPIO pins.
643645 // BCM2835 data sheet, Page 90 onwards.
644646 // There are 6 control registers, each control the functions of a block
645647 // of 10 pins.
646648
647649 CLOCK_BASE = (REG_GPIO + $101);
648650 GPIO_BASE = (REG_GPIO + $200);
649651 GPIO_PWM = (REG_GPIO + $20C);
650652
651653 INPUT = 0;
652654 OUTPUT = 1;
653655 PWM_OUTPUT = 2;
654656 LOW = False;
655657 HIGH = True;
656658 PUD_OFF = 0;
657659 PUD_DOWN = 1;
658660 PUD_UP = 2;
659661
660662 // PWM
661663
662664 PWM_CONTROL = 0;
663665 PWM_STATUS = 4;
664666 PWM0_RANGE = 16;
665667 PWM0_DATA = 20;
666668 PWM1_RANGE = 32;
667669 PWM1_DATA = 36;
668670
669671 PWMCLK_CNTL = 160;
670672 PWMCLK_DIV = 164;
671673
672674 PWM1_MS_MODE = $8000; // Run in MS mode
673675 PWM1_USEFIFO = $2000; // Data from FIFO
674676 PWM1_REVPOLAR = $1000; // Reverse polarity
675677 PWM1_OFFSTATE = $0800; // Ouput Off state
676678 PWM1_REPEATFF = $0400; // Repeat last value if FIFO empty
677679 PWM1_SERIAL = $0200; // Run in serial mode
678680 PWM1_ENABLE = $0100; // Channel Enable
679681
680682 PWM0_MS_MODE = $0080; // Run in MS mode
681683 PWM0_USEFIFO = $0020; // Data from FIFO
682684 PWM0_REVPOLAR = $0010; // Reverse polarity
683685 PWM0_OFFSTATE = $0008; // Ouput Off state
684686 PWM0_REPEATFF = $0004; // Repeat last value if FIFO empty
685687 PWM0_SERIAL = $0002; // Run in serial mode
686688 PWM0_ENABLE = $0001; // Channel Enable
687689
688690type
689691
690692 { TIoPort }
691693
692694 TIoPort = class // IO bank object
693695 private //
694696
695697 //function get_pinDirection(aPin: TGpIoPin): TGpioPinConf;
696698
697699 public
698700 FGpio: ^LongWord;
699701 FClk: ^LongWord;
700702 FPwm: ^LongWord;
701703 procedure SetPinMode(gpin, mode: byte);
702704 function GetBit(gpin : byte):boolean;inline; // gets pin bit}
703705 procedure ClearBit(gpin : byte);inline;// write pin to 0
704706 procedure SetBit(gpin : byte);inline;// write pin to 1
705707 procedure SetPullMode(gpin, mode: byte);
706708 procedure PwmWrite(gpin : byte; value : LongWord);inline;// write pin to pwm value
707709 end;
708710
709711 { TIoDriver }
710712
711713 TIoDriver = class
712714 private
713715
714716 public
715717 destructor Destroy;override;
716718 function MapIo:boolean;// creates io memory mapping
717719 procedure UnmapIoRegisrty(FMap: TIoPort);// close io memory mapping
718720 function CreatePort(PortGpio, PortClk, PortPwm: LongWord):TIoPort; // create new IO port
719721 end;
720722
721723var
722724
723725 fd: integer;// /dev/mem file handle
724726procedure delayNanoseconds (howLong : LongWord);
725727
726728implementation
727729
728730uses
729731 baseUnix, Unix;
730732
731733procedure delayNanoseconds (howLong : LongWord);
732734var
733735 sleeper, dummy : timespec;
734736begin
735737 sleeper.tv_sec := 0 ;
736738 sleeper.tv_nsec := howLong ;
737739 fpnanosleep (@sleeper,@dummy) ;
738740end;
739741{ TIoDriver }
740742//*******************************************************************************
741743destructor TIoDriver.Destroy;
742744begin
743745 inherited Destroy;
744746end;
745747//*******************************************************************************
746748function TIoDriver.MapIo: boolean;
747749begin
748750 Result := True;
749751 fd := fpopen('/dev/mem', O_RdWr or O_Sync); // Open the master /dev/memory device
750752 if fd < 0 then
751753 begin
752754 Result := False; // unsuccessful memory mapping
753755 end;
754756 //
755757end;
756758//*******************************************************************************
757759procedure TIoDriver.UnmapIoRegisrty(FMap:TIoPort);
758760begin
759761 if FMap.FGpio <> nil then
760762 begin
761763 fpMUnmap(FMap.FGpio,PAGE_SIZE);
762764 FMap.FGpio := Nil;
763765 end;
764766 if FMap.FClk <> nil then
765767 begin
766768 fpMUnmap(FMap.FClk,PAGE_SIZE);
767769 FMap.FClk := Nil;
768770 end;
769771 if FMap.FPwm <> nil then
770772 begin
771773 fpMUnmap(FMap.FPwm ,PAGE_SIZE);
772774 FMap.FPwm := Nil;
773775 end;
774776end;
775777//*******************************************************************************
776778function TIoDriver.CreatePort(PortGpio, PortClk, PortPwm: LongWord): TIoPort;
777779begin
778780 Result := TIoPort.Create;// new io port, pascal calls new fpMap, where offst is page sized 4096 bytes!!!
779781 Result.FGpio := FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortGpio); // port config gpio memory
780782 Result.FClk:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortClk);; // port clk
781783 Result.FPwm:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortPwm);; // port pwm
782784end;
783785//*******************************************************************************
784786procedure TIoPort.SetPinMode(gpin, mode: byte);
785787var
786788 fSel, shift, alt : byte;
787789 gpiof, clkf, pwmf : ^LongWord;
788790begin
789791 fSel := (gpin div 10)*4 ; //Select Gpfsel 0 to 5 register
790792 shift := (gpin mod 10)*3 ; //0-9 pin shift
791793 gpiof := Pointer(LongWord(Self.FGpio)+fSel);
792794 if (mode = INPUT) then
793795 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) //7 shl shift komplemens - Sets bits to zero = input
794796 else if (mode = OUTPUT) then
795797 begin
796798 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (1 shl shift);
797799 end
798800 else if (mode = PWM_OUTPUT) then
799801 begin
800802 Case gpin of
801803 12,13,40,41,45 : alt:= 4 ;
802804 18,19 : alt:= 2 ;
803805 else alt:= 0 ;
804806 end;
805807 If alt > 0 then
806808 begin
807809 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (alt shl shift);
808810 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
809811 clkf^ := $5A000011 or (1 shl 5) ; //stop clock
810812 delayNanoseconds(200);
811813 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_DIV);
812814 clkf^ := $5A000000 or (32 shl 12) ; // set pwm clock div to 32 (19.2/3 = 600KHz)
813815 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
814816 clkf^ := $5A000011 ; //start clock
815817 Self.ClearBit(gpin);
816818 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
817819 pwmf^ := 0 ; // Disable PWM
818820 delayNanoseconds(200);
819821 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_RANGE);
820822 pwmf^ := $400 ; //max: 1023
821823 delayNanoseconds(200);
822824 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_RANGE);
823825 pwmf^ := $400 ; //max: 1023
824826 delayNanoseconds(200);
825827 // Enable PWMs
826828 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_DATA);
827829 pwmf^ := 0 ; //start value
828830 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_DATA);
829831 pwmf^ := 0 ; //start value
830832 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
831833 pwmf^ := PWM0_ENABLE or PWM1_ENABLE ;
832834 end;
833835 end;
834836end;
835837//*******************************************************************************
836838procedure TIoPort.SetBit(gpin : byte);
837839var
838840 gpiof : ^LongWord;
839841begin
840842 gpiof := Pointer(LongWord(Self.FGpio) + 28 + (gpin shr 5) shl 2);
841843 gpiof^ := 1 shl gpin;
842844end;
843845//*******************************************************************************
844846procedure TIoPort.ClearBit(gpin : byte);
845847var
846848 gpiof : ^LongWord;
847849begin
848850 gpiof := Pointer(LongWord(Self.FGpio) + 40 + (gpin shr 5) shl 2);
849851 gpiof^ := 1 shl gpin;
850852end;
851853//*******************************************************************************
852854function TIoPort.GetBit(gpin : byte):boolean;
853855var
854856 gpiof : ^LongWord;
855857begin
856858 gpiof := Pointer(LongWord(Self.FGpio) + 52 + (gpin shr 5) shl 2);
857859 if (gpiof^ and (1 shl gpin)) = 0 then Result := False else Result := True;
858860end;
859861//*******************************************************************************
860862procedure TIoPort.SetPullMode(gpin, mode: byte);
861863var
862864 pudf, pudclkf : ^LongWord;
863865begin
864866 pudf := Pointer(LongWord(Self.FGpio) + 148 );
865867 pudf^ := mode; //mode = 0, 1, 2 :Off, Down, Up
866868 delayNanoseconds(200);
867869 pudclkf := Pointer(LongWord(Self.FGpio) + 152 + (gpin shr 5) shl 2);
868870 pudclkf^ := 1 shl gpin ;
869871 delayNanoseconds(200);
870872 pudf^ := 0 ;
871873 pudclkf^ := 0 ;
872874end;
873875//*******************************************************************************
874876procedure TIoPort.PwmWrite(gpin : byte; value : Longword);
875877var
876878 pwmf : ^LongWord;
877879 port : byte;
878880begin
879881 Case gpin of
880882 12,18,40 : port:= PWM0_DATA ;
881883 13,19,41,45 : port:= PWM1_DATA ;
882884 else exit;
883885 end;
884886 pwmf := Pointer(LongWord(Self.FPwm) + port);
885887 pwmf^ := value and $FFFFFBFF; // $400 complemens
886888end;
887889//*******************************************************************************
888890end.
889891```
890892
891-*Controlling Lazarus unit:(Project files[3](https://drive.google.com/folderview?id=0B-b-5ooIWPvGU043ZTZ0cUc2YkE&usp=sharing))*
893+*Controlling Lazarus unit:(Project files[2](https://drive.google.com/folderview?id=0B-b-5ooIWPvGU043ZTZ0cUc2YkE&usp=sharing))*
892894
893895``` pascal
894896unit Unit1;
895897
896898{Demo application for GPIO on Raspberry Pi}
897899{Inspired by the Python input/output demo application by Gareth Halfacree}
898900{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
899901
900902{$mode objfpc}{$H+}
901903
902904interface
903905
904906uses
905907 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
906908 ExtCtrls, Unix, PiGpio;
907909
908910type
909911
910912 { TForm1 }
911913
912914 TForm1 = class(TForm)
913915 GPIO25In: TButton;
914916 SpeedButton: TButton;
915917 LogMemo: TMemo;
916918 GPIO23switch: TToggleBox;
917919 Timer1: TTimer;
918920 GPIO18Pwm: TToggleBox;
919921 Direction: TToggleBox;
920922 procedure DirectionChange(Sender: TObject);
921923 procedure GPIO18PwmChange(Sender: TObject);
922924 procedure GPIO25InClick(Sender: TObject);
923925 procedure FormActivate(Sender: TObject);
924926 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
925927 procedure GPIO23switchChange(Sender: TObject);
926928 procedure SpeedButtonClick(Sender: TObject);
927929 procedure Timer1Timer(Sender: TObject);
928930 private
929931 { private declarations }
930932 public
931933 { public declarations }
932934 end;
933935
934936const
935937 INPUT = 0;
936938 OUTPUT = 1;
937939 PWM_OUTPUT = 2;
938940 LOW = False;
939941 HIGH = True;
940942 PUD_OFF = 0;
941943 PUD_DOWN = 1;
942944 PUD_UP = 2;
943945 // Convert Raspberry Pi P1 pins (Px) to GPIO port
944946 P3 = 0;
945947 P5 = 1;
946948 P7 = 4;
947949 P8 = 14;
948950 P10 = 15;
949951 P11 = 17;
950952 P12 = 18;
951953 P13 = 21;
952954 P15 = 22;
953955 P16 = 23;
954956 P18 = 24;
955957 P19 = 10;
956958 P21 = 9;
957959 P22 = 25;
958960 P23 = 11;
959961 P24 = 8;
960962 P26 = 7;
961963
962964var
963965 Form1: TForm1;
964966 GPIO_Driver: TIoDriver;
965967 GpF: TIoPort;
966968 PWM :Boolean;
967969 i, d : integer;
968970 Pin,Pout,Ppwm : byte;
969971
970972implementation
971973
972974{$R *.lfm}
973975
974976{ TForm1 }
975977
976978procedure TForm1.FormActivate(Sender: TObject);
977979begin
978980 if not GPIO_Driver.MapIo then
979981 begin
980982 LogMemo.Lines.Add('Error mapping gpio registry');
981983 end
982984 else
983985 begin
984986 GpF := GpIo_Driver.CreatePort(GPIO_BASE, CLOCK_BASE, GPIO_PWM);
985987 end ;
986988 Timer1.Enabled:= True;
987989 Timer1.Interval:= 25; //25 ms controll interval
988990 Pin := P22;
989991 Pout := P16;
990992 Ppwm := P12;
991993 i:=1;
992994 GpF.SetPinMode(Pout,OUTPUT);
993995 GpF.SetPinMode(Pin,INPUT);
994996 GpF.SetPullMode(Pin,PUD_Up); // Input PullUp High level
995997end;
996998
997999procedure TForm1.GPIO25InClick(Sender: TObject);
9981000begin
9991001 If GpF.GetBit(Pin) then LogMemo.Lines.Add('In: '+IntToStr(1))
10001002 else LogMemo.Lines.Add('In: '+IntToStr(0));
10011003end;
10021004
10031005procedure TForm1.GPIO18PwmChange(Sender: TObject);
10041006begin
10051007 if GPIO18Pwm.Checked then
10061008 begin
10071009 GpF.SetPinMode(Ppwm,PWM_OUTPUT);
10081010 PWM := True; //PWM on
10091011 end
10101012 else
10111013 begin
10121014 GpF.SetPinMode(Ppwm,INPUT);
10131015 PWM := False; //PWM off
10141016 end;
10151017end;
10161018
10171019procedure TForm1.DirectionChange(Sender: TObject);
10181020begin
10191021 if Direction.Checked then d:=10 else d:=-10;
10201022end;
10211023
10221024
10231025procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
10241026begin
10251027 GpF.SetPinMode(Ppwm,INPUT);
10261028 GpF.ClearBit(Pout);
10271029 GpIo_Driver.UnmapIoRegisrty(GpF);
10281030end;
10291031
10301032procedure TForm1.GPIO23switchChange(Sender: TObject);
10311033
10321034Begin
10331035 Timer1.Enabled := False;
10341036 if GPIO23switch.Checked then
10351037 begin
10361038 GpF.SetBit(Pout); //Turn LED on
10371039 end
10381040 else
10391041 begin
10401042 GpF.ClearBit(Pout); //Turn LED off
10411043 end;
10421044 Timer1.Enabled := True;
10431045end;
10441046
10451047procedure TForm1.SpeedButtonClick(Sender: TObject);
10461048var
10471049 i,p,k,v: longint;
10481050 ido:TDateTime;
10491051begin
10501052 ido:= Time;
10511053 k:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10521054 LogMemo.Lines.Add('Start: '+TimeToStr(ido));
10531055 p:=10000000 ;
10541056 For i:=1 to p do Begin
10551057 GpF.SetBit(P16);
10561058 GpF.ClearBit(P16);
10571059 end;
10581060 ido:= Time;
10591061 v:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10601062 LogMemo.Lines.Add('Stop: '+TimeToStr(ido)+' Frequency: '+
10611063 IntToStr(p div (v-k))+' kHz');
10621064end;
10631065
10641066procedure TForm1.Timer1Timer(Sender: TObject);
10651067begin
10661068 If PWM then Begin
10671069 If (d > 0) and (i+d < 1024) then begin
10681070 i:=i+d;
10691071 GpF.PwmWrite(Ppwm,i);
10701072 end ;
10711073 If (d < 0) and (i+d > -1) then begin
10721074 i:=i+d;
10731075 GpF.PwmWrite(Ppwm,i);
10741076 end;
10751077 end;
10761078end;
10771079
10781080
10791081end.
10801082```
10811083
10821084### PXL (Platform eXtended Library) for low level native access to GPIO, I²C, SPI, PWM, UART, V4L2, displays and sensors
10831085
10841086- Fácil y rápido acceso a GPIO, I²C, SPI, PWM, UART y timer de alta preción de la CPU.
10851087- 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.
10861088- OpenGL ES hardware de renderizado con y sin servidor X. Software de renderizado.
10871089- Pantallas I²C y SPI tales como SSD1306, SSD1351, PCB8544 (Nokia), HX8357 y ILI9340.
10881090- LCD de caracteres con cableado de pines directo.
10891091- Suporte para software SPI y UART (bit-banging).
10901092- Suporte para SC16IS7x0 (controladora UART conectada a través de I²C o SPI), incluyendo pins GPIO extra.
10911093- Soporte para sensores tales como BMP180, DHT22, L3GD20, LSM303 y SHT10.
10921094- Otras características como networking, math, transformación de imágenes, efectos, dibujo de primitivas gráficas...
10931095
10941096*Más información y descargas de la [librería PXL](http://asphyre.net/products/pxl).*
10951097
10961098## Referencias
10971099
10981100- Eben Upton and Gareth Halfacree. Raspberry Pi User Guide. John Wiley and Sons, Chichester 2012, ISBN 111846446X
10991101- B. J. Rao (2013) The Raspberry Pi, Pi Vision and Lazarus/FPC. [Blaise Pascal Magazine](http://www.blaisepascal.eu). 29: 14-21.
11001102
11011103## External Links
11021104
11031105- [Raspberry Pi Foundation](http://www.raspberrypi.org)
11041106- [Raspberry Pi Spy: Raspberry Pi tutorials, scripts, help and downloads](http://www.raspberrypi-spy.co.uk)
11051107- [Lazarus wrapper unit for Gordon Henderson's wiringPi C library](http://www.lazarus.freepascal.org/index.php/topic,17404.0.html)
11061108- [Pin layout of the wiringPi library](https://projects.drogon.net/raspberry-pi/wiringpi/pins/)
11071109- [Additional information on Lazarus and Raspberry Pi at eLinux.org](http://www.elinux.org/Lazarus_on_RPi)
11081110- [Getting Started with Pascal on the Pi](http://www.pp4s.co.uk/main/gs-pi-intro.html)
11091111- [Lazberry Pi: Comprehensive information on Lazarus on the Raspberry Pi computer](http://superbitysoft.co.uk/lazberrypi/).
11101112- [Stefan Fischer's Lazarus unit rpi_hal](http://www.lazarus.freepascal.org/index.php/topic,20991.0.html).
11111113- [Improved Lazarus Unit for fast access to GPIO](http://www.meltonisl.com/software.html).
11121114- [PXL - Platform eXtended Library](http://asphyre.net/products/pxl).
11131115
11141116---
11151117*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