#include <AccelStepper.h> #include <TMCStepper.h> // Pin Definitions #define DIR_PIN 2 #define STEP_PIN 3 #define LATCH_PIN 4 // Stepper Motor Setup #define MICROSTEPS 16 // TMC2160 supports up to 256 microsteps #define MIN_POS 0 // Minimum position for the flatbed #define MAX_POS 500 // Maximum position for the flatbed #define SPEED 500 // Speed of the stepper motor // Laser Transmitter and Receiver Setup #define LASER_PIN 5 #define RECEIVER_PIN A0 #define THRESHOLD 900 // Threshold value for detecting the object // Create TMC2160 stepper driver instance TMC2160Stepper driver(SPI, LATCH_PIN); // Create AccelStepper instance AccelStepper stepper(AccelStepper::FULL4WIRE, STEP_PIN, DIR_PIN); // Flag to indicate if object is touch-detected bool objectTouched = false; void setup() { // Initialize Serial Monitor Serial.begin(9600); Serial.println("Stepper Motor & Laser Control"); // Set up Stepper Motor stepper.setEnablePin(LATCH_PIN); stepper.setMaxSpeed(SPEED); stepper.setAcceleration(1000); // Adjust this value as per your requirement // Initialize TMC2160 driver driver.begin(); driver.stealthChop(0); // Enable stealthChop driver.TCOOLTHRS(0xFFFFF); // Set TCOOLTHRS to its maximum value // Set initial position of the flatbed stepper.setCurrentPosition(MIN_POS); // Set up Laser Transmitter pinMode(LASER_PIN, OUTPUT); pinMode(RECEIVER_PIN, INPUT_PULLUP); // Assuming laser receiver connected to A0 } void loop() { // Move flatbed up and down moveFlatbed(); // Check object distance using laser receiver int sensorValue = analogRead(RECEIVER_PIN); bool objectDetected = (sensorValue > THRESHOLD); // Lock flatbed when object touches laser beam with 3mm distance if (objectDetected && !objectTouched) { stepper.stop(); // Stop the flatbed objectTouched = true; // Object touched the laser beam Serial.println("Object touched. Flatbed locked."); } else if (!objectDetected && objectTouched) { objectTouched = false; // Object moved away from the laser beam } delay(100); } // Function to move the flatbed up and down void moveFlatbed() { static bool movingUp = true; if (movingUp && stepper.currentPosition() >= MAX_POS) { // Reached upper limit, start moving down movingUp = false; stepper.move(-3 * MICROSTEPS); // Move 3mm down Serial.println("Moving Down"); } else if (!movingUp && stepper.currentPosition() <= MIN_POS) { // Reached lower limit, start moving up movingUp = true; stepper.move(3 * MICROSTEPS); // Move 3mm up Serial.println("Moving Up"); } stepper.run(); }