Outils pour utilisateurs

Outils du site


issue122:python

Welcome back to our ‘Temp/Humidity via Bluetooth’ project. As you will remember, last month we got everything working to a smartphone. This month, we will be working on getting things up and running on the Raspberry Pi. The first thing we have to do is get the RPi Bluetooth connected to the Arduino. I’m going to assume that you already have the proper bluetooth software installed on your RPi. I’ve installed bluetooth-5.23-2+rpi2, bluez-5.23-2+rpi2, bluez-firmware-1.2-3+4rpi1, pi-bluetooth-0.1.3 and pulseaudio-module-bluetooth-5.0-13 on my RPi3. I’m sure that some of those are not needed for basic bluetooth communications. There are many places on the web that can explain the process. Once you get everything installed, connect to your Arduino bluetooth device. I had to use “1234” during the pairing process. I also marked it as a trusted device.

Heureux de vous revoir sur notre projet « Température/humidité via Bluetooth ». Comme vous vous en souvenez, nous avons tout mis au point sur un smartphone. Ce mois-ci, nous allons travailler pour mettre les choses en place sur le Raspberry Pi.

La première chose que nous devons faire est de connecter le Bluetooth du RPi à l'Arduino. Je vais supposer que le logiciel bluetooth correct est déjà installé sur votre RPi. J'ai installé luetooth-5.23-2+rpi2, bluez-5.23-2+rpi2, bluez-firmware-1.2-3+4rpi1, pi-bluetooth-0.1.3 et pulseaudio-module-bluetooth-5.0-13 sur mon RPi3. Je suis sûr que certains de ceux-ci ne sont pas nécessaires pour des communications simples en bluetooth.Il y a beaucoup d'endroits sur le Web qui peuvent expliquer le processus. Une fois que tout est installé, connectez-vous à votre dispositif bluetooth de l'Arduino. J'ai dû utiliser « 1234 » pendant le processus d'appairage. Je l'ai aussi coché comme dispositif de confiance.

Once we have it paired and trusted, we need to do some command-line magic to create a virtual serial port named ‘rfcomm1’. In a terminal type: hcitool scan You should see something like: pi@raspberrypi:~ $ hcitool scan Scanning … 98:D3:31:30:49:B1 HC-06 pi@raspberrypi:~ $ The big thing you should take away from this is the mac address of the bluetooth device (hopefully the arduino) that you are connected to. You will be using this address in the next command.

Une fois que nous l'avons appairé et garanti, nous devons faire un peu de magie en ligne de commande pour créer un port série virtuel appelé « rfcomm1 ».

Saisissez dans un terminal :

hcitool scan

Vous devriez voir quelque chose comme :

pi@raspberrypi:~ $ hcitool scan

Scanning …

98:D3:31:30:49:B1	HC-06

pi@raspberrypi:~ $

De tout ça, la chose importante que vous devriez mettre de côté c'est l'adresse mac du dispositif bluetooth (avec un peu de chance, c'est l'Arduino) auquel vous êtes connecté. Vous utiliserez cette adresse dans la prochaine commande.

Now, type: sudo rfcomm bind /dev/rfcomm1 98:D3:31:30:49:B1 Where the 98:D3:31:30:49:B1 is the mac address of the bluetooth H05/06 module on the Arduino that was obtained from the hcitool command above. Yours will be different, so use it. Now in the terminal type: rfcomm Again, you should see something like this: pi@raspberrypi:~ $ rfcomm rfcomm1: 98:D3:31:30:49:B1 channel 1 clean pi@raspberrypi:~ $ This tells you that you now have an open serial port into the Arduino bluetooth device.

Maintenant, tapez :

sudo rfcomm bind /dev/rfcomm1 98:D3:31:30:49:B1

où 98:D3:31:30:49:B1 est l'adresse mac du module bluetooth H05/06 de l'Arduino qui a été obtenue par la commande hcitool ci-dessus. La vôtre sera différente, donc, utilisez-la.

Maintenant, tapez dans le terminal :

rfcomm

À nouveau, vous devriez voir quelque chose comme ceci :

pi@raspberrypi:~ $ rfcomm

rfcomm1: 98:D3:31:30:49:B1 channel 1 clean

pi@raspberrypi:~ $

Cela vous indique que vous disposez d'un port série ouvert dans le dispositif bluetooth de l'Arduino.

Finally, in the terminal type: sudo picocom -c /dev/rfcomm1 In the terminal, you should see: rfcomm1: 98:D3:31:30:49:B1 channel 1 clean picocom v1.7 port is : /dev/rfcomm1 flowcontrol : none baudrate is : 9600 parity is : none databits are : 8 escape is : C-a local echo is : yes noinit is : no noreset is : no nolock is : no send_cmd is : sz -vv receive_cmd is : rz -vv imap is : omap is : emap is : crcrlf,delbs, Terminal ready This will allow you to send a “T” for temperature, an “H” for humidity, or an “A” for both. You will have to repeat most of this process each time you reboot the RPi. I made a shell script that contained those lines so I could run it as needed.

Enfin, saisissez dans le terminal :

sudo picocom -c /dev/rfcomm1

Dans le terminal, vous devriez voir :

rfcomm1: 98:D3:31:30:49:B1 channel 1 clean

picocom v1.7

port is : /dev/rfcomm1 flowcontrol : none baudrate is : 9600 parity is : none databits are : 8 escape is : C-a local echo is : yes noinit is : no noreset is : no nolock is : no send_cmd is : sz -vv receive_cmd is : rz -vv imap is : omap is : emap is : crcrlf,delbs,

Terminal ready

Ceci vous permettra d'envoyer un « T » pour la température, un « H » pour l'humidité ou un « A » pour les deux.

