Outils pour utilisateurs

Outils du site


issue115:python

Table des matières

1

Welcome back for another entry into what I lovingly call ‘Greg’s Python Folly’. As promised, we will be working on interfacing a stepper motor to the Raspberry Pi. You will need your Raspberry Pi, a hobby stepper motor, a 4 x AA size battery pack, the L293D driver chip we used previously, a breadboard, and some jumpers. While I was doing research for this particular project, I stumbled across a tutorial at tutorials-raspberrypi.de. I was so impressed by the information at this website, I am using the majority of their information and code in this article. The website is: http://tutorials-raspberrypi.com/how-to-control-a-stepper-motor-with-raspberry-pi-and-l293d-uln2003a/. If you get confused by my explanations, you can always drop by and maybe get some clarifications. The motor I chose is a Radio Shack mini stepper motor. Basically it is a 28BJY-48 low-voltage stepper. Before you try to interface any stepper motor, please research the data sheet for as much information as you can get. In this case, the data sheet is located at: http://www.tutorials-raspberrypi.de/wp-content/uploads/2014/08/Stepper-Motor-28BJY-48-Datasheet.pdf Now, let’s examine stepper motors in general, then we’ll expand that information to the 28BJY specifically and work on interfacing it to the Pi through our L293D driver chip.

Bienvenue de nouveau dans ce que j'appelle affectueusement « La folie de Greg pour Python ». Comme promis, nous allons travailler à la connexion d'un moteur pas-à-pas à un Raspberry Pi. Vous aurez besoin de votre Raspberry Pi, un moteur pas-à-pas de loisirs, 4 piles AA et le bloc-piles, la puce de commande L293D que nous avons utilisée précédemment, une plaque d'essais, et quelques cavaliers.

Alors que je faisais des recherches pour ce projet-ci, je suis tombé sur un guide sur tutorials-raspberrypi.de. J'ai été tellement impressionné par les informations de ce site web que j'utilise une majorité de leur renseignements et de leur code dans cet article. Le site Web : http://tutorials-raspberrypi.com/how-to-control-a-stepper-motor-with-raspberry-pi-and-l293d-uln2003a/. Si vous êtes perdu dans mes explications, vous pouvez toujours y aller et obtenir quelques éclaircissements.

Le moteur choisi est un mini-moteur pas-à-pas Radio Shack. En fait, c'est un moteur basse tension 28BJY-48. Avant d'essayer de connecter un moteur pas-à-pas, merci de vous procurer sa documentation et autant d'informations que possible. Pour mon cas, la documentation est ici : http://www.tutorials-raspberrypi.de/wp-content/uploads/2014/08/Stepper-Motor-28BJY-48-Datasheet.pdf

Bon, regardons d'abord les moteurs pas-à-pas en général et, ensuite, nous préciserons cette information pour le 28BJY et nous le connecterons au Pi via notre puce de commande L293D.

Stepper Motors Stepper motors are used in robotics and in CNC type machines where you want the ability to move an item to a specific location easily. There are two basic types of stepper motors, one called Unipolar and one called Bipolar. The difference will become obvious as we go through this tutorial. The 28BJY is a Bipolar motor and also has a gearing system. In both models, there are multiple electromagnetic coils that are turned on and off in a sequence to make the motor turn. Each time we apply power to one of the coils, the motor rotates a small amount (if powered in the correct sequence for the motor), called a step, hence the name stepper motor. Unipolar Motors Unipolar motors have coils that are powered in only one direction, hence the UNI in Unipolar. The rotor of the motor is controlled by powering the various electromagnetic coils on and off in a specific sequence for a certain amount of time. In a simplified version of this model, let’s look at the following diagram… Turning on each coil one at a time will cause the magnet in the rotor to turn toward the proper coil. Using a clock face as a guide, turning on the coils in the sequence of 12 o’clock, 3 o’clock, 6 o’clock, 9 o’clock and then again at 12 o’clock will cause the rotor to turn clockwise one full rotation. This requires 4 “steps” to make one rotation. This is called the Unipolar wave. If we go a bit further, we could make a more granular movement by alternating the coils from a single coil turned on and then turning on the next coil as well, which makes the rotor turn in an eighth turn when both coils are turned on. The sequence would then be: 12, 12 and 3, 3, 3 and 6, 6, 6 and 9, 9, 9 and 12, and then finally 12 alone again. This then is 8 steps per rotation which is called half stepping. To make the motor reverse (counter-clockwise), we simply reverse the sequence. This is a VERY simple representation, and many stepper motors have a resolution that can be as high as 200 steps per revolution.

