Mémos

M é m o - l a b .

Arduino – Joystick et leds – fonction map

Le principe est de commander 2 leds et un Buzzer à partir d’un Joystick.
Nous n’utiliserons que le mouvement du Joystick en x. La led verte s’allume lorsque le Joystick est déplacé vers la droite et la led rouge lorsque le Joystick est déplacé vers la gauche. Les 2leds sont éteintes lorsque le Joystick est en position centrée.
Lorsque l’on appui sur le bouton, le buzzer joue la note LA 440Hz durant 700ms.

Schéma

Code





// Joystick
const char joyXPin = 0;
const char joyBtnPin = 4;
const char buzzerPin = 2;
const int note = 440;
unsigned int joyX;
bool joyBtn;
const unsigned int joyRange = 1024;
const char tolerance = 30;

// LED
const char ledGreenPin = 12;
const char ledRedPin = 14;

void setup() 
{
  pinMode(joyXPin, INPUT);
  pinMode(joyBtnPin, INPUT_PULLUP);
  pinMode(ledGreenPin, OUTPUT);
  pinMode(ledRedPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
}

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

  int brightnessGreen = map(joyX,joyRange/2,joyRange,0,255);
  int brightnessRed = map(joyX,0,joyRange/2,255,0);

  switch(joyX) {
    case 0 ... ((joyRange/2)-tolerance) :
      analogWrite(ledRedPin, brightnessRed);
      analogWrite(ledGreenPin, 0);
      break;
    case ((joyRange/2)+tolerance) ... (joyRange) :
      analogWrite(ledGreenPin, brightnessGreen);
      analogWrite(ledRedPin, 0);
      break;
    default:
      analogWrite(ledRedPin, LOW);
      analogWrite(ledGreenPin, LOW);
  }

  // Bouton appuyé
  if (joyBtn == 0) {
    tone(buzzerPin, note, 700);
  }
}