Vous devrez répéter la plupart de ce processus chaque fois que vous redémarrerez le RPi. J'ai fait un script shell qui contient ces lignes, de sorte que je peux le lancer à la demande.

However, this series is about using Python, so, next, we’ll write a simple program to communicate with our Arduino. A simple terminal Program Below is a very simple program in Python that will allow us to communicate to the Arduino via the serial port. The first three lines import the pyserial library and set up the port. import serial port = “/dev/rfcomm1” baud = 19200 The next line uses only some of the parameters available since the others aren’t needed. The important one is the timeout parameter. If we set the timeout to “none”, the system will wait forever (blocking) until the specified number of characters have been received in the .read command. If we set the timeout to 0, the system will return immediately, returning 0 or more characters from the port. We, however will set the timeout to 1 second. You can specify the number of seconds for the system to wait and you can use a float value.

Cependant, cette série est sur l'utilisation de Python ; aussi, pour poursuivre, nous écrirons un programme simple pour communiquer avec notre Arduino.

Un programme simple dans le terminal

Ci-dessous, ce programme très simple en Python nous permettra de communiquer avec l'Arduino via le port série.

Les trois premières lignes importent la bibliothèque pyserial et paramètrent le port série.

import serial

port = “/dev/rfcomm1” baud = 19200

La ligne suivante n'utilise que certains des paramètres disponibles car les autres ne sont pas nécessaires. Celui qui est important est le paramètre de fin de délai (timeout). Si celui-ci est mis à « none » (aucun), le système attendra éternellement (=bloqué) jusqu'à ce que le nombre de caractères spécifiés soit reçu par la commande .read. Si nous réglons le timeout à 0, le système répondra immédiatement, renvoyant 0 ou plusieurs caractères par son port. Vous pouvez spécifier le nombre de secondes d'attente du système et vous pouvez utiliser une valeur en virgule flottante.

ser = serial.Serial(port, baud, timeout=1) In the next two lines (plus the comment), we are simply verifying the serial port is open and then printing that fact. # open the serial port if ser.isOpen(): print(ser.name + ' is open…') Now comes the meat of the program. We start a “forever” loop, sending out a prompt to enter a command or to enter ‘exit’ to quit, and wait for input from the user. This works perfectly for our purposes, since the Arduino is also waiting for a command. It also allows us to terminate the program properly. while True: cmd = raw_input(“Enter command or 'exit':”) # for Python 2 # cmd = input(“Enter command or 'exit':”) # for Python 3 if cmd == 'exit': ser.close() exit()

ser = serial.Serial(port, baud, timeout=1)

Dans les deux lignes suivantes, (plus le commentaire), nous vérifions simplement que le port série est ouvert avec impression de ce fait.

# open the serial port - ouverture du port série

if ser.isOpen():

   print(ser.name + ' is open...')

Le moment est venu pour le plat de résistance du programme. Nous commençons une boucle « éternelle », envoyant une demande d'entrée d'une commande ou d'« exit » pour quitter, puis l'attente de la saisie par l'utilisateur. Ceci fonctionne parfaitement pour nos besoins, car l'Arduino attend aussi une commande. Cela nous permet aussi de terminer le programme proprement.

while True:

  cmd = raw_input("Enter command or 'exit':")
  # for Python 2
  # cmd = input("Enter command or 'exit':")
      # for Python 3
  if cmd == 'exit':
      ser.close()
      exit()

Now that there is something in the cmd variable, we encode it to ascii, append a CRLF to it, and then write it to the serial port. We then use the ser.readlines() command to get the data from our Arduino. We actually have several options here to read from the serial port. If we had used ser.read(), we would have had to specify the number of bytes to be received. Since that can change depending on the command we send, that option isn’t really a good one without a lot of work. We also could have used the ser.readline() command, but that only reads up to the CRLF being sent in, so while good for the “T” or “H” command, the “A” command which sends two lines, would have some problems. The timeout value we set earlier is important, since the system would block until the CRLF is returned. else: ser.write(cmd.encode('ascii')+'\r\n') out = ser.readlines() for l in out: print l The source (short as it is) is available on pastebin at https://pastebin.com/tXWirGCX So, that’s it for this month. We’ve successfully created the Temp and Humidity sensor circuit and are now able to read its values with a remote Raspberry Pi using Python. We’ll see you next month.

Maintenant qu'il y a quelque chose dans la variable cmd, nous l'encodons en ascii, lui ajoutons CRLF et l'écrivons sur le port série. Ensuite, nous utilisons la commande ser.readlines() pour obtenir les données de l'Arduino. En réalité, nous avons ici plusieurs options pour lire le port série. Si nous avions utilisé ser.read(), nous aurions dû spécifier le nombre d'octets à recevoir. Comme ça peut changer suivant la commande que nous envoyons, cette option n est pas vraiment bonne sans beaucoup de travail. Nous aurions pu aussi utiliser la commande ser.readline(), mais elle ne lit que jusqu'à l'envoi d'un CRLF, ce qui est bien pour une commande « T » ou « H », mais, avec la commande « A » qui envoie deux lignes, il y aurait des problèmes. La valeur du timeout paramétrée précédemment est importante, car le système sera bloqué jusqu'à ce qu'un CRLF soit retourné.

  else:
      ser.write(cmd.encode('ascii')+'\r\n')
      out = ser.readlines()
      for l in out:
          print l

Le code source (court s'il en est) est disponible sur pastebin à https://pastebin.com/tXWirGCX

Voilà ! C'est tout pour ce mois-ci. Nous avons successivement créé le circuit du capteur de température et d'humidité et nous sommes maintenant capables de lire ses valeurs à distance avec un Raspberry Pi utilisant Python.

Au mois prochain.

issue122/python.txt · Dernière modification : 2017/07/16 14:10 de auntiee