Les moteurs pas-à-pas

Les moteurs pas-à-pas sont utilisés en robotique et dans les machines à commande numérique lorsque vous voulez pouvoir facilement bouger un objet vers un endroit précis. Il y a deux types de base de moteurs pas-à-pas, un appelé unipolaire et l'autre bipolaire. Leur différence apparaîtra plus loin dans ce tutoriel. Le 28BJY est bipolaire et a aussi une boîte de vitesses.

Dans les deux cas, il y a un certain nombre de bobines électromagnétiques qui sont allumées et coupées successivement pour faire tourner le moteur. Chaque fois que nous alimentons l'une des bobines, le moteur tourne un petit peu (si alimenté dans la séquence correcte pour le moteur). On appelle cela un pas, d'où le nom de moteur pas-à-pas.

Moteurs Unipolaires

Les moteurs unipolaires possèdent des bobines alimentées dans une seule direction : le UNI de unipolaire. Le rotor du moteur est contrôlé en alimentant, puis coupant, les différentes bobines dans une séquence spécifique pendant un certain temps. Voici un diagramme simplifié de ce modèle :

Alimenter chaque bobine, une à la fois, va faire que l'aimant du rotor va se tourner vers la bonne bobine. Si on se guide sur un cadran d'horloge, alimenter les bobines successivement à 12 h, 3 h, 6 h, 9 h, puis de nouveau 12 h va faire tourner le rotor d'un tour complet dans le sens des aiguilles d'une montre. On a donc besoin de quatre « pas » pour faire un tour. On appelle cela l'onde unipolaire. En allant plus loin, nous pourrions avoir un mouvement plus granulaire en activant alternativement les bobines, mais en activant aussi la bobine d'après, ce qui fait faire un huitième de tour au rotor quand les deux bobines sont alimentées. La suite serait alors : 12, 12 et 3, 3, 3 et 6, 6, 6 et 9, 9, 9 et 12, et finalement 12 de nouveau seule. On a ainsi 8 pas par tour, ce que l'on appelle le fonctionnement en demi-pas. Pour faire aller le moteur en marche arrière (sens inverse des aiguilles), nous inversons simplement la séquence. Ceci est une représentation TRÈS simple, et beaucoup de moteurs pas-à-pas ont une résolution qui peut aller jusqu'à 200 pas par tour.

2

Bipolar Motors The 28BJY, as I stated earlier, is a Bipolar motor. In this case, the coils can have their current reversed and two coils are powered at any time. This creates a situation where the switching is more complex, but the amount of turn force (power) of the rotor is increased. A simple block diagram of the 28BJY is shown below. The numbers shown with the colors of the wires are for the 28BJY and yours may be different. The wire connector (if there is one) might differ from unit to unit. You can use an ohmmeter to verify the coils. The Wiring A couple of words of warning on this before we start. First, do all of your wiring BEFORE you power on the Raspberry Pi. We are working with an external power source, so you want to make sure that you don’t short any wires or apply the battery power to the wrong pin. Second, BE SURE of your wiring before you power on your RPi. If you get the wiring confused, at best your project will not work and the motor will just sit there and buzz. When you look at the fritzing drawing, it looks fairly simple (and it is). I made sure that the wiring from the RPi to the driver chip were the same color as the intended segment of the motor. We will be using only 4 of the 5 motor wires. The red one (if yours has a red one) is not connected for this project. Since the central component in this project is the L293D driver chip, here is a quick breakdown to try to make things easier for you…

Moteurs bipolaires

Le 28BJY, comme dit précédemment, est un moteur bipolaire. Dans ce cas, les bobines peuvent voir leur courant inversé et deux bobines sont alimentées en même temps. Cela crée une situation où la commutation est plus complexe, mais la quantité de force de rotation (puissance) du rotor est augmentée. Voir ci-dessous un diagramme bloc simple du 28BJY.

