Différences entre versions de « Rasp-Hack-Afficheur-LCD-Python »

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 125 : Ligne 125 :
 
lcd.blink(False)
 
lcd.blink(False)
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
La classe LCD expose d'autres fonctions (des ''méthodes'') que nous n'avons pas abordé ici. Cela ne veut pas dire qu'elle ne seraient pas utiles. N'hésitez pas à afficher l'aide contextuel de la classe LCD en utilisant la fonction d'aide {{fname|help()}} de python. (ignorez l'invite de commande >>> , elle n'est là que comme référence pour signalé que nous utilisons l'interpréteur Python):
  
 
{{traduction}}
 
{{traduction}}
 
Although not shown above, there are other functions you might find useful on the LCD class. To see details on all functions you can have Python print help text for the class by executing (ignore the >>> prompt, it's only shown for reference as the Python interpreter):
 
  
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">

Version du 6 février 2017 à 13:02

Pre-requis

Sur un Raspberry-Pi, vous aurez besoin d'installer le minimum logiciel pour pouvoir télécharger la bibliothèque Adafruit.

sudo apt-get update
sudo apt-get install build-essential python-dev python-smbus python-pip git
sudo pip install RPi.GPIO

Installation de la bibliothèque

Une fois les dépendances ci-dessus installées, vous pouvez installer le module LCD Alphanumerique en exécutant les commandes suivantes sur votre appareil:

cd ~
git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git
cd Adafruit_Python_CharLCD
sudo python setup.py install

Ces commandes vont dupliquer (cloner) les source de la bibliothèque depuis GitHub puis exécuter le script setup.py pour installer la bibliothèque dans python.

Avec un LCD standard

UNe fois la bibliothèque installée, vous trouverez quelques exemples de son utilisation dans le sous répertoire examples. Si vous utilisez un LCD à rétro-éclairage monochrome (ex: une seule couleur, comme pour notre LCD blanc / bleu) alors le script char_lcd.py permet de démontrer l'utilisation de base.

Vous pouvez utiliser directement cet exemple si vous utilisé un Pi avec le raccordement recommandées dans ce guide. Si vous avez utilisez un BeagleBone Black ou utilisé un autre raccordement alors ouvrez le fichier char_lcd.py dans votre éditeur de texte préféré (comme nano) puis commentez/dé-commentez les lignes nécessaire en début de fichier (les lignes correspondant à l'initialisation des broches).

Note: Si vous utiliser un BeagleBone Black raccordé avec le rétro-éclairage LCD raccordé sur une broche PWM matériel alors consultez le guide Lcd with raspberry-pi or beaglebone black et consultez la section concernant le contrôle PWM (hardware PWM).

Saisissez les commandes suivantes pour exécuter l'exemple:

cd examples
python char_lcd.py

Vous devriez voir le rétro-éclairage s'allumer et des messages affichés sur l'écran. L'exemple suivant montre ce qui est affiché sur un écran blanc/bleu 20x4 (4 lignes de 20 caractères).

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Pour montrer l'utilisation de la bibliothèque, nous vous proposons de parcourir l'exemple char_lcd.py ci-dessous.

import math
import time

import Adafruit_CharLCD as LCD

La première partie du script contient des commandes de chargement des modules que nous allons utiliser.

Plus particulièrement, le module Adafruit_CharLCD est importé sous le nom LCD. Vous verrez plus tard, dans le script, comment les classes du module LCD sont utilisées pour interagit avec l'afficheur.

La prochaine partie du script défini la correspondance entre les broches GPIO et leur utilisation/branchement sur l'afficheur LCD. Vous pouvez constater que la configuration Pi est active par défaut et que la configuration pour BeagleBone est désactivée (en commentaire).

Vous pouvez utiliser n'importe quelle broche digitale GPIO dans la configuration.

# Configuration des broches du Raspberry Pi :
lcd_rs        = 27  # doit être changé à 21 pour les anciennes versions de Pi.
lcd_en        = 22
lcd_d4        = 25
lcd_d5        = 24
lcd_d6        = 23
lcd_d7        = 18
lcd_backlight = 4

# Configuration pour BeagleBone Black:
# lcd_rs        = 'P8_8'
# lcd_en        = 'P8_10'
# lcd_d4        = 'P8_18'
# lcd_d5        = 'P8_16'
# lcd_d6        = 'P8_14'
# lcd_d7        = 'P8_12'
# lcd_backlight = 'P8_7'

Cette section du script configure la taille du LCD (en caractères). Par défaut, nous convenons qu'il y a 2 lignes (rows) de 16 caractères (16 columns [colonne]) chacune.

Il est cependant d'ajuster la configuration à 20x4 ou toute autre taille supportée par le contrôleur HD44780.

# -- Definition de la taille du LCD --
# Ecran LCD de 16x2 
# Definir le nbre de colonne du LCD (column) = nbre de carateres par lignes.
lcd_columns = 16
# Definir le nombre de ligne du LCD (row)
lcd_rows    = 2

# Dimension alternative pour LCD 20x4 .
# lcd_columns = 20
# lcd_rows    = 4

Ensuite, nous allons créer une instance de de la classe Adafruit_CharLCD en lui précisant les différents paramètres de configuration (que nous avons précisé plus haut dans le script).

# Initialisation du LCD (avec definition du brochage)
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, 
                           lcd_columns, lcd_rows, lcd_backlight)

Les lignes suivantes démontrent l'utilisation de la classe d'affichage LCD. La fonction message peut être utilisé pour afficher une chaîne de caractère sur l'afficheur (supporte le retour à la ligne line breaks). La fonction clear efface le contenu de l'afficheur, la fonction show_cursor et blink affichent le curseur et le fait clignoter.

# Affiche un message en deux lignes
lcd.message('Hello\nworld!')

# Attends 5 secondes
time.sleep(5.0)

# Affiche le curseur.
lcd.clear()
lcd.show_cursor(True)
lcd.message('Show cursor')

time.sleep(5.0)

# Affiche un curseur clignotant.
lcd.clear()
lcd.blink(True)
lcd.message('Blink cursor')

time.sleep(5.0)

# Arrête le clignotement du curseur et masque le curseur.
lcd.show_cursor(False)
lcd.blink(False)

La classe LCD expose d'autres fonctions (des méthodes) que nous n'avons pas abordé ici. Cela ne veut pas dire qu'elle ne seraient pas utiles. N'hésitez pas à afficher l'aide contextuel de la classe LCD en utilisant la fonction d'aide help() de python. (ignorez l'invite de commande >>> , elle n'est là que comme référence pour signalé que nous utilisons l'interpréteur Python):

python
>>> import Adafruit_CharLCD as LCD
>>> help(LCD.Adafruit_CharLCD)

You should see a description of each function on the LCD class, including some functions not shown in the example:

autoscroll(autoscroll)

Autoscroll will 'right justify' text from the cursor if set True, otherwise it will 'left justify' the text.

enable_display(enable)

Enable or disable the display. Set enable to True to enable.

home()

Move the cursor back to its home (first line and first column).

set_backlight(backlight)

Enable or disable the backlight. If PWM is not enabled (default), a non-zero backlight value will turn on the backlight and a zero value will turn it off. If PWM is enabled, backlight can be any value from 0.0 to 1.0, with 1.0 being full intensity backlight.

set_cursor(col, row)

Move the cursor to an explicit column and row position.

Finally, the last portion of the char_lcd.py script:

# Demo scrolling message right/left.
lcd.clear()
message = 'Scroll'
lcd.message(message)
for i in range(lcd_columns-len(message)):
	time.sleep(0.5)
	lcd.move_right()
for i in range(lcd_columns-len(message)):
	time.sleep(0.5)
	lcd.move_left()

# Demo turning backlight off and on.
lcd.clear()
lcd.message('Flash backlight\nin 5 seconds...')
time.sleep(5.0)
# Turn backlight off.
lcd.set_backlight(0)
time.sleep(2.0)
# Change message.
lcd.clear()
lcd.message('Goodbye!')
# Turn backlight on.
lcd.set_backlight(1)

You can see how the move_right and move_left functions are used to scroll the display, and further down how the set_backlight function turns off and on the backlight.

That's all there is to using the Adafruit_CharLCD class!

Avec un LCD RGB

If you're using an RGB backlight LCD the char_lcd_rgb.py script will demonstrate the usage.

If you're using a Raspberry Pi and have wired it according to this guide, you can immediately run the script. However if you're using a BeagleBone Black or have changed the wiring, edit the script with a text editor and uncomment/change the lines at the top that define the LCD pins.

To execute the RGB backlight example run this command from inside the examples directory:

sudo python char_lcd_rgb.py

You should see the LCD turn on and display different backlight colors. For example:

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

If you open the file char_lcd_rgb.py in a text editor (such as nano) I'll describe the important differences between it and the previous char_lcd.py example below.

# Example Raspberry Pi configuration:
lcd_rs = 27  # Change this to pin 21 on older revision Raspberry Pi's
lcd_en = 22
lcd_d4 = 25
lcd_d5 = 24
lcd_d6 = 23
lcd_d7 = 18
lcd_red   = 4
lcd_green = 17
lcd_blue  = 7  # Pin 7 is CE1

# Example BeagleBone Black configuration:
# lcd_rs = 'P8_8'
# lcd_en = 'P8_10'
# lcd_d4 = 'P8_18'
# lcd_d5 = 'P8_16'
# lcd_d6 = 'P8_14'
# lcd_d7 = 'P8_12'
# lcd_red   = 'P8_7'
# lcd_green = 'P8_9'
# lcd_blue  = 'P8_11'

The first important difference is the configuration of LCD pins. Notice there are now explicit pins defined for the red, green, and blue backlight LEDs.

# Initialize the LCD using the pins 
lcd = LCD.Adafruit_RGBCharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                              lcd_columns, lcd_rows, lcd_red, lcd_green, lcd_blue)

The next line creates an instance of the Adafruit_RGBCharLCD class using the pin configuration defined earlier.

The Adafruit_RGBCharLCD class inherits from the Adafruit_CharLCD class so it has all the same functionality as demonstrated in the char_lcd.py example. In addition to the basic character LCD functionality the RGB character LCD class adds some functions to set the RGB color of the backlight.

# Show some basic colors.
lcd.set_color(1.0, 0.0, 0.0)
lcd.clear()
lcd.message('RED')
time.sleep(3.0)

lcd.set_color(0.0, 1.0, 0.0)
lcd.clear()
lcd.message('GREEN')
time.sleep(3.0)

lcd.set_color(0.0, 0.0, 1.0)
lcd.clear()
lcd.message('BLUE')
time.sleep(3.0)

lcd.set_color(1.0, 1.0, 0.0)
lcd.clear()
lcd.message('YELLOW')
time.sleep(3.0)

lcd.set_color(0.0, 1.0, 1.0)
lcd.clear()
lcd.message('CYAN')
time.sleep(3.0)

lcd.set_color(1.0, 0.0, 1.0)
lcd.clear()
lcd.message('MAGENTA')
time.sleep(3.0)

lcd.set_color(1.0, 1.0, 1.0)
lcd.clear()
lcd.message('WHITE')
time.sleep(3.0)

The code above demonstrates each basic color by calling the set_color function and passing in which red, green, and blue LEDs to enable. For example the first call to set_color(1.0, 0.0, 0.0) will turn on the red LED and turn off the green and blue LED so the backlight will have a red color.

Notice how later lines combine multiple LEDs to get different colors, like calling set_color(1.0, 0.0, 1.0) to combine red and blue LEDs for a magenta/violet color.

Avec un MCP23017 + LCD

Si vous avez suivi le plan de montage avec le MCP23017 alors c'est cette partie du tutoriel qui vous intéresse.

The char_lcd_mcp.py file in the library's examples folder demonstrates the usage of a character LCD (non-RGB version) with an MCP23017 IO extender. Run the script by executing this command inside the examples directory:

sudo python char_lcd_mcp.py

You should see a simple demo of the LCD displaying text, cursors, and scrolling just like the char_lcd.py demo described on the previous page.

If you open char_lcd_mcp.py in a text editor you can see how to use the character LCD library with the MCP chip. Below is an overview of the file:

import math
import time

import Adafruit_CharLCD as LCD
import Adafruit_GPIO.MCP230xx as MCP

First the required modules are imported. Notice the addition of the Adafruit_GPIO.MCP230xx module (imported under the name MCP). This MCP230xx class will be used to talk to the MCP chip and interface with the LCD.

# Define MCP pins connected to the LCD.
lcd_rs        = 0
lcd_en        = 1
lcd_d4        = 2
lcd_d5        = 3
lcd_d6        = 4
lcd_d7        = 5
lcd_backlight = 6
# Optionally if the backlight is not controllable then set:
# lcd_backlight = None

# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows    = 2

# Alternatively specify a 20x4 LCD.
# lcd_columns = 20
# lcd_rows    = 4

Next the LCD pins are defined in the script. Note that these pin numbers are the MCP chip GPIO pin numbers, and NOT Raspberry Pi/BeagleBone Black pin numbers!

# Initialize MCP23017 device using its default 0x20 I2C address.
gpio = MCP.MCP23017()

# Alternatively you can initialize the MCP device on another I2C address or bus.
# gpio = MCP.MCP23017(0x24, busnum=1)

Next an instance of the MCP23017 class is created. By default this class will use the I2C address 0x20 (default for MCP chips) and appropriate I2C bus for the running development board. However if you need to override the address or bus number you can see in the commented line how these are passed as parameters.

Also note if you're using an MCP23008 chip you can instead create an instance of the MCP23008 class. This class is exactly the same as the MCP23017 class, but only supports 8 GPIO pins.

Now the Adafruit_CharLCD class instance is created. The big difference with this line and previous examples is that the MCP23017 class (created with the name 'gpio') is passed in as the gpio parameter. By passing in an explicit gpio parameter, the char LCD class will use that GPIO class for talking to the LCD instead of the default development board GPIO pins.

The rest of the example code is exactly the same as the non-MCP character LCD example. You only need to change the setup and initialization of the character LCD class to use the MCP IO extender with an LCD!

L'exemple Horloge + IP

#!/usr/bin/python
     
from Adafruit_CharLCD import Adafruit_CharLCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
     
lcd = Adafruit_CharLCD()
     
cmd = "ip addr show eth0 | grep inet | awk '{print $2}' | cut -d/ -f1"
     
lcd.begin(16,1)
     
def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output
     
while 1:
    lcd.clear()
    ipaddr = run_cmd(cmd)
    lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n'))
    lcd.message('IP %s' % ( ipaddr ) )
    sleep(2)

Executer le code

Démarrer l'exemple IP + horloge

$ sudo ./Adafruit_CharLCD_IPclock_example.py 

Résultat

Ce que vous devriez voir:

Rasp-Hack-Afficheur-LCD-Python-01.jpg


Source: Character LCD with Raspberry Pi or BeagleBone Black écrit par Tony Dicola pour Adafruit Industries.

Traduit avec l'autorisation d'AdaFruit Industries - Translated with the permission from Adafruit Industries - www.adafruit.com

Toute référence, mention ou extrait de cette traduction doit être explicitement accompagné du texte suivant : «  Traduction par MCHobby (www.MCHobby.be) - Vente de kit et composants » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.

L'utilisation commercial de la traduction (texte) et/ou réalisation, même partielle, pourrait être soumis à redevance. Dans tous les cas de figures, vous devez également obtenir l'accord du(des) détenteur initial des droits. Celui de MC Hobby s'arrêtant au travail de traduction proprement dit.