Sign in Join
Wiki copytemporary

Lazarus on Raspberry Pi/es: what changed

Revision 2 to 3. 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
3-<img src="Lazarus_on_Raspberry_Pi_Raspian_Wheezy_version_2012-10-28.png" title="Lazarus on Raspbian Wheezy" width="200" alt="Lazarus on Raspbian Wheezy" /> *(Raspberry Pi only)*
3+![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
2828Install 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
2929
3030Si 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).
3131
3232#### Raspberry Pi 2
3333
3434Desde 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/).
3535
3636<File:Lazarus> 0 9 30 4 on RPi 2.png\|Lazarus "out of the box" en Raspberry Pi 2
3737
3838160
3939
4040#### Raspberry Pi 3
4141
4242Ver Raspberry Pi 2.
4343
4444![](/wiki-images/5/50/RaspBerryPi3B%2B.png)
4545
4646<File:RaspBerryPi3B+_img1.png>
4747
4848<File:RaspBerryPi3B+_img2.png>
4949
5050Como se puede observar tiene más pines de los cuales se debe consultar la funcionalidad de cada uno antes de conectar algo.
5151
5252![](/wiki-images/f/f3/RaspBerryPi3B%2B_img3.png)
5353
5454### Compilación cruzada (cross compiling) para Raspberry Pi desde Windows
5555
56561\. Utilizando fpcup
5757
5858Un camino es utilizar fpcup para configurar un compilador cruzado; seguir estas instrucciones:
5959
6060[[fpcup|fpcup#Linux_ARM_cross_compiler]]
6161
62622\. Utilizando scripts
6363
6464Alternativamente, para una aproximación más manual, y utilizando ficheros de proceso por lotes, puedes seguir los siguientes pasos.
6565
66662.1 Prerequisitos
6767
6868`FPC 2.7.1 or higher installed with sourcecode`\
6969`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)
7070
71712.2 Script ejemplo para construir (adaptar los trayectos a como se necesiten)
7272
7373``` bat
7474set PATH=C:\pp\bin\i386-win32;%PATH%;
7575set FPCMAKEPATH=C:/pp
7676set FPCPATH=C:/pp
7777set OUTPATH=C:/pp271
7878%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
7979
8080%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
8181if errorlevel 1 goto quit
8282%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%
8383
8484:quit
8585pause
8686```
8787
8888Con 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.
8989
9090### Compilando desde el código fuente
9191
9292Puede 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..
9393
9494<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
9595
9696Compilando desde las fuentes en Raspberry con Gentoo (y otra distro)
9797
9898------------------------------------------------------------------------
9999
100100Si necesitas instalar la última release estable de fpc y, adicional y aisladamente, el compilador fpc del trunk entonces puedes leer la siguiente guía.
101101
102102Esto se escribió utilizando Gentoo, pero esta guía debería ser de utilidad para cualquier otra distro: [[Install fpc on Raspberry with Gentoo]]
103103
104104## Accediendo a hardware externo
105105
106-<img src="rpi_pinout_all_50.png" title="Raspberry Pi pinout of external connectors" width="300" />
106+![](/wiki-images/f/f2/Rpi_pinout_all_50.png)
107107
108108Una 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):
109109
1101101. [[Lazarus on Raspberry Pi|Direct access]] Utilizando la unidad [[BaseUnix]].
1111112. Acceso a través de [[Lazarus on Raspberry Pi|encapsulated shell calls]]
1121123. Acceso a través de [[Lazarus on Raspberry Pi|wiringPi library]].
1131134. Acceso a través de la unidad [[Lazarus on Raspberry Pi|rpi_hal]].
1141145. Acceso a través de la unidad [[Lazarus on Raspberry Pi|PiGpio]].
1151156. Acceso a través de la librería [PascalIO](https://github.com/SAmeis/pascalio).
1161167. Acceso a través de la librería [PXL](http://asphyre.net/products/pxl).
117117
118118### Acceso nativo al hardware
119119
120120![ 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.
121121
122122#### Conmutando un dispositivo a través de un puerto GPIO
123123
124124El 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*.
125125
126126Para 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.
127127
128128El 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:
129129
130130``` bash
131131sudo adduser pi gpio
132132sudo adduser pi i2c
133133sudo adduser pi spi
134134```
135135
136136*Unidad de control:*
137137
138138``` pascal
139139unit Unit1;
140140
141141{Demo application for GPIO on Raspberry Pi}
142142{Inspired by the Python input/output demo application by Gareth Halfacree}
143143{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
144144
145145{$mode objfpc}{$H+}
146146
147147interface
148148
149149uses
150150 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
151151 Unix, BaseUnix;
152152
153153type
154154
155155 { TForm1 }
156156
157157 TForm1 = class(TForm)
158158 LogMemo: TMemo;
159159 GPIO17ToggleBox: TToggleBox;
160160 procedure FormActivate(Sender: TObject);
161161 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
162162 procedure GPIO17ToggleBoxChange(Sender: TObject);
163163 private
164164 { private declarations }
165165 public
166166 { public declarations }
167167 end;
168168
169169const
170170 PIN_17: PChar = '17';
171171 PIN_ON: PChar = '1';
172172 PIN_OFF: PChar = '0';
173173 OUT_DIRECTION: PChar = 'out';
174174
175175var
176176 Form1: TForm1;
177177 gReturnCode: longint; {stores the result of the IO operation}
178178
179179implementation
180180
181181{$R *.lfm}
182182
183183{ TForm1 }
184184
185185procedure TForm1.FormActivate(Sender: TObject);
186186var
187187 fileDesc: integer;
188188begin
189189 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
190190 try
191191 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
192192 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
193193 LogMemo.Lines.Add(IntToStr(gReturnCode));
194194 finally
195195 gReturnCode := fpclose(fileDesc);
196196 LogMemo.Lines.Add(IntToStr(gReturnCode));
197197 end;
198198 { Set SoC pin 17 as output: }
199199 try
200200 fileDesc := fpopen('/sys/class/gpio/gpio17/direction', O_WrOnly);
201201 gReturnCode := fpwrite(fileDesc, OUT_DIRECTION[0], 3);
202202 LogMemo.Lines.Add(IntToStr(gReturnCode));
203203 finally
204204 gReturnCode := fpclose(fileDesc);
205205 LogMemo.Lines.Add(IntToStr(gReturnCode));
206206 end;
207207end;
208208
209209procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
210210var
211211 fileDesc: integer;
212212begin
213213 { Free SoC pin 17: }
214214 try
215215 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
216216 gReturnCode := fpwrite(fileDesc, PIN_17[0], 2);
217217 LogMemo.Lines.Add(IntToStr(gReturnCode));
218218 finally
219219 gReturnCode := fpclose(fileDesc);
220220 LogMemo.Lines.Add(IntToStr(gReturnCode));
221221 end;
222222end;
223223
224224procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
225225var
226226 fileDesc: integer;
227227begin
228228 if GPIO17ToggleBox.Checked then
229229 begin
230230 { Swith SoC pin 17 on: }
231231 try
232232 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
233233 gReturnCode := fpwrite(fileDesc, PIN_ON[0], 1);
234234 LogMemo.Lines.Add(IntToStr(gReturnCode));
235235 finally
236236 gReturnCode := fpclose(fileDesc);
237237 LogMemo.Lines.Add(IntToStr(gReturnCode));
238238 end;
239239 end
240240 else
241241 begin
242242 { Switch SoC pin 17 off: }
243243 try
244244 fileDesc := fpopen('/sys/class/gpio/gpio17/value', O_WrOnly);
245245 gReturnCode := fpwrite(fileDesc, PIN_OFF[0], 1);
246246 LogMemo.Lines.Add(IntToStr(gReturnCode));
247247 finally
248248 gReturnCode := fpclose(fileDesc);
249249 LogMemo.Lines.Add(IntToStr(gReturnCode));
250250 end;
251251 end;
252252end;
253253
254254end.
255255```
256256
257257*Programa principal:*
258258
259259``` pascal
260260program io_test;
261261
262262{$mode objfpc}{$H+}
263263
264264uses
265265 {$IFDEF UNIX}{$IFDEF UseCThreads}
266266 cthreads,
267267 {$ENDIF}{$ENDIF}
268268 Interfaces, // this includes the LCL widgetset
269269 Forms, Unit1
270270 { puedes añadir unidades después de esto };
271271
272272{$R *.res}
273273
274274begin
275275 Application.Initialize;
276276 Application.CreateForm(TForm1, Form1);
277277 Application.Run;
278278end.
279279```
280280
281281#### Leyendo el estado de un pin
282282
283283![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)
284284
285285Por supuesto también es posible leer el estado de un pulsador conectado a un puerto GPIO (General Porpouse Inpunt Output).
286286
287287El 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.
288288
289289Para 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.
290290
291291Ten 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.
292292
293293Este programa tiene que ser ejecutado también como usuario root.
294294
295295*Unidad de control:*
296296
297297``` pascal
298298unit Unit1;
299299
300300{Demo application for GPIO on Raspberry Pi}
301301{Inspired by the Python input/output demo application by Gareth Halfacree}
302302{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
303303
304304{This application reads the status of a push-button}
305305
306306{$mode objfpc}{$H+}
307307
308308interface
309309
310310uses
311311 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
312312 ButtonPanel, Unix, BaseUnix;
313313
314314type
315315
316316 { TForm1 }
317317
318318 TForm1 = class(TForm)
319319 ApplicationProperties1: TApplicationProperties;
320320 GPIO18CheckBox: TCheckBox;
321321 LogMemo: TMemo;
322322 procedure ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
323323 procedure FormActivate(Sender: TObject);
324324 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
325325 private
326326 { private declarations }
327327 public
328328 { public declarations }
329329 end;
330330
331331const
332332 PIN_18: PChar = '18';
333333 IN_DIRECTION: PChar = 'in';
334334
335335var
336336 Form1: TForm1;
337337 gReturnCode: longint; {stores the result of the IO operation}
338338
339339implementation
340340
341341{$R *.lfm}
342342
343343{ TForm1 }
344344
345345procedure TForm1.FormActivate(Sender: TObject);
346346var
347347 fileDesc: integer;
348348begin
349349 { Prepare SoC pin 18 (pin 12 on GPIO port) for access: }
350350 try
351351 fileDesc := fpopen('/sys/class/gpio/export', O_WrOnly);
352352 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
353353 LogMemo.Lines.Add(IntToStr(gReturnCode));
354354 finally
355355 gReturnCode := fpclose(fileDesc);
356356 LogMemo.Lines.Add(IntToStr(gReturnCode));
357357 end;
358358 { Set SoC pin 18 as input: }
359359 try
360360 fileDesc := fpopen('/sys/class/gpio/gpio18/direction', O_WrOnly);
361361 gReturnCode := fpwrite(fileDesc, IN_DIRECTION[0], 2);
362362 LogMemo.Lines.Add(IntToStr(gReturnCode));
363363 finally
364364 gReturnCode := fpclose(fileDesc);
365365 LogMemo.Lines.Add(IntToStr(gReturnCode));
366366 end;
367367end;
368368
369369procedure TForm1.ApplicationProperties1Idle(Sender: TObject; var Done: Boolean);
370370var
371371 fileDesc: integer;
372372 buttonStatus: string[1] = '1';
373373begin
374374 try
375375 { Open SoC pin 18 (pin 12 on GPIO port) in read-only mode: }
376376 fileDesc := fpopen('/sys/class/gpio/gpio18/value', O_RdOnly);
377377 if fileDesc > 0 then
378378 begin
379379 { Read status of this pin (0: button pressed, 1: button released): }
380380 gReturnCode := fpread(fileDesc, buttonStatus[1], 1);
381381 LogMemo.Lines.Add(IntToStr(gReturnCode) + ': ' + buttonStatus);
382382 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
383383 if buttonStatus = '0' then
384384 GPIO18CheckBox.Checked := true
385385 else
386386 GPIO18CheckBox.Checked := false;
387387 end;
388388 finally
389389 { Close SoC pin 18 (pin 12 on GPIO port) }
390390 gReturnCode := fpclose(fileDesc);
391391 LogMemo.Lines.Add(IntToStr(gReturnCode));
392392 LogMemo.SelStart := Length(LogMemo.Lines.Text) - 1;
393393 end;
394394end;
395395
396396procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
397397var
398398 fileDesc: integer;
399399begin
400400 { Free SoC pin 18: }
401401 try
402402 fileDesc := fpopen('/sys/class/gpio/unexport', O_WrOnly);
403403 gReturnCode := fpwrite(fileDesc, PIN_18[0], 2);
404404 LogMemo.Lines.Add(IntToStr(gReturnCode));
405405 finally
406406 gReturnCode := fpclose(fileDesc);
407407 LogMemo.Lines.Add(IntToStr(gReturnCode));
408408 end;
409409end;
410410
411411end.
412412```
413413
414414El programa main es idéntico al del ejemplo de arriba.
415415
416416### Acceso hardware mediante llamadas encapsuladas del shell
417417
418418Otro 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.
419419
420420*Controlling unit:*
421421
422422``` pascal
423423unit Unit1;
424424
425425{Demo application for GPIO on Raspberry Pi}
426426{Inspired by the Python input/output demo application by Gareth Halfacree}
427427{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
428428
429429{$mode objfpc}{$H+}
430430
431431interface
432432
433433uses
434434 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Unix;
435435
436436type
437437
438438 { TForm1 }
439439
440440 TForm1 = class(TForm)
441441 LogMemo: TMemo;
442442 GPIO17ToggleBox: TToggleBox;
443443 procedure FormActivate(Sender: TObject);
444444 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
445445 procedure GPIO17ToggleBoxChange(Sender: TObject);
446446 private
447447 { private declarations }
448448 public
449449 { public declarations }
450450 end;
451451
452452var
453453 Form1: TForm1;
454454 gReturnCode: longint; {stores the result of the IO operation}
455455
456456implementation
457457
458458{$R *.lfm}
459459
460460{ TForm1 }
461461
462462procedure TForm1.FormActivate(Sender: TObject);
463463begin
464464 { Prepare SoC pin 17 (pin 11 on GPIO port) for access: }
465465 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/export');
466466 LogMemo.Lines.Add(IntToStr(gReturnCode));
467467 { Set SoC pin 17 as output: }
468468 gReturnCode := fpsystem('echo "out" > /sys/class/gpio/gpio17/direction');
469469 LogMemo.Lines.Add(IntToStr(gReturnCode));
470470end;
471471
472472procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
473473begin
474474 { Free SoC pin 17: }
475475 gReturnCode := fpsystem('echo "17" > /sys/class/gpio/unexport');
476476 LogMemo.Lines.Add(IntToStr(gReturnCode));
477477end;
478478
479479procedure TForm1.GPIO17ToggleBoxChange(Sender: TObject);
480480begin
481481 if GPIO17ToggleBox.Checked then
482482 begin
483483 { Swith SoC pin 17 on: }
484484 gReturnCode := fpsystem('echo "1" > /sys/class/gpio/gpio17/value');
485485 LogMemo.Lines.Add(IntToStr(gReturnCode));
486486 end
487487 else
488488 begin
489489 { Switch SoC pin 17 off: }
490490 gReturnCode := fpsystem('echo "0" > /sys/class/gpio/gpio17/value');
491491 LogMemo.Lines.Add(IntToStr(gReturnCode));
492492 end;
493493end;
494494
495495end.
496496```
497497
498498El programa main es idéntico al del ejemplo de arriba. Este programa necesita ejecutarse con privilegios de root también.
499499
500500### Procedimientos y funciones de wiringPi
501501
502502Alex Schaller's wrapper unit for Gordon Henderson's Arduino compatible wiringPi library provides a numbering scheme that resembles that of Arduino boards.
503503
504504**Function wiringPiSetup:longint:** Initializes wiringPi system using the wiringPi pin numbering scheme.
505505
506506**Procedure wiringPiGpioMode(mode:longint):** Initializes wiringPi system with the Broadcom GPIO pin numbering scheme.
507507
508508**Procedure pullUpDnControl(pin:longint;** pud:longint): controls the internal pull-up/down resistors on a GPIO pin.
509509
510510**Procedure pinMode(pin:longint; mode:longint):** sets the mode of a pin to either INPUT, OUTPUT, or PWM_OUTPUT.
511511
512512**Procedure digitalWrite(pin:longint; value:longint):** sets an output bit.
513513
514514**Procedure pwmWrite(pin:longint; value:longint):** sets an output PWM value between 0 and 1024.
515515
516516**Function digitalRead(pin:longint):longint:** reads the value of a given Pin, returning 1 or 0.
517517
518518**Procedure delay(howLong:dword):** waits for at least howLong milliseconds.
519519
520520**Procedure delayMicroseconds(howLong:dword):** waits for at least howLong microseconds.
521521
522522**Function millis:dword:** returns the number of milliseconds since the program called one of the wiringPiSetup functions.
523523
524524### rpi_hal-Hardware Abstraction Library (funciones y procedimientos GPIO, I2C y SPI de la librería de abstracción hardware de la RaspBerry Pi)
525525
526526Esta 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:
527527
528528Justamente un extracto de los procedimientos y funciones disponibles:
529529
530530**procedure gpio_set_pin (pin:longword;highlevel:boolean);** { Establece RPi GPIO pin a nivel alto o bajo; Velocidad @ 700MHz -\> 0.65MHz }
531531
532532**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 }
533533
534534**procedure gpio_set_input (pin:longword);** { Establece RPi GPIO pin en modo entrada }
535535
536536**procedure gpio_set_output(pin:longword);** { Establece RPi GPIO pin en modo salida}
537537
538538**procedure gpio_set_alt (pin,altfunc:longword);** { Establece RPi GPIO pin to alternate function nr. 0..5 }
539539
540540**procedure gpio_set_gppud (mask:longword);** { Establece RPi GPIO Pull-up/down Register (GPPUD) with mask }
541541
542542...
543543
544544**function rpi_snr :string;** { Emtrega el SNR: 0000000012345678 }
545545
546546**function rpi_hw :string;** { Entrega el tipo de procesador: BCM2708 }
547547
548548**function rpi_proc:string;** { ARMv6-compatible processor rev 7 (v6l) }
549549
550550...
551551
552552**function i2c_bus_write(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
553553
554554**function i2c_bus_read (baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : integer;**
555555
556556**function i2c_string_read(baseadr,reg:word; var <data:databuf_t>; lgt:byte; testnr:integer) : string;**
557557
558558**function i2c_string_write(baseadr,reg:word; s:string; testnr:integer) : integer;**
559559
560560...
561561
562562**procedure SPI_Write(devnum:byte; reg,data:word);**
563563
564564**function SPI_Read(devnum:byte; reg:word) : byte;**
565565
566566**procedure SPI_BurstRead2Buffer (devnum,start_reg:byte; xferlen:longword);**
567567
568568**procedure SPI_BurstWriteBuffer (devnum,start_reg:byte; xferlen:longword);** { Write 'len' Bytes from Buffer SPI Dev startig at address 'reg' }
569569
570570...
571571
572572*Test Program (testrpi.pas):*
573573
574574``` pascal
575575//Progama simple de chequeo, el cual utiliza rpi_hal;
576576
577577 program testrpi;
578578 uses rpi_hal;
579579 begin
580580 writeln('Show CPU-Info, RPI-HW-Info and Registers:');
581581 rpi_show_all_info;
582582 writeln('Let Status LED Blink. Using GPIO functions:');
583583 GPIO_PIN_TOGGLE_TEST;
584584 writeln('Test SPI Read function. (piggy back board with installed RFM22B Module is required!)');
585585 Test_SPI;
586586 end.
587587```
588588
589589### Unidad nativa PiGpio de bajo nivel escrita en pascal (control GPIO en lugar de la librería c de wiringPi)
590590
591591*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) :*
592592
593593``` pascal
594594
595595unit PiGpio;
596596{
597597 BCM2835 GPIO Registry Driver, also can use to manipulate cpu other registry areas
598598
599599 This code is tested only Broadcom bcm2835 cpu, different arm cpus may need different
600600 gpio driver implementation
601601
602602 2013 Gabor Szollosi
603603}
604604{$mode objfpc}{$H+}
605605
606606interface
607607
608608uses
609609 Classes, SysUtils;
610610
611611const
612612 REG_GPIO = $3F000;// bcm2835 gpio register 0x2000 0000 (RPi1), 0x3F00 0000 (RPi2)
613613 // new fpMap uses page offset, one page is 4096 bytes = 0x1000 so simply calculate 0x2000 0000 / 0x1000 = 0x2000 0
614614 PAGE_SIZE = 4096;
615615 BLOCK_SIZE = 4096;
616616 // The BCM2835 has 54 GPIO pins.
617617 // BCM2835 data sheet, Page 90 onwards.
618618 // There are 6 control registers, each control the functions of a block
619619 // of 10 pins.
620620
621621 CLOCK_BASE = (REG_GPIO + $101);
622622 GPIO_BASE = (REG_GPIO + $200);
623623 GPIO_PWM = (REG_GPIO + $20C);
624624
625625 INPUT = 0;
626626 OUTPUT = 1;
627627 PWM_OUTPUT = 2;
628628 LOW = False;
629629 HIGH = True;
630630 PUD_OFF = 0;
631631 PUD_DOWN = 1;
632632 PUD_UP = 2;
633633
634634 // PWM
635635
636636 PWM_CONTROL = 0;
637637 PWM_STATUS = 4;
638638 PWM0_RANGE = 16;
639639 PWM0_DATA = 20;
640640 PWM1_RANGE = 32;
641641 PWM1_DATA = 36;
642642
643643 PWMCLK_CNTL = 160;
644644 PWMCLK_DIV = 164;
645645
646646 PWM1_MS_MODE = $8000; // Run in MS mode
647647 PWM1_USEFIFO = $2000; // Data from FIFO
648648 PWM1_REVPOLAR = $1000; // Reverse polarity
649649 PWM1_OFFSTATE = $0800; // Ouput Off state
650650 PWM1_REPEATFF = $0400; // Repeat last value if FIFO empty
651651 PWM1_SERIAL = $0200; // Run in serial mode
652652 PWM1_ENABLE = $0100; // Channel Enable
653653
654654 PWM0_MS_MODE = $0080; // Run in MS mode
655655 PWM0_USEFIFO = $0020; // Data from FIFO
656656 PWM0_REVPOLAR = $0010; // Reverse polarity
657657 PWM0_OFFSTATE = $0008; // Ouput Off state
658658 PWM0_REPEATFF = $0004; // Repeat last value if FIFO empty
659659 PWM0_SERIAL = $0002; // Run in serial mode
660660 PWM0_ENABLE = $0001; // Channel Enable
661661
662662type
663663
664664 { TIoPort }
665665
666666 TIoPort = class // IO bank object
667667 private //
668668
669669 //function get_pinDirection(aPin: TGpIoPin): TGpioPinConf;
670670
671671 public
672672 FGpio: ^LongWord;
673673 FClk: ^LongWord;
674674 FPwm: ^LongWord;
675675 procedure SetPinMode(gpin, mode: byte);
676676 function GetBit(gpin : byte):boolean;inline; // gets pin bit}
677677 procedure ClearBit(gpin : byte);inline;// write pin to 0
678678 procedure SetBit(gpin : byte);inline;// write pin to 1
679679 procedure SetPullMode(gpin, mode: byte);
680680 procedure PwmWrite(gpin : byte; value : LongWord);inline;// write pin to pwm value
681681 end;
682682
683683 { TIoDriver }
684684
685685 TIoDriver = class
686686 private
687687
688688 public
689689 destructor Destroy;override;
690690 function MapIo:boolean;// creates io memory mapping
691691 procedure UnmapIoRegisrty(FMap: TIoPort);// close io memory mapping
692692 function CreatePort(PortGpio, PortClk, PortPwm: LongWord):TIoPort; // create new IO port
693693 end;
694694
695695var
696696
697697 fd: integer;// /dev/mem file handle
698698procedure delayNanoseconds (howLong : LongWord);
699699
700700implementation
701701
702702uses
703703 baseUnix, Unix;
704704
705705procedure delayNanoseconds (howLong : LongWord);
706706var
707707 sleeper, dummy : timespec;
708708begin
709709 sleeper.tv_sec := 0 ;
710710 sleeper.tv_nsec := howLong ;
711711 fpnanosleep (@sleeper,@dummy) ;
712712end;
713713{ TIoDriver }
714714//*******************************************************************************
715715destructor TIoDriver.Destroy;
716716begin
717717 inherited Destroy;
718718end;
719719//*******************************************************************************
720720function TIoDriver.MapIo: boolean;
721721begin
722722 Result := True;
723723 fd := fpopen('/dev/mem', O_RdWr or O_Sync); // Open the master /dev/memory device
724724 if fd < 0 then
725725 begin
726726 Result := False; // unsuccessful memory mapping
727727 end;
728728 //
729729end;
730730//*******************************************************************************
731731procedure TIoDriver.UnmapIoRegisrty(FMap:TIoPort);
732732begin
733733 if FMap.FGpio <> nil then
734734 begin
735735 fpMUnmap(FMap.FGpio,PAGE_SIZE);
736736 FMap.FGpio := Nil;
737737 end;
738738 if FMap.FClk <> nil then
739739 begin
740740 fpMUnmap(FMap.FClk,PAGE_SIZE);
741741 FMap.FClk := Nil;
742742 end;
743743 if FMap.FPwm <> nil then
744744 begin
745745 fpMUnmap(FMap.FPwm ,PAGE_SIZE);
746746 FMap.FPwm := Nil;
747747 end;
748748end;
749749//*******************************************************************************
750750function TIoDriver.CreatePort(PortGpio, PortClk, PortPwm: LongWord): TIoPort;
751751begin
752752 Result := TIoPort.Create;// new io port, pascal calls new fpMap, where offst is page sized 4096 bytes!!!
753753 Result.FGpio := FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortGpio); // port config gpio memory
754754 Result.FClk:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortClk);; // port clk
755755 Result.FPwm:= FpMmap(Nil, PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, fd, PortPwm);; // port pwm
756756end;
757757//*******************************************************************************
758758procedure TIoPort.SetPinMode(gpin, mode: byte);
759759var
760760 fSel, shift, alt : byte;
761761 gpiof, clkf, pwmf : ^LongWord;
762762begin
763763 fSel := (gpin div 10)*4 ; //Select Gpfsel 0 to 5 register
764764 shift := (gpin mod 10)*3 ; //0-9 pin shift
765765 gpiof := Pointer(LongWord(Self.FGpio)+fSel);
766766 if (mode = INPUT) then
767767 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) //7 shl shift komplemens - Sets bits to zero = input
768768 else if (mode = OUTPUT) then
769769 begin
770770 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (1 shl shift);
771771 end
772772 else if (mode = PWM_OUTPUT) then
773773 begin
774774 Case gpin of
775775 12,13,40,41,45 : alt:= 4 ;
776776 18,19 : alt:= 2 ;
777777 else alt:= 0 ;
778778 end;
779779 If alt > 0 then
780780 begin
781781 gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (alt shl shift);
782782 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
783783 clkf^ := $5A000011 or (1 shl 5) ; //stop clock
784784 delayNanoseconds(200);
785785 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_DIV);
786786 clkf^ := $5A000000 or (32 shl 12) ; // set pwm clock div to 32 (19.2/3 = 600KHz)
787787 clkf := Pointer(LongWord(Self.FClk)+PWMCLK_CNTL);
788788 clkf^ := $5A000011 ; //start clock
789789 Self.ClearBit(gpin);
790790 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
791791 pwmf^ := 0 ; // Disable PWM
792792 delayNanoseconds(200);
793793 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_RANGE);
794794 pwmf^ := $400 ; //max: 1023
795795 delayNanoseconds(200);
796796 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_RANGE);
797797 pwmf^ := $400 ; //max: 1023
798798 delayNanoseconds(200);
799799 // Enable PWMs
800800 pwmf := Pointer(LongWord(Self.FPwm)+PWM0_DATA);
801801 pwmf^ := 0 ; //start value
802802 pwmf := Pointer(LongWord(Self.FPwm)+PWM1_DATA);
803803 pwmf^ := 0 ; //start value
804804 pwmf := Pointer(LongWord(Self.FPwm)+PWM_CONTROL);
805805 pwmf^ := PWM0_ENABLE or PWM1_ENABLE ;
806806 end;
807807 end;
808808end;
809809//*******************************************************************************
810810procedure TIoPort.SetBit(gpin : byte);
811811var
812812 gpiof : ^LongWord;
813813begin
814814 gpiof := Pointer(LongWord(Self.FGpio) + 28 + (gpin shr 5) shl 2);
815815 gpiof^ := 1 shl gpin;
816816end;
817817//*******************************************************************************
818818procedure TIoPort.ClearBit(gpin : byte);
819819var
820820 gpiof : ^LongWord;
821821begin
822822 gpiof := Pointer(LongWord(Self.FGpio) + 40 + (gpin shr 5) shl 2);
823823 gpiof^ := 1 shl gpin;
824824end;
825825//*******************************************************************************
826826function TIoPort.GetBit(gpin : byte):boolean;
827827var
828828 gpiof : ^LongWord;
829829begin
830830 gpiof := Pointer(LongWord(Self.FGpio) + 52 + (gpin shr 5) shl 2);
831831 if (gpiof^ and (1 shl gpin)) = 0 then Result := False else Result := True;
832832end;
833833//*******************************************************************************
834834procedure TIoPort.SetPullMode(gpin, mode: byte);
835835var
836836 pudf, pudclkf : ^LongWord;
837837begin
838838 pudf := Pointer(LongWord(Self.FGpio) + 148 );
839839 pudf^ := mode; //mode = 0, 1, 2 :Off, Down, Up
840840 delayNanoseconds(200);
841841 pudclkf := Pointer(LongWord(Self.FGpio) + 152 + (gpin shr 5) shl 2);
842842 pudclkf^ := 1 shl gpin ;
843843 delayNanoseconds(200);
844844 pudf^ := 0 ;
845845 pudclkf^ := 0 ;
846846end;
847847//*******************************************************************************
848848procedure TIoPort.PwmWrite(gpin : byte; value : Longword);
849849var
850850 pwmf : ^LongWord;
851851 port : byte;
852852begin
853853 Case gpin of
854854 12,18,40 : port:= PWM0_DATA ;
855855 13,19,41,45 : port:= PWM1_DATA ;
856856 else exit;
857857 end;
858858 pwmf := Pointer(LongWord(Self.FPwm) + port);
859859 pwmf^ := value and $FFFFFBFF; // $400 complemens
860860end;
861861//*******************************************************************************
862862end.
863863```
864864
865865*Controlling Lazarus unit:(Project files[3](https://drive.google.com/folderview?id=0B-b-5ooIWPvGU043ZTZ0cUc2YkE&usp=sharing))*
866866
867867``` pascal
868868unit Unit1;
869869
870870{Demo application for GPIO on Raspberry Pi}
871871{Inspired by the Python input/output demo application by Gareth Halfacree}
872872{written for the Raspberry Pi User Guide, ISBN 978-1-118-46446-5}
873873
874874{$mode objfpc}{$H+}
875875
876876interface
877877
878878uses
879879 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
880880 ExtCtrls, Unix, PiGpio;
881881
882882type
883883
884884 { TForm1 }
885885
886886 TForm1 = class(TForm)
887887 GPIO25In: TButton;
888888 SpeedButton: TButton;
889889 LogMemo: TMemo;
890890 GPIO23switch: TToggleBox;
891891 Timer1: TTimer;
892892 GPIO18Pwm: TToggleBox;
893893 Direction: TToggleBox;
894894 procedure DirectionChange(Sender: TObject);
895895 procedure GPIO18PwmChange(Sender: TObject);
896896 procedure GPIO25InClick(Sender: TObject);
897897 procedure FormActivate(Sender: TObject);
898898 procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
899899 procedure GPIO23switchChange(Sender: TObject);
900900 procedure SpeedButtonClick(Sender: TObject);
901901 procedure Timer1Timer(Sender: TObject);
902902 private
903903 { private declarations }
904904 public
905905 { public declarations }
906906 end;
907907
908908const
909909 INPUT = 0;
910910 OUTPUT = 1;
911911 PWM_OUTPUT = 2;
912912 LOW = False;
913913 HIGH = True;
914914 PUD_OFF = 0;
915915 PUD_DOWN = 1;
916916 PUD_UP = 2;
917917 // Convert Raspberry Pi P1 pins (Px) to GPIO port
918918 P3 = 0;
919919 P5 = 1;
920920 P7 = 4;
921921 P8 = 14;
922922 P10 = 15;
923923 P11 = 17;
924924 P12 = 18;
925925 P13 = 21;
926926 P15 = 22;
927927 P16 = 23;
928928 P18 = 24;
929929 P19 = 10;
930930 P21 = 9;
931931 P22 = 25;
932932 P23 = 11;
933933 P24 = 8;
934934 P26 = 7;
935935
936936var
937937 Form1: TForm1;
938938 GPIO_Driver: TIoDriver;
939939 GpF: TIoPort;
940940 PWM :Boolean;
941941 i, d : integer;
942942 Pin,Pout,Ppwm : byte;
943943
944944implementation
945945
946946{$R *.lfm}
947947
948948{ TForm1 }
949949
950950procedure TForm1.FormActivate(Sender: TObject);
951951begin
952952 if not GPIO_Driver.MapIo then
953953 begin
954954 LogMemo.Lines.Add('Error mapping gpio registry');
955955 end
956956 else
957957 begin
958958 GpF := GpIo_Driver.CreatePort(GPIO_BASE, CLOCK_BASE, GPIO_PWM);
959959 end ;
960960 Timer1.Enabled:= True;
961961 Timer1.Interval:= 25; //25 ms controll interval
962962 Pin := P22;
963963 Pout := P16;
964964 Ppwm := P12;
965965 i:=1;
966966 GpF.SetPinMode(Pout,OUTPUT);
967967 GpF.SetPinMode(Pin,INPUT);
968968 GpF.SetPullMode(Pin,PUD_Up); // Input PullUp High level
969969end;
970970
971971procedure TForm1.GPIO25InClick(Sender: TObject);
972972begin
973973 If GpF.GetBit(Pin) then LogMemo.Lines.Add('In: '+IntToStr(1))
974974 else LogMemo.Lines.Add('In: '+IntToStr(0));
975975end;
976976
977977procedure TForm1.GPIO18PwmChange(Sender: TObject);
978978begin
979979 if GPIO18Pwm.Checked then
980980 begin
981981 GpF.SetPinMode(Ppwm,PWM_OUTPUT);
982982 PWM := True; //PWM on
983983 end
984984 else
985985 begin
986986 GpF.SetPinMode(Ppwm,INPUT);
987987 PWM := False; //PWM off
988988 end;
989989end;
990990
991991procedure TForm1.DirectionChange(Sender: TObject);
992992begin
993993 if Direction.Checked then d:=10 else d:=-10;
994994end;
995995
996996
997997procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction);
998998begin
999999 GpF.SetPinMode(Ppwm,INPUT);
10001000 GpF.ClearBit(Pout);
10011001 GpIo_Driver.UnmapIoRegisrty(GpF);
10021002end;
10031003
10041004procedure TForm1.GPIO23switchChange(Sender: TObject);
10051005
10061006Begin
10071007 Timer1.Enabled := False;
10081008 if GPIO23switch.Checked then
10091009 begin
10101010 GpF.SetBit(Pout); //Turn LED on
10111011 end
10121012 else
10131013 begin
10141014 GpF.ClearBit(Pout); //Turn LED off
10151015 end;
10161016 Timer1.Enabled := True;
10171017end;
10181018
10191019procedure TForm1.SpeedButtonClick(Sender: TObject);
10201020var
10211021 i,p,k,v: longint;
10221022 ido:TDateTime;
10231023begin
10241024 ido:= Time;
10251025 k:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10261026 LogMemo.Lines.Add('Start: '+TimeToStr(ido));
10271027 p:=10000000 ;
10281028 For i:=1 to p do Begin
10291029 GpF.SetBit(P16);
10301030 GpF.ClearBit(P16);
10311031 end;
10321032 ido:= Time;
10331033 v:= TimeStampToMSecs(DateTimeToTimeStamp(ido));
10341034 LogMemo.Lines.Add('Stop: '+TimeToStr(ido)+' Frequency: '+
10351035 IntToStr(p div (v-k))+' kHz');
10361036end;
10371037
10381038procedure TForm1.Timer1Timer(Sender: TObject);
10391039begin
10401040 If PWM then Begin
10411041 If (d > 0) and (i+d < 1024) then begin
10421042 i:=i+d;
10431043 GpF.PwmWrite(Ppwm,i);
10441044 end ;
10451045 If (d < 0) and (i+d > -1) then begin
10461046 i:=i+d;
10471047 GpF.PwmWrite(Ppwm,i);
10481048 end;
10491049 end;
10501050end;
10511051
10521052
10531053end.
10541054```
10551055
10561056### PXL (Platform eXtended Library) for low level native access to GPIO, I²C, SPI, PWM, UART, V4L2, displays and sensors
10571057
10581058- Fácil y rápido acceso a GPIO, I²C, SPI, PWM, UART y timer de alta preción de la CPU.
10591059- 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.
10601060- OpenGL ES hardware de renderizado con y sin servidor X. Software de renderizado.
10611061- Pantallas I²C y SPI tales como SSD1306, SSD1351, PCB8544 (Nokia), HX8357 y ILI9340.
10621062- LCD de caracteres con cableado de pines directo.
10631063- Suporte para software SPI y UART (bit-banging).
10641064- Suporte para SC16IS7x0 (controladora UART conectada a través de I²C o SPI), incluyendo pins GPIO extra.
10651065- Soporte para sensores tales como BMP180, DHT22, L3GD20, LSM303 y SHT10.
10661066- Otras características como networking, math, transformación de imágenes, efectos, dibujo de primitivas gráficas...
10671067
10681068*Más información y descargas de la [librería PXL](http://asphyre.net/products/pxl).*
10691069
10701070## Referencias
10711071
10721072- Eben Upton and Gareth Halfacree. Raspberry Pi User Guide. John Wiley and Sons, Chichester 2012, ISBN 111846446X
10731073- B. J. Rao (2013) The Raspberry Pi, Pi Vision and Lazarus/FPC. [Blaise Pascal Magazine](http://www.blaisepascal.eu). 29: 14-21.
10741074
10751075## External Links
10761076
10771077- [Raspberry Pi Foundation](http://www.raspberrypi.org)
10781078- [Raspberry Pi Spy: Raspberry Pi tutorials, scripts, help and downloads](http://www.raspberrypi-spy.co.uk)
10791079- [Lazarus wrapper unit for Gordon Henderson's wiringPi C library](http://www.lazarus.freepascal.org/index.php/topic,17404.0.html)
10801080- [Pin layout of the wiringPi library](https://projects.drogon.net/raspberry-pi/wiringpi/pins/)
10811081- [Additional information on Lazarus and Raspberry Pi at eLinux.org](http://www.elinux.org/Lazarus_on_RPi)
10821082- [Getting Started with Pascal on the Pi](http://www.pp4s.co.uk/main/gs-pi-intro.html)
10831083- [Lazberry Pi: Comprehensive information on Lazarus on the Raspberry Pi computer](http://superbitysoft.co.uk/lazberrypi/).
10841084- [Stefan Fischer's Lazarus unit rpi_hal](http://www.lazarus.freepascal.org/index.php/topic,20991.0.html).
10851085- [Improved Lazarus Unit for fast access to GPIO](http://www.meltonisl.com/software.html).
10861086- [PXL - Platform eXtended Library](http://asphyre.net/products/pxl).
10871087
10881088---
10891089*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