Les numéros montrés avec les couleurs des fils sont pour le 28BJY et les vôtres peuvent être différents. Le connecteur des fils (s'il y en a un) peut être différent d'une unité à l'autre. Vous pouvez utiliser un ohmmètre pour tester les bobines.

Le câblage

Un léger avertissement avant de commencer.

Tout d'abord, faites l'ensemble de votre câblage AVANT d'allumer le Raspberry Pi. Nous travaillons avec une source externe de puissance, donc faites attention de ne pas mettre en court-circuit certains fils ou d'alimenter la mauvaise broche.

Deuxièmement, VÉRIFIEZ votre câblage avant d'allumer votre RPi. Si vous vous êtes emmêlé, au mieux votre projet ne fonctionnera pas, et le moteur ne fera rien en buzzant.

Quand vous regardez le plan, ça semble plutôt simple (et ça l'est). Je me suis assuré que le câblage entre le Rpi et la puce de commande était de la même couleur que le segment correspondant du moteur. Nous n'allons utiliser que 4 fils sur les 5 du moteur. Le rouge (si le vôtre a un fil rouge) n'est pas connecté pour ce projet.

Puisque le composant principal dans ce projet est la puce de commande L293D, voici un petit plan pour essayer de vous faciliter la tâche :

L293D Pin 1 → Pin 9 Pin 2 → Pi GPIO 6 Pin 3 → Motor Pink Pin 4 → Breadboard Negative Rail Pin 5 → No Connect Pin 6 → Motor Orange Pin 7 → Pi GPIO 5 Pin 8 → Breadboard Positive Rail Pin 9 → Pin 1 Pin 10 → PI GPIO 23 Pin 11 → Motor Yellow Pin 12 → No Connect Pin 13 → No Connect Pin 14 → Motor Blue Pin 15 → Pi GPio 24 Pin 16 → Pi +5VDC If you follow this, you should have no problems with the wiring. The Code As always, I will discuss the code in blocks. So let’s get started. import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) coil_A_1_pin = 6 # pink coil_A_2_pin = 5 # orange coil_B_1_pin = 23 # blue coil_B_2_pin = 24 # yellow

L293D Pin 1 → Pin 9 Pin 2 → Pi GPIO 6 Pin 3 → Moteur rose Pin 4 → Rail négatif de la plaque Pin 5 → Non connecté Pin 6 → Moteur orange Pin 7 → Pi GPIO 5 Pin 8 → Rail positif de la plaque Pin 9 → Pin 1 Pin 10 → PI GPIO 23 Pin 11 → Moteur jaune Pin 12 → Non connecté Pin 13 → Non connecté Pin 14 → Moteur bleu Pin 15 → Pi GPio 24 Pin 16 → Pi +5VDC

Si vous respectez cela, vous ne devrez pas avoir de problème avec les fils.

Le code

Comme toujours, je vais parler du code par blocs. Allons-y.

import RPi.GPIO as GPIO import time

GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) coil_A_1_pin = 6 # rose coil_A_2_pin = 5 # orange coil_B_1_pin = 23 # bleu coil_B_2_pin = 24 # jaune

3

Here we are simply defining the imports, setting the GPIO mode, and setting the warnings to False so we don’t get any nagging notices about already initialized pins. We also define which GPIO pins control the motor coils through the driver chip. # adjust if different StepCount = 8 Seq = range(0, StepCount) Seq[0] = [0,1,0,0] Seq[1] = [0,1,0,1] Seq[2] = [0,0,0,1] Seq[3] = [1,0,0,1] Seq[4] = [1,0,0,0] Seq[5] = [1,0,1,0] Seq[6] = [0,0,1,0] Seq[7] = [0,1,1,0] Now this is the key to making our project work. This motor wants to have 8 steps (internal) per revolution of the motor (per the data sheet). We also define the sequence of which coil(s) are energized per step as a series of lists. Each sequence array explains which coil(s) is energized at any given time. GPIO.setup(coil_A_1_pin, GPIO.OUT) GPIO.setup(coil_A_2_pin, GPIO.OUT) GPIO.setup(coil_B_1_pin, GPIO.OUT) GPIO.setup(coil_B_2_pin, GPIO.OUT) Here we are going through the setup steps, defining each of our pins used as outputs. def setStep(w1, w2, w3, w4): GPIO.output(coil_A_1_pin, w1) GPIO.output(coil_A_2_pin, w2) GPIO.output(coil_B_1_pin, w3) GPIO.output(coil_B_2_pin, w4)

Ici, nous ne définissons que les imports, nous paramétrons le mode GPIO (entrée/sortie universelle) et nous désactivons les alertes pour ne pas être ennuyé par des messages lorsque les broches sont déjà initialisées. Nous définissons aussi quelle broche universelle contrôle les bobines du moteur à travers la puce de commande.

# adaptez si c'est différent StepCount = 8 Seq = range(0, StepCount) Seq[0] = [0,1,0,0] Seq[1] = [0,1,0,1] Seq[2] = [0,0,0,1] Seq[3] = [1,0,0,1] Seq[4] = [1,0,0,0] Seq[5] = [1,0,1,0] Seq[6] = [0,0,1,0] Seq[7] = [0,1,1,0]

Et voici la clé permettant de faire fonctionner notre projet. Ce moteur veut 8 pas (internes) par tour de moteur (selon la doc.). Nous définissons également la séquence des bobines qui seront alimentées à chaque pas, sous la forme d'une série de listes. Chaque liste indique quelle bobine est alimentée à un moment donné.

GPIO.setup(coil_A_1_pin, GPIO.OUT) GPIO.setup(coil_A_2_pin, GPIO.OUT) GPIO.setup(coil_B_1_pin, GPIO.OUT) GPIO.setup(coil_B_2_pin, GPIO.OUT)

Ici nous faisons le paramétrage, en déterminant quelles broches sont utilisées comme sorties.

def setStep(w1, w2, w3, w4):

GPIO.output(coil_A_1_pin, w1)
GPIO.output(coil_A_2_pin, w2)
GPIO.output(coil_B_1_pin, w3)
GPIO.output(coil_B_2_pin, w4)

This subroutine is called each time we want to step the motor and we pass a 0 or 1 to each coil wire port on the driver chip to energize or deenergize the various coils to turn the rotor. And finally our “main” routine which loops over and over again asking the amount of the time delay and the number of steps in that given direction. For my motor, it takes 512 steps to make close to a full rotation. On my system, with my motor, a time delay of 1ms works well. However, you might have to add a few milliseconds to yours for it to work. Notice I stated that it takes 512 steps to make CLOSE to a full rotation. This motor has a 64:1 gearing ratio, which leaves a rather ugly fractional step angle. But for the purposes of this tutorial, it works pretty well. If you want to learn more about stepper motors, adafruit.com has a very nice article on the subject. Hopefully you have enjoyed the series so far. Next up will be learning to use the Arduino microcontroller board. We’ll use this information in the third section of the series where we control the Arduino with a Raspberry Pi (or other computer). So, that having been said, you should be ready and have an Arduino (Uno or Mega) ready and dust off the components we used in the early part of this series for next time. Until then, keep learning and above all, HAVE FUN!

Cette sous-routine est appelée chaque fois que nous voulons faire avancer le moteur d'un pas, et nous transmettons un 0 ou un 1 à chaque broche de fil de bobine sur la puce de commande pour alimenter ou pas les différentes bobines pour faire tourner le rotor.

Et enfin notre fonction « main » (principale) qui boucle sans cesse en demandant la quantité de temps et le nombre de pas dans cette direction donnée. Pour mon moteur, il faut 512 pas pour faire presque une rotation complète.

Sur mon système, avec mon moteur, un délai de 1 ms fonctionne bien. Mais vous devrez peut-être ajouter quelques millisecondes au vôtre pour qu'il fonctionne.

Notez que j'ai dit qu'il fallait 512 pas pour faire PRESQUE une rotation complète. Ce moteur a un rapport d'accélération de 64:1, pour lequel l'angle de pas est une fraction assez laide. Mais pour ce tutoriel, ça marche assez bien.

Si vous voulez en apprendre plus sur les moteurs pas-à-pas, adafruit.com propose un chouette petit article sur le sujet.

J'espère que vous avez aimé cette série jusqu'ici. Le prochain article vous apprendra à utiliser la carte microcontrôleur de l'Arduino. Nous utiliserons cette information dans la troisième partie de la série où nous contrôlerons l'Arduino avec un Raspberry Pi (ou tout autre ordinateur). Aussi, cela étant dit, pour la prochaine fois, vous devriez être prêt avec un Arduino (Uno ou Mega) et avoir sorti de leur carton les composants que nous avons utilisés au tout début de cette série.

En attendant, continuez d'apprendre et surtout, AMUSEZ-VOUS !

Encadré de la page 19, texte en noir : These two routines allow for easily commanding the motor forwards or backwards a specific number of steps in the proper direction.

Encadré de la page 19, texte en noir :

Ces deux fonctions permettent, pour commander facilement le moteur en avant ou en arrière, un nombre spécifique de pas dans la direction appropriée.

issue115/python.txt · Dernière modification : 2016/12/10 15:35 de andre_domenech