#include <AccelStepper.h>
// These constants won't change:
const int sensorPin = A0; // pin that the sensor is attached to
const int ledPin = 9; // pin that the LED is attached to
const int stepPin = 10; // pin connected to the stepper motor step input
const int dirPin = 11; // pin connected to the stepper motor direction input
const int stepsPerRevolution = 1; // number of steps per revolution for your stepper motor
// Create an instance of the AccelStepper library
AccelStepper myStepper(AccelStepper::DRIVER, stepPin, dirPin);
// variables:
int sensorValue = 0; // the sensor value
int sensorMin = 1; // minimum sensor value
int sensorMax = 1010; // maximum sensor value
int motorStep = 0; // number of steps to move in each direction
int Yondegis =0;
void setup() {
// start serial communication:
Serial.begin(9600); // Set the baud rate to 9600
// turn on LED to signal the start of the calibration period:
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// calibrate during the first five seconds
while (millis() < 1000) {
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
}
// signal the end of the calibration period
digitalWrite(13, LOW);
// Print calibration results
Serial.print("Sensor Min: ");
Serial.println(sensorMin);
Serial.print("Sensor Max: ");
Serial.println(sensorMax);
if(Yondegis==1){myStepper.setPinsInverted(true, false, false);}
else{myStepper.setPinsInverted(false, false, false); }
// Set the speed and acceleration of the stepper motor
myStepper.setMaxSpeed(1000); // Set maximum speed (steps per second)
myStepper.setAcceleration(500); // Set acceleration (steps per second^2)
}
void loop() {
// read the sensor:
sensorValue = analogRead(sensorPin);
// in case the sensor value is outside the range seen during calibration
sensorValue = constrain(sensorValue, sensorMin, sensorMax);
// apply the calibration to the sensor reading
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
// fade the LED using the calibrated value:
analogWrite(ledPin, sensorValue);
// Print the sensor value to Serial Monitor
Serial.print("Sensor Value: ");
Serial.println(sensorValue);
if(sensorValue>1)
{
myStepper.moveTo(200);
}else {myStepper.moveTo(0);}
// Calculate the number of steps to move
//motorStep = map(sensorValue, sensorMax, sensorMin, 0, 255); // Map sensor value to 0-200 steps
// Set the target position for the stepper motor
//myStepper.moveTo(motorStep);
// Run the stepper to the target position
myStepper.run();
delay(10); // Delay to make serial output more readable
}