Ceci est une ancienne révision du document !
In the previous part of this series, we saw various ways in which our application can run on a Raspberry Pi, turning it either into a lightweight terminal or an equally lightweight application server. In this part, we will focus on what makes the Raspberry Pi unique, and will build a Free Vision interface to make use of the General Purpose I/O (GPIO) port on this small board computer. Our test scenario will be to turn the RPi into a lighting manager, that controls three separate lighting circuits from a Free Vision interface. Each circuit will be controlled by a simple On/Off press button.
Dans la partie précédente de cette série, nous avons vu plusieurs façons pa r lesquelles notre application peut tourner sur un Raspberry Pi, le transformant, soit un terminal léger, soit en serveur d'applications tout aussi léger. Dasn cette partie, nous nous intéresserons sur ce qui rend le Raspberry Pi unique, et nous construirons un interface en Vision pour faire usage des ports d'entrées/sorties d'usage général (GPIO) sur ce petit ordinateur mono-carte.
Notre scénario de test transformera le RPi en gestionnaire d'éclairage, qui pilote trois circuits séparés d'éclairage à partir d'une interface en Free Vision. Chaque circuit sera piloté par un simple bouton poussoir marche/arrêt.
The physical circuit Both the Raspberry Pi models 2 and 3 retain a similar GPIO pin assignment to the earlier B+ models. The 40-pin header has two parallel rows of pins, with the odd numbers inboard and the even closer to the card’s edge. I tend to use the last (right-hand) pins of the outboard row, specifically pins 34, 36, 38 and 40 that are attached to Ground, GPIO ports 16, 20 and 21, respectively. The circuits we will be connecting to the RPi to get the software working will be simple LEDs, though in a real circuit these would be replaced by a high-impedance adapter (probably an optical isolator and a relay or a triac) that would allow us to control normal AC electric circuits. For the time being, we will be connecting the three GPIO ports to one LED’s positive leg each, while the negative legs get connected to a common ground on pin 34.
Le circuit matériel
Les modèles 2 et 3 du Raspberry Pi ont conservé l'assignement de broches GPIO identiques aux modèles B+ plus anciens. Le connecteur 40 broches a deux rangées parallèles de picots, avec les numéros impaires à l'intérieur de la carte et les numéros pairs sur le bord. J'ai tendance à utiliser les derniers picots (à droite) de la rangée, spécialement les broches 34, 36, 38 et 40 qui sont respectivement reliées à la masse et aux ports GPIO 16, 20 et 21.
Les circuits qui seront connectés au RPi pour faire fonctionner le logiciel seront de simples LED, bien que, dans un vrai circuit, celles-ci seraient remplacées par un adaptateur à haute impédance (probablement un isolateur optique, un relais ou un triac) qui nous permettrait de piloter des circuits électriques classiques sur le secteur. Pour l'instant, nous connecterons les trois ports GPIO sur chaque patte positive de LED, alors que chaque patte négative sera branché à la masse commune sur la broche 34.
LEDs need to avoid high current values, with about 15 mA being a safe limit for most robust parts. On the other hand, the RPi’s GPIO ports have even lower working values (2 to 12 mA) both as a source (providing current to drive an external circuit) or as a sink (ground return). This means we need to insert some way of limiting current in series with the LEDs - or risk overloading both the LEDs and the Raspberry Pi itself. A simple way of doing this is to insert a simple resistor into the common ground. We will be using a 1 kΩ part here, though 2.2 kΩ would probably be safer. On this diagram drawn with Fritzing, green, yellow and blue will be used respectively for circuits 1, 2 and 3. Fritzing had only a representation of the RPi 2 in its library, but this is for all practical purposes interchangeable with the RPi 3. To make connections to the RPi, we would need electric cords with female connectors to slip over the RPi’s male pins. However, a typical breadboard will need cords with male pins at their ends. I had no cords with male connectors so, instead of soldering normal cords directly to the Raspberry Pi, I connected several to a short strip of header that can then be placed and removed at will from the computer.
Les forts courants doivent être évités sur les LED, 15 mA étant une limite de sécurité pour la plupart des pièces de qualité. D'un autre côté, les port GPIO du RPi ont plutôt des valeurs de travail plus basses (entre 2 et 12 mA) , comme source (fournissant du courant à un circuit extérieur) ou comme xx (retour à la masse). Ceci signifie que nous avons besoin d'insérer une quelconque limitation de courant en série avec les LED - ou de risquer de surcharger, et les LED, et les Raspberry lui-même. Une manière simple de le faire est d'insérer une simple résistance dans la masse commune. Nous en utiliserons une de 1 k ici, bien que 2,2 k serait plus sûr.
Sur le diagramme tracé avec Fritzing, le vert, le jaune et le bleu seront utilisés respectivement pour les circuits 1, 2 et 3. Fritzing a aussi une représentation du RPi 2 dans sa bibliothèque, mais celle-ci est interchangeable avec le RPi 3 pour tous les cas pratiques.
Pour réaliser les connexions au RPi, nous aurons besoin de câbles électriques avec des connecteurs femelles pour les appliquer aux picots mâles du RPi. Cependant, une plaque d'essai usuelle nécessitera des fils avec des terminaisons mâles aux deux bouts. Je n'avais pas de câbles avec des connecteurs mâles, aussi, plutôt que de souder directement les fils sur les picots du Raspberry Pi, j'en ai connecté plusieurs sur un petit connecteur en ligne qui peut être branché à l'ordinateur et enlevé à volonté.
Controlling the GPIO from Free Pascal There are several projects to build a Pascal unit that controls the GPIO. However, just to make things more interesting, I thought it would be fun to write our own. It is actually quite simple - under Ubuntu as under Raspbian - to control the GPIO pins on a RPi, since the Linux kernel has been patched to give access through the /sys filesystem. We could actually do it with the command-line - though we will need root access to do so. To set up GPIO port 16 for output, for example, we need to: echo 16 > /sys/class/gpio/export echo out > /sys/class/gpio/gpio16/direction We can actually see which ports are activated at a point in time by listing the contents of directory /sys/class/gpio/gpio* - each time a port is activated, a corresponding link appears here. Now, to turn on GPIO 16 (switch it to 5V output), or turn it back off (0V): echo 1 > /sys/class/gpio/gpio16/value echo 0 > /sys/class/gpio/gpio16/value
Piloter les GPIO depuis Free Pascal
Il y a plusieurs projets pour construire une « unit » en Pascal qui pilote les GPIO. Cependant, juste pour rendre les choses plus intéressantes, je pensais qu'il serait amusant de l'écrire nous-même. C'est en fait assez simple - sous Ubuntu comme sous Desbian - de piloter les broches GPIO d'un RPi, car le noyau Linux a été corrigé pour donner accès au système de fichiers /sys. Nous pouvons vraiment le faire en ligne de commande - bien que l'accès comme root soit nécessaire. Pour paramétrer le port GPIO 16 en sortie, par exemple, nous devons faire :
echo 16 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio16/direction
Nous voyons bien que les pots sont activés à un moment en listant les contenus du répertoire /sys/class/gpio/gpio* - chaque fois qu'un port est activé, un lien correspondant apparaît à cet endroit.
Maintenant, pour activer GPIO 16 (mettre la sortie à 5 V), ou l'éteindre (O V) :
echo 1 > /sys/class/gpio/gpio16/value
echo 0 > /sys/class/gpio/gpio16/value
Finally, to release the port: echo 16 > /sys/class/gpio/unexport As can be seen, the /sys interface really helps gain access to the ports, in a way that can easily be ported to any programming language that has access to the file system. Let us do so for Pascal, in a unit appropriately called Gpio (above). It is easier to reference port numbers and values as strings; if they are passed as integers, each value would need to be converted into a string when building file names. The first two routines are to set up a port, either for digital input (setup_input), or output (setup_output). It will both export the port and write its direction: ‘in’ or ‘out’ respectively. Within the implementation section of our unit, we can start by writing a short procedure that serves to append a string to a given file, thus packaging this functionality away from the main procedures (next page, top right).
Enfin, pour libérer ce port :
echo 16 > /sys/class/gpio/unexport
Comme vous le voyez, l'interface /sys aide réellement à accéder aux ports, de façon à ce que ça puisse être porté sur n'importe quel langage de programmation qui a accès au système de fichiers. Faisons-le avec Pascal, dans une « unit » appelée Gpio (ci-dessus).
C'est plus facile de référencer les numéros des ports et les valeurs sous forme de chaînes ; si ils sont passé en entiers, chaque valeur devra être convertie en chaîne pour construire les les noms de fichiers. Les deux premières routines sont là pour paramétrer un port, soit en entrée (setup_input), soit en sortie (setup_output), toutes les deux en numérique. Les deux exportent le port et écrivent sa direction : « in » ou « out », respectivement. Dans la section d'implémentation de l'unit, nous commençons par écrire un courte procédure qui sert à ajouter un chaîne dans un fichier donné ; ainsi, cette fonctionnalité est logée ailleurs que dans les procédures principales (page suivante, en haut à droite).
Finally, procedure release will unexport the port. All of these are rather simple to code, and the complete unit is available at this link: http://pastebin.com/Vnj6ZCqP . A simple program to test this unit could be as follows: To compile and execute this program, we will need to compile both the unit and the program itself, and then execute the binary file as root: fpc gpio.pas fpc test10.pas sudo ./test10
Enfin, la procédure release « dé-exportera » le port. Tout ceci est plutôt simple à coder, et l'unit complète est disponible par ce lien : http://pastebin.com/Vnj6ZCqP .
Pour compiler et exécuter ce programme, nous devrons compiler à la fois l'unit et le programme lui-même, et, ensuite, exécuter le fichier binaire comme root :
fpc gpio.pas
fpc test10.pas
sudo ./test10
Creating a Free Vision interface Let us Integrate our new Gpio unit into a short Free Vision application to control the Rasberry Pi’s three LEDs. We do not need a complete interface, so let us dispense with creating a menu bar and simply load a Dialog box with four buttons: three to control each circuit on GPIO 16, 20 and 21; and a last button to quit the application. Our program will need to access Gpio, and the standard Free Vision units: uses gpio, App, Objects, Menus, Drivers, Views, Dialogs, MsgBox, StdDlg; The application itself will need only a bespoke constructor, that creates and launches our LightsDialog: Finally, the LightsDialog will need a HandleEvent procedure to respond to button presses. This is a tad tedious, since we will need to detect a button press for each button, and for each of those determine if we are going from an On state to Off, or vice-versa. It begins in this way (next page).
Créer une interface avec Free Vision
Intégrons notre nouvelle unit Gpio dans une application en Free Vision pour piloter les trois LED du Raspberry Pi. Nous n'avons pas besoin d'une interface complète ; aussi, dispensons-nous de créer une barre de menu et chargeons simplement une boîte de dialogue avec quatre boutons : trois pour le contrôle de chaque circuit des GPIO 16, 20 et 21, et un dernier bouton pour quitter l'application.
Notre programme aura besoin d'accéder à Gpio et aux units standard de Free Vision :
uses
gpio, App, Objects, Menus, Drivers, Views, Dialogs, MsgBox, StdDlg;
l'application elle-même n'aura besoin que d'un constructeur sur mesure, qui crée et lance notre LightsDialog :
Enfin, LightsDialog aura besoin d'une procédure HandleEvent pour répondre aux appuis sur les boutons. Ceci est un brin pénible, car nous aurons besoin de détecter un appui sur un bouton pour chaque bouton, et pour chacun d'eux de déterminer si nous passons d'Allumé à Éteint, ou vice-versa. Ça commence de cette manière (page suivante) :
The complete code for this program is available here: http://pastebin.com/KdGuJexk . In this seventh part of our series on Free Pascal, we saw how the Raspberry Pi can be wired up to control several LEDs. We then wrote a simple unit in Pascal to access the GPIO port, and finally used the unit inside a Free Vision application to produce a text-based user interface that, quite frankly, is elegant and functional. As an exercise, this project has been quite complete since it combines elements at a very low level close to the hardware, with a very clean object-oriented style of programming. The end result is actually quite practical, since the application can be accessed directly through the Raspberry Pi if it is connected to a screen and keyboard, or over an SSH connection either wired or wireless (if a model 3 is used). To go further, the interested reader could modify the application so that the second circuit switches on at the press of a button, and then turns off when a set time-period has elapsed. A slider could be provided to fine tune the delay time. The third circuit could also be set up to turn on and off at specific times during the day.
From the hardware’s standpoint, our three trusty LEDs may be replaced with something more substantial. However, going on to an AC circuit with voltage levels of 110 to 250 V should really not be attempted unless one is a qualified electrical installer - much caution needs to be exercised when using AC since it can quite readily kill you, either directly or by causing a fire. This is also true even with the 12 VDC used in cars. Proceed at your own risk, and please do your homework first. Having someone who is qualified stand by and check your work - before switching it on - is surely a smart move. It is also wise to remember that any current over 10 to 15 mA going in or coming out can seriously damage the Raspberry Pi, so an optical isolator or some equivalent means of disconnecting the RPi from the load’s level of current will be a must.
Textes en noir dans les zones saumon : p 29 à droite
The complete code to set up a port for writing is rather simple:
Other procedures used are port_write to write to a GPIO port, and function port_read to read from a port that has been configured in the ‘in’ direction:
p 30 à gauche
The LightsDialog type will need a few more elements to work. We will need to keep track of the state of each circuit (True for on, False for off). If we wish to be able to change the caption on each button to reflect the state of the circuit, we will also need to access these buttons from the main Dialog object, so include buttons 1 , 2 and 3 in its declaration:
We will also need several constants, both to identify which GPIO ports will be used to control each circuit, and to store the command identification codes that each button will emit when pressed:
p30 à droite
The LightsDialog can be initialized in a very simple manner. All we need to do is set up the buttons, and then add some code at the end of this constructor to initialize button states for the software, and set up the hardware correctly: