Mémos

M é m o - l a b .

Arduino – Commander un moteur pas à pas avec un joystick

Schéma de montage

Librairie

Code

// Moteur
#include <Stepper.h>
const char IN1 = 18;
const char IN2 = 19;
const char IN3 = 21;
const char IN4 = 22;
// Nbre d'etapes pour une revolution du rotor du moteur
const float stepsPerRevolution = 2048;
Stepper stepper(stepsPerRevolution, IN4, IN2, IN3, IN1);

// Joystick
const char joyXPin = 32;
const char joyYPin = 33;
const char joyBtnPin = 2;
unsigned int joyX;
unsigned int joyY;
bool joyBtn;
unsigned int valInfJoy = 462;
unsigned int valSupJoy = 562;

// LED
const char ledPin = 4;

void setup() 
{
  pinMode (joyXPin, INPUT);
  pinMode (joyYPin, INPUT);
  pinMode (joyBtnPin, INPUT_PULLUP);
  
  // rpm - vitesse de rotation - 10 tours/mn max
  stepper.setSpeed(10);
}

void loop()
{
  joyX = analogRead(joyXPin);
  joyY = analogRead(joyYPin);
  joyBtn = digitalRead(joyBtnPin);


  if (joyX > valSupJoy){
    // 1 tour de l'axe interieur
    stepper.step(4);
  }

  if (joyX < valInfJoy){
    // 1 tour de l'axe interieur
    stepper.step(-4); 
  }
    
  // Bouton appuyé
  if (joyBtn == 0) {
    digitalWrite(ledPin, HIGH);
  }
}