edge lab LIVE! starts Tuesday in Munich. Grab a workshop seat and take home the board you build on. Code FRIEND-HACKSTER saves 20%. () Learn more!
Adam Radjabov
Published © GPL3+

Joystick and servo with led

This is a joystick with a servo motor that blinks at a different speed depending on were the servo arm is.

BeginnerShowcase (no instructions)1 hour90
Joystick and servo with led

Things used in this project

Hardware components

SG90 Micro-servo motor
SG90 Micro-servo motor
×1
Arduino Jinpat Electronics
×1
LED (generic)
LED (generic)
×1
Male/Male Jumper Wires
×6
Male/Female Jumper Wires
Male/Female Jumper Wires
×1
Resistor 220 ohm
Resistor 220 ohm
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Custom parts and enclosures

diagram for project

diagram for project

Schematics

project diagram

for connections

Code

servo+joystick+led code

JavaScript
for controlling the servo
#include <Servo.h>

Servo myServo;

// Pins
const int joystickXPin = A0;
const int servoPin = 9;
const int ledPin = 13;

// Servo settings
int servoAngle = 90;
const int deadzone = 50;
const int moveSpeed = 2;

// LED blink timing
unsigned long previousMillis = 0;
bool ledState = LOW;

void setup() {
  myServo.attach(servoPin);
  myServo.write(servoAngle);

  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);
}

void loop() {

  // Read joystick
  int joystickX = analogRead(joystickXPin);

  // Move servo
  if (joystickX > (512 + deadzone)) {
    servoAngle += moveSpeed;
  }
  else if (joystickX < (512 - deadzone)) {
    servoAngle -= moveSpeed;
  }

  // Keep angle within limits
  servoAngle = constrain(servoAngle, 0, 180);

  // Update servo position
  myServo.write(servoAngle);

  // Distance from center
  int distanceFromCenter = abs(servoAngle - 90);

  // LED blink logic
  if (distanceFromCenter > 10) {

    // Faster blinking closer to 0° or 180°
    int blinkInterval = map(distanceFromCenter, 10, 90, 500, 50);

    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= blinkInterval) {
      previousMillis = currentMillis;

      ledState = !ledState;
      digitalWrite(ledPin, ledState);
    }
  }
  else {
    digitalWrite(ledPin, LOW);
    ledState = LOW;
  }

  // Debug output
  Serial.print("Servo Angle: ");
  Serial.print(servoAngle);
  Serial.print(" | Blink Distance: ");
  Serial.println(distanceFromCenter);

  delay(20);
}

Credits

Adam Radjabov
9 projects • 1 follower

Comments