Devices & Components
Arduino Uno Rev3
Dual axis Joystick
Bread board
Balsa Wood parts
Laser pointer
Potentiometers
BIC BallPoint Pen
Jumper Wires (Male to Male)
Zip ties
Hot Glue Pistol and Hot Glue
MG90S 9G Micro Servo Motor
Male to Female jumper wires
Hardware & Tools
Your hands
Hot glue gun
hand saw
Software & Tools
Arduino IDE
Project description
Code
Light_Saber_Code
cpp
Code works for both The Arduino and Elegoo Uno R3
1#include "arduino_secrets.h" 2 3// Light saber BY: Preston Malana 4 5// Enjoy 6 7 8#include <Servo.h> 9 10Servo servoX, servoY; 11 12const int servoPin1 = 10; 13const int servoPin2 = 11; 14const int ledPin = 12; 15const int buttonPin = 2; 16 17int posX = 90; 18int posY = 90; 19int targetX = 90; 20int targetY = 90; 21 22void setup() { 23 servoX.attach(servoPin1); 24 servoY.attach(servoPin2); 25 26 pinMode(ledPin, OUTPUT); 27 pinMode(buttonPin, INPUT_PULLUP); 28 29 Serial.begin(9600); 30} 31 32// Limit servo range safely 33int adjustPosition(int current, int delta) { 34 current += delta; 35 current = constrain(current, 0, 214); 36 return current; 37} 38 39// Smooth and fast servo movement with LED flicker 40void smoothMove(Servo &servo, int ¤tPos, int targetPos, int stepDelay = 2) { 41 if (currentPos == targetPos) return; 42 43 int step = (targetPos > currentPos) ? 2 : -2; // move 2° per step (faster) 44 45 while (currentPos != targetPos) { 46 currentPos += step; 47 48 // Stop exactly at the target 49 if ((step > 0 && currentPos > targetPos) || (step < 0 && currentPos < targetPos)) { 50 currentPos = targetPos; 51 } 52 53 servo.write(currentPos); 54 55 // Flicker LED briefly while moving 56 digitalWrite(ledPin, HIGH); 57 delay(1); 58 digitalWrite(ledPin, LOW); 59 60 delay(stepDelay); // small delay = faster movement 61 } 62} 63 64void loop() { 65 int xVal = analogRead(A0); 66 int yVal = analogRead(A1); 67 68 int deltaX = 0, deltaY = 0; 69 70 // Joystick X 71 if (xVal <= 450 || xVal >= 550) { 72 deltaX = map(xVal, 0, 1023, -10, 10); 73 targetX = adjustPosition(targetX, deltaX); 74 } 75 76 // Joystick Y 77 if (yVal <= 450 || yVal >= 550) { 78 deltaY = map(yVal, 0, 1023, 10, -10); 79 targetY = adjustPosition(targetY, deltaY); 80 } 81 82 // Move both servos quickly and smoothly 83 smoothMove(servoX, posX, targetX, 0.000011); 84 smoothMove(servoY, posY, targetY, 0.000011); 85 86 // LED ON when button is pressed 87 if (digitalRead(buttonPin) == LOW) 88 digitalWrite(ledPin, HIGH); 89 else 90 digitalWrite(ledPin, LOW); 91 92 delay(0.001 93 ); 94}
Documentation
Schematics
Made on circuit canvas
Circuit_Canvas_Sketch .pdf
Comments
Only logged in users can leave comments