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

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 18 : Ligne 18 :
 
Ces commandes vont dupliquer (cloner) les [https://github.com/adafruit/Adafruit_Python_CharLCD source de la bibliothèque depuis GitHub] puis exécuter le script {{fname|setup.py}} pour installer la bibliothèque dans python.
 
Ces commandes vont dupliquer (cloner) les [https://github.com/adafruit/Adafruit_Python_CharLCD source de la bibliothèque depuis GitHub] puis exécuter le script {{fname|setup.py}} pour installer la bibliothèque dans python.
  
== Tester ==
+
== Utiliser avec un LCD standard ==
 +
Once the library is installed you can find a few examples of its usage in the '''examples''' subdirectory. If you're using a monochrome backlight LCD (i.e. single color, like a white on blue LCD) the '''char_lcd.py''' script will demonstrate the basic usage.
  
Vous pouvez tester le câblage réalisé lors des étapes précédentes en exécutant le code python de Adafruit_CharLCD.py . Il ne dispose que d'un peu de code... et si tout est raccordé correctement, vous verrez apparaître un message de test.
+
If you're using a Raspberry Pi and have wired it according to this guide, you can immediately run the example. However if you're using a BeagleBone Black or changed the wiring, first open '''char_lcd.py''' in a text editor (like nano) and uncomment/comment the lines towards the top that set the LCD pins.
  
Si vous utilisez un '''Raspberry Pi Version 2''',alors la broche '''#21''' de la carte à été remplacée avec la broche '''#27'''. Il faudra donc modifier Adafruit_CharLCD.py et changer la ligne:
+
'''Note: If you're using a BeagleBone Black wired for hardware PWM of the backlight, skip down the page to the section on using hardware PWM.'''
  
def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, '''21''', 22], GPIO = None):
+
To run the example execute:
  
par
+
<nowiki>cd examples
 +
python char_lcd.py</nowiki>
  
def __init__(self, pin_rs=25, pin_e=24, pins_db=[23, 17, '''27''', 22], GPIO = None):
+
You should see the LCD backlight turn on and messages printed to the display. For example below is what you will see with a 20x4 blue backlight LCD:
  
 +
{{ADFImage|Rasp-Hack-Afficheur-LCD-Python-a01.jpg}}
  
vous pouvez utiliser la commande '''nano Adafruit_CharLCD.py''' pour modifier le fichier
+
To demonstrate the usage of the library I'll walk through the source code of the char_lcd.py example below.
  
  <nowiki>chmod +x Adafruit_CharLCD.py
+
<syntaxhighlight lang="python">
sudo ./Adafruit_CharLCD.py</nowiki>
+
import math
 +
import time
 +
 
 +
import Adafruit_CharLCD as LCD
 +
</syntaxhighlight>
 +
 
 +
The first part of the script are commands to import modules that will be used. In particular the Adafruit_CharLCD module is imported under the name LCD. Later in the script you can see how classes from the char LCD module are used to interact with the LCD.
 +
 
 +
<syntaxhighlight lang="python">
 +
# Raspberry Pi pin configuration:
 +
lcd_rs        = 27 # Note this might need to be changed to 21 for older revision Pi's.
 +
lcd_en        = 22
 +
lcd_d4        = 25
 +
lcd_d5        = 24
 +
lcd_d6        = 23
 +
lcd_d7        = 18
 +
lcd_backlight = 4
 +
 
 +
# 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_backlight = 'P8_7'
 +
</syntaxhighlight>
 +
 
 +
The next part of the script configures which pins are connected to the LCD. You can see the Raspberry Pi configuration is uncommented by default, and below it the BeagleBone Black configuration is commented. You can use any digital GPIO pins in the configuration.
 +
 
 +
<syntaxhighlight lang="python">
 +
# 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
 +
</syntaxhighlight>
 +
 
 +
This section of the script configures the size of the LCD. By default the code assumes a 16 column, 2 row LCD however you can adjust the configuration to a 20x4 or other size display supported by the HD44780.
 +
 
 +
<syntaxhighlight lang="python">
 +
# Initialize the LCD using the pins above.
 +
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
 +
                          lcd_columns, lcd_rows, lcd_backlight)
 +
</syntaxhighlight>
 +
 
 +
Next an instance of the '''Adafruit_CharLCD''' class is created based on the configuration specified earlier in the script.  
 +
 
 +
<syntaxhighlight lang="python">
 +
# Print a two line message
 +
lcd.message('Hello\nworld!')
 +
 
 +
