Différences entre versions de « NeoPixel-UserGuide-Arduino »

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche
Ligne 30 : Ligne 30 :
 
{{ADFImage|NeoPixel-UserGuide-Arduino-Brancher-01.png|640px}}
 
{{ADFImage|NeoPixel-UserGuide-Arduino-Brancher-01.png|640px}}
  
{{ambox-stop|text=When connecting NeoPixels to any live power source or microcontroller, ALWAYS CONNECT GROUND (–) BEFORE ANYTHING ELSE. Conversely, disconnect ground last when separating.}}
+
{{ambox-stop|text=Lorsque vous connectez des NéoPixels sur n'importe quel source d'alimentation active ou microcontroleur, TOUJOURS CONNECTER LA MASSE/GND (–) AVANT QUOIQUE CE SOIT D'AUTRE. Et a l'inverse, toujours déconnecter la masse/GND en dernier.}}
  
  
{{ambox-stop|text=Adding a ~470 ohm resistor between your microcontroller's data pin and the data input on the NeoPixels can help prevent spikes on the data line that can damage your first pixel. Please add one between your micro and NeoPixels!}}
+
{{ambox-stop|text=Ajoutez une résistance de ~470 Ohms entre la broche de donnée du microcontrôleur et l'entrée de donnée NéoPixels ("''data input''") sur le ruban NéoPixel pour prévenir pointes de tensions sur la ligne de donnée qui pourrait endommager votre premier Pixel. Ajouter une résistance entre votre microcontroleur et les NéoPixels SVP!}}
  
  
{{ambox-stop|text= We also recommend adding a large capacitor (1000 µF, 6.3V or higher) across the + and terminals. This prevents the initial onrush of current from damaging the pixels. See the photo on the next page for an example.}}
+
{{ambox-stop|text=Nous recommandons également d'ajouter une grande capacité (1000 µF, 6.3V ou plus) entre les bornes + et –. Cela protège les NéoPixels des dommages du "torrent initial" de courant. Voyez les exemples/photographies sur la page suivante.}}
  
=== Can NeoPixels be powered directly from the Arduino’s 5V pin? ===
+
=== Est-il possible d'alimenter les NéoPixels directement depuis le +5v d'Arduino? ===
  
Sometimes. The Arduino can continuously supply only about 500 milliamps to the 5V pin. Each NeoPixel can draw up to 60 milliamps at full brightness. So yes, you can skip the separate DC supply and power directly off the Arduino as long as just a few pixels are used, or more if the colors and overall brightness are low. When in doubt, give the pixels a separate power supply.
+
Parfois. Le régulateur d'Arduino peut continuellement fournir 500 milliampères (environ) sur la broche 5V. Chaque NéoPixel peut consommer jusqu'à 60 milliampères (a pleine luminosité). Il est donc possible de se passer d'une alimentation séparée et d'alimente directement des NéoPixels depuis votre Arduino... mais seulement quelques NéoPixels ou si vous les utilisez en couleur et à faible luminosité. En cas de doute, optez pour une alimentation séparée.
  
 
== Code d'exemple simple: standtest ==
 
== Code d'exemple simple: standtest ==

Version du 25 février 2014 à 22:00


MCHobby investit du temps et de l'argent dans la réalisation de traduction et/ou documentation. C'est un travail long et fastidieux réalisé dans l'esprit Open-Source... donc gratuit et librement accessible.
SI vous aimez nos traductions et documentations ALORS aidez nous à en produire plus en achetant vos produits chez MCHobby.

Bibliothèque Arduino

Contrôler des NéoPixels à "partir de rien" est un sacré challenge. AdaFruit propose une bibliothèque/librairie permettant avant tout de prendre du plaisir et de se concentrer sur les points intéressants. La bibliothèque fonctionne avec la plupart des cartes Arduino et dérivés: Uno, Mega, Leonardo, Micro, Adafruit Flora, etc. — la plupart des plateformes à base de processeur Atmel AVR 8-bits entre 8 et 16 MHz — elle fonctionne également avec Arduino Due et toute une variété de carte PJRC Teensy.

Etant donné que la bibliothèque utilise le langage assembleur spécifique au processeur, la librairie ne fonctionne pas sur Netduino, ChipKIT ou autres cartes avancées “type-Arduino”. D'autres contributeurs peuvent avoir écrit du code et bibliothèques pour de telles cartes, mais AdaFruit ne saura pas fournir de support technique en cas de bug ou problème sur de telle plateforme.

Vous pouvez installer la bibliothèque comme suit:

  • Naviguez sur la page de la bibliothèque Adafruit_NeoPixel sur Github.com.
  • Sélectionnez le bouton “Download ZIP” (téléchargement) ou cliquer simplement sur ce liens pour un téléchargement direct.
  • Décompressez l'archive ZIP après le téléchargement de celui-ci.
  • Il devrait en résulter un répertoire contenant les fichiers “Adafruit_NeoPixel.cpp”, “Adafruit_NeoPixel.h” et un sous-répertoire “examples” (contenant les exemples). Sous Windows, il arrive parfois que vous obteniez un répertoire intermédiaire et vous aurez besoin de déplacer les fichier.
  • Renommez le répertoire (celui contenant les fichiers .cpp et .h) en “Adafruit_NeoPixel” (avec l'Underscore et tout le reste), et la placer à côté des autres bibliothèques/librairies Arduino (généralement dans votre répertoire <répertoire_racine>/Documents/Arduino/Libraries.
  • Redémarrez votre environnement Arduino IDE (s'il est en cours de fonctionnement).

Vous trouverez ici un tutoriel contenant des informations complémentaire pour installer une bibliothèque/librairie Arduino.

Branchement de base

Pour débuter, considérons que nous avons un microcontroleur Arduino connecté sur le port USB d'un ordinateur. Nous nous attarderons plus tard sur l'alimentation des NéoPixels, mais pour le moment nous allons utiliser une alimentation séparée de 5V continu (ou un accu lithium-ion 3.7V pour un projet fringuable Flora).

Identifiez le bout correspondant à l'entrée ("input") de votre ruban NeoPixel, Pixel(s) ou autre périphérique NéoPixel. Sur certains modèles vous trouverez une partie portant l'indication "DIN" ou "DI" pour data input (entrée de donnée). D'autre modèles porterons une petite flèche indiquant la directions de déplacement des information. L'entrée de donnée du NeoPixel ("data input") peut être connecté sur n'importe quel broche digitale de votre Arduino mais pour ce code d'exemple nous allons la brancher sur la sortie digital 6 (celle utilisée par défaut). Le shield NéoPixel utilise par ailleurs la broche digital 6.

Si vous utilisez un Flora avec un accu lithium-ion: connectez l'entrée +5V du ruban NéoPixel sur la pastille VBATT de Flora, le GND du ruban sur l'une des pastilles GND de Flora et le DIN du ruban sur la pastille D6 de Flora.

Pour les autres cartes Arduino disposant d'une aliment +5V DC séparée pour les NéoPixels: connectez l'entrée +5V du ruban NéoPixel sur la borne + (positive) de l'alimentation (ne pas la connecter sur l'alimentation de votre Arduino), la connexion DIN sur la broche digital 6 de votre Arduino et le "–"/Négatif/GND du ruban NéoPixel sur les deux masses (sur la masse/GND d'Arduino et sur la masse/GND de l'alimentation séparée).

Les rubans NéoPixels 144 pixels/m sont très dense, il n'y a pas beaucoup de place pour y indiquer d'autres libellés que "–", "+" et une flèche indiquant la direction des données. L'entrée/sortie de données ne dipose pas d'une pastille avec un libellé.

NeoPixel-UserGuide-Arduino-Brancher-01.png
Crédit: AdaFruit Industries www.adafruit.com



Est-il possible d'alimenter les NéoPixels directement depuis le +5v d'Arduino?

Parfois. Le régulateur d'Arduino peut continuellement fournir 500 milliampères (environ) sur la broche 5V. Chaque NéoPixel peut consommer jusqu'à 60 milliampères (a pleine luminosité). Il est donc possible de se passer d'une alimentation séparée et d'alimente directement des NéoPixels depuis votre Arduino... mais seulement quelques NéoPixels ou si vous les utilisez en couleur et à faible luminosité. En cas de doute, optez pour une alimentation séparée.

Code d'exemple simple: standtest

Launch the Arduino IDE. From the File menu, select Fichier > Exemple > Adafruit_NeoPixel > strandtest

(If the Adafruit_NeoPixel rollover menu is not present, the library has not been correctly installed, or the IDE needs to be restarted after installation. Check the installation steps above to confirm it’s properly named and located.)

Select your board type and serial port from the Tools menu, and try uploading to the board. If the NeoPixels are connected and powered, you should see a little light show.

Il ne se passe rien

Check your connections. The most common mistake is connecting to the output end of a strip rather than the input.

Inspectons le code

Let’s look at the code now...

All NeoPixel sketches begin by including the header file:

#include <Adafruit_NeoPixel.h>

The block of code that follows is mostly descriptive comments. Only the last line is really doing any work:

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);

The first line assigns a number to the symbol “PIN” for later reference. It doesn’t need to be done this way, but makes it easier to change the pin where the NeoPixels are connected without digging deeper into the code.

The last line declares a NeoPixel object. We’ll refer to this by name later to control the strip of pixels. There are three parameters or arguments in parenthesis:

  1. The number of sequential NeoPixels in the strip. In the example this is set to 60, equal to 1 meter of medium-density strip. Change this to match the actual number you’re using.
  2. The pin number to which the NeoPixel strip (or other device) is connected. Normally this would be a number, but we previously declared the symbol PIN to refer to it by name here.
  3. A value indicating the type of NeoPixels that are connected. In most cases you can leave this off and pass just two arguments; the example code is just being extra descriptive. If you have a supply of classic “V1” Flora pixels, those require NEO_KHZ400 + NEO_RGB to be passed here.

Then, in the setup() function, call begin() to prepare the data pin for NeoPixel output:

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

The second line, strip.show(), isn’t absolutely necessary, it’s just there to be thorough. That function pushes data out to the pixels…since no colors have been set yet, this initializes all the NeoPixels to an initial “off” state in case some were left lit by a prior program. In the strandtest example, loop() doesn’t set any pixel colors on its own — it calls other functions that create animated effects. So let’s ignore it for now and look ahead, inside the individual functions, to see how the strip is controlled.

There are two ways to set the color of a pixel. The first is:

strip.setPixelColor(n, red, green, blue);

The first argument — n in this example — is the pixel number along the strip, starting from 0 closest to the Arduino. If you have a strip of 30 pixels, they’re numbered 0 through 29. It’s a computer thing. You’ll see various places in the code using a for loop, passing the loop counter variable as the pixel number to this function, to set the values of multiple pixels.

The next three arguments are the pixel color, expressed as red, green and blue brightness levels, where 0 is dimmest (off) and 255 is maximum brightness.

To set the 12th pixel (#11, counting from 0) to magenta (red + blue), you could write:

strip.setPixelColor(11, 255, 0, 255);

An alternate syntax has just two arguments:

strip.setPixelColor(n, color);

Here, color is a 32-bit type that merges the red, green and blue values into a single number. This is sometimes easier or faster for some (but not all) programs to work with; you’ll see the strandtest code uses both syntaxes in different places.

You can also convert separate red, green and blue values into a single 32-bit type for later use:

uint32_t magenta = strip.Color(255, 0, 255);

Then later you can just pass “magenta” as an argument to setPixelColor rather than the separate red, green and blue numbers every time.

setPixelColor() does not have an immediate effect on the LEDs. To “push” the color data to the strip, call show():

strip.show();

This updates the whole strip at once, and despite the extra step is actually a good thing. If every call to setPixelColor() had an immediate effect, animation would appear jumpy rather than buttery smooth. You can query the color of a previously-set pixel using getPixelColor():

uint32_t color = strip.getPixelColor(11);

This returns a 32-bit merged color value.

The number of pixels in a previously-declared strip can be queried using numPixels():

uint16_t n = strip.numPixels();

The overall brightness of all the LEDs can be adjusted using setBrightness(). This takes a single argument, a number in the range 0 (off) to 255 (max brightness). For example, to set a strip to 1/4 brightness:

strip.setBrightness(64);

Just like setPixel(), this does not have an immediate effect. You need to follow this with a call to show().

You can’t move from a lower brightness to a higher setting without some loss in fidelity. Certain animation effects are better served by leaving the brightness at max and calling setPixel() repeatedly to fill the strip.

I’m calling setPixel() but nothing’s happening!

There are two main culprits for this:

  1. forgetting to call strip.begin() in setup().
  2. forgetting to call strip.show() after setting pixel colors.

Another (less common) possibility is running out of RAM — see the last section below. If the program sort of works but has unpredictable results, consider that.

Can I have multiple NeoPixel objects on different pins?

Certainly! Each requires its own declaration with a unique name:

Adafruit_NeoPixel strip_a = Adafruit_NeoPixel(16, 5);
Adafruit_NeoPixel strip_b = Adafruit_NeoPixel(16, 6);

The above declares two distinct NeoPixel objects, one each on pins 5 and 6, each containing 16 pixels and using the implied default type (NEO_KHZ800 + NEO_GRB).

Can I connect multiple NeoPixel strips to the same Arduino pin?

In many cases, yes. All the strips will then show exactly the same thing. This only works up to a point though…four strips on a single pin is a good and reliable number. If you need more than that, individual NeoPixels can be used as buffers to “fan out” to more strips: connect one Arduino pin to the inputs of four separate NeoPixels, then connect each pixels’ output to the inputs of four strips (or fewer, if you don’t need quite that many). If the strips are 10 pixels long, declare the NeoPixel object as having 11 pixels. The extra “buffer” pixels will be at position #0 — just leave them turned off — and the strips then run from positions 1 through 10.

Les pixels sont gourmand en RAM

Each NeoPixel requires about 3 bytes of RAM. This doesn’t sound like very much, but when you start using dozens or even hundreds of pixels, and consider that the mainstream Arduino Uno only has 2 kilobytes of RAM (often much less after other libraries stake their claim), this can be a real problem!

For using really large numbers of LEDs, you might need to step up to a more potent board like the Arduino Mega or Due. But if you’re close and need just a little extra space, you can sometimes tweak your code to be more RAM-efficient. This tutorial has some pointers on memory usage.


Source: NeoPixel UserGuide créé par Phillip Burgess pour AdaFruit Industries. Crédit AdaFruit Industries

Traduit par Meurisse D. pour MCHobby.be

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.