# Wait 5 seconds
 +
time.sleep(5.0)
 +
 
 +
# Demo showing the cursor.
 +
lcd.clear()
 +
lcd.show_cursor(True)
 +
lcd.message('Show cursor')
 +
 
 +
time.sleep(5.0)
 +
 
 +
# Demo showing the blinking cursor.
 +
lcd.clear()
 +
lcd.blink(True)
 +
lcd.message('Blink cursor')
 +
 
 +
time.sleep(5.0)
 +
 
 +
# Stop blinking and showing cursor.
 +
lcd.show_cursor(False)
 +
lcd.blink(False)
 +
</syntaxhighlight>
 +
 
 +
The next lines demonstrate basic usage of the LCD display class. The {{fname|message}} function can be used to write a string of text to the display (including support for line breaks). The {{fname|clear}} function clears the display, and the {{fname|show_cursor}} and {{fname|blink}} functions specify if the cursor is shown and should blink.
 +
 
 +
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">
 +
python
 +
>>> import Adafruit_CharLCD as LCD
 +
>>> help(LCD.Adafruit_CharLCD)
 +
</syntaxhighlight>
 +
 
 +
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:
 +
 
 +
<syntaxhighlight lang="python">
 +
# 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)
 +
</syntaxhighlight>
 +
 
 +
You can see how the {{fname|move_right}} and {{fname|move_left}} functions are used to scroll the display, and further down how the {{fname|set_backlight}} function turns off and on the backlight.
 +
 
 +
That's all there is to using the '''Adafruit_CharLCD''' class!
  
 
== L'exemple Horloge + IP ==
 
== L'exemple Horloge + IP ==

Version du 31 décembre 2016 à 10:22

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.

Utiliser avec un LCD standard

Once the library is installed you can find a few examples of its usage in the examples subdirectory. If you're using a monochrome backlight LCD (i.e. single color, like a white on blue LCD) the char_lcd.py script will demonstrate the basic usage.

If you're using a Raspberry Pi and have wired it according to this guide, you can immediately run the example. However if you're using a BeagleBone Black or changed the wiring, first open char_lcd.py in a text editor (like nano) and uncomment/comment the lines towards the top that set the LCD pins.

Note: If you're using a BeagleBone Black wired for hardware PWM of the backlight, skip down the page to the section on using hardware PWM.

To run the example execute:

cd examples
python char_lcd.py

You should see the LCD backlight turn on and messages printed to the display. For example below is what you will see with a 20x4 blue backlight LCD:

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

To demonstrate the usage of the library I'll walk through the source code of the char_lcd.py example below.

import math
import time

import Adafruit_CharLCD as LCD

The first part of the script are commands to import modules that will be used. In particular the Adafruit_CharLCD module is imported under the name LCD. Later in the script you can see how classes from the char LCD module are used to interact with the LCD.

# Raspberry Pi pin configuration:
lcd_rs        = 27  # Note this might need to be changed to 21 for older revision Pi's.
lcd_en        = 22
lcd_d4        = 25
lcd_d5        = 24
lcd_d6        = 23
lcd_d7        = 18
lcd_backlight = 4

# 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_backlight = 'P8_7'

The next part of the script configures which pins are connected to the LCD. You can see the Raspberry Pi configuration is uncommented by default, and below it the BeagleBone Black configuration is commented. You can use any digital GPIO pins in the configuration.

# 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

This section of the script configures the size of the LCD. By default the code assumes a 16 column, 2 row LCD however you can adjust the configuration to a 20x4 or other size display supported by the HD44780.

# Initialize the LCD using the pins above.
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, 
                           lcd_columns, lcd_rows, lcd_backlight)

Next an instance of the Adafruit_CharLCD class is created based on the configuration specified earlier in the script.

# Print a two line message
lcd.message('Hello\nworld!')

# Wait 5 seconds
time.sleep(5.0)

# Demo showing the cursor.
lcd.clear()
lcd.show_cursor(True)
lcd.message('Show cursor')

time.sleep(5.0)

# Demo showing the blinking cursor.
lcd.clear()
lcd.blink(True)
lcd.message('Blink cursor')

time.sleep(5.0)

# Stop blinking and showing cursor.
lcd.show_cursor(False)
lcd.blink(False)

The next lines demonstrate basic usage of the LCD display class. The message function can be used to write a string of text to the display (including support for line breaks). The clear function clears the display, and the show_cursor and blink functions specify if the cursor is shown and should blink.

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):

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!

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.