Position problem after motor is home.

I modified this sketch from Brainy-Bits to use with my Adafruit V2 shield and the home function works up until the limit switch is hit. Then when I enter new positions in the serial monitor the monitor says the stepper moved and in fact it does not. I think there is an issue in my void loop or at the end of setup, but I can’t find it.

any eyes on and advice is appreciated.

/*  Motor Homing code using AccelStepper and the Serial Monitor

  Created by Yvan / https://Brainy-Bits.com
  This code is in the public domain...
*/

#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

// Define the Pins used
#define home_switch 18 // Pin 18 connected to Home Switch (MicroSwitch)

// Stepper Travel Variables
long TravelX;  // Used to store the X value entered in the Serial Monitor
int move_finished = 1; // Used to check if move is completed
long initial_homing = -1; // Used to Home Stepper at startup

void forwardstep1() {
  mystepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, SINGLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1); // use functions to step

void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  AFMSmid.begin();  // create with the default frequency 1.6KHz
  pinMode(home_switch, INPUT_PULLUP);

  delay(5);  // Wait for EasyDriver wake up

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    Astepper1.run();  // Start moving the stepper
    delay(5);
  }

  Astepper1.setCurrentPosition(0);  // Set the current position as zero for now
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing++;
    delay(5);
  }

  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(1000.0);      // Set Max Speed of Stepper (Faster for regular movements)
  Astepper1.setAcceleration(1000.0);  // Set Acceleration of Stepper

  // Print out Instructions on the Serial Monitor at Start
  Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
}

void loop() {

  while (Serial.available() > 0)  { // Check if values are available in the Serial Buffer

    move_finished = 0; // Set variable for checking move of the Stepper

    TravelX = Serial.parseInt(); // Put numeric value from buffer in TravelX variable
    if (TravelX < 0 || TravelX > 1350) {  // Make sure the position entered is not beyond the HOME or MAX position
      Serial.println("");
      Serial.println("Please enter a value greater than zero and smaller or equal to 1350.....");
      Serial.println("");
    } else {
      Serial.print("Moving stepper into position: ");
      Serial.println(TravelX);

      Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper

      delay(1000);  // Wait 1 seconds before moving the Stepper
    }
  }

  if (TravelX >= 0 && TravelX <= 1350) {

    // Check if the Stepper has reached desired position
    if ((Astepper1.distanceToGo() != 0)) {

      Astepper1.run();  // Move Stepper into position

    }

    // If move is completed display message on Serial Monitor
    if ((move_finished == 0) && (Astepper1.distanceToGo() == 0)) {
      Serial.println("COMPLETED!");
      Serial.println("");
      Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
      move_finished = 1; // Reset move variable
    }
  }
}

If you see the message from line 66 Serial.println("Homing Completed"); then I don't think the problem has anything to do with homing.

The code for receiving data is not at all robust. Just because Serial.parseInt() is satisfied once does not mean that the input buffer is empty and the next time around loop() there may be another character that is not sufficient to satisfy parseInt(). Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

Temporarily take out the entire WHILE clause and just give TravelX the value 200 and see what happens.

...R

I removed the "while" in the loop and doing so the serial monitor reads this.

"St . . . . . . Stepper is Homing . . . . . . . . . . . Homing Completed

Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): "

Then when I enter a value nothing happens.

Thank you for the help.

AROTTER2:
I removed the "while" in the loop and doing so the serial monitor reads this.

.....

Then when I enter a value nothing happens.

You need to post the latest version of your program so we can see exactly what you did.

In my Reply #1 I intended you to create a system that does not ask for any input and, instead, uses a fixed value for TravelX just to see if the stepper code is working properly.

...R

Ok, with this code it now Stops at limit switch and then moves 200 like I belive you asked.

thank you again

#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

// Define the Pins used
#define home_switch 18 // Pin 9 connected to Home Switch (MicroSwitch)

// Stepper Travel Variables
long TravelX;  // Used to store the X value entered in the Serial Monitor
int move_finished = 1; // Used to check if move is completed
long initial_homing = -1; // Used to Home Stepper at startup

void forwardstep1() {
  mystepper1->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1); // use functions to step

void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  AFMSmid.begin();  // create with the default frequency 1.6KHz
  pinMode(home_switch, INPUT_PULLUP);

  delay(5);  // Wait for EasyDriver wake up

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    Astepper1.run();  // Start moving the stepper
    delay(5);
  }

  Astepper1.setCurrentPosition(0);  // Set the current position as zero for now
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing++;
    delay(5);
  }
  mystepper1->release(); //Release steper to save on heat! Using <Adafruit_MotorShield.h>
  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(600.0);      // Set Max Speed of Stepper (Faster for regular movements)
  Astepper1.setAcceleration(600.0);  // Set Acceleration of Stepper

  // Print out Instructions on the Serial Monitor at Start
  Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
}

void loop() {

/*  while (Serial.available() > 0)  { // Check if values are available in the Serial Buffer

    move_finished = 0; // Set variable for checking move of the Stepper

    TravelX = Serial.parseInt(); // Put numeric value from buffer in TravelX variable
    if (TravelX < 0 || TravelX > 1350) {  // Make sure the position entered is not beyond the HOME or MAX position
      Serial.println("");
      Serial.println("Please enter a value greater than zero and smaller or equal to 1350.....");
      Serial.println("");
    } else {
      Serial.print("Moving stepper into position: ");
      Serial.println(TravelX);
*/
   
   Astepper1.moveTo(200);  // Set new moveto position of Stepper
Astepper1.run();  // Move Stepper into position
//      delay(1000);  // Wait 1 seconds before moving the Stepper
    }
//  }

/*
  if (TravelX >= 0 && TravelX <= 1350) {

    // Check if the Stepper has reached desired position
    if ((Astepper1.distanceToGo() != 0)) {

      Astepper1.run();  // Move Stepper into position

    }

    // If move is completed display message on Serial Monitor
    if ((move_finished == 0) && (Astepper1.distanceToGo() == 0)) {
      Serial.println("COMPLETED!");
      Serial.println("");
      Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
      move_finished = 1; // Reset move variable
    }
  }
}
*/

OK. That’s progress. But I had intended that you would do this

TravelX = 200;
Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
Astepper1.run();

because that lays the groundwork for adding in code that gets the value for TravelX from Serial

Now add in some code to receive the serial data - if you are just sending data from the Serial Monitor then the code in the 2nd example in Serial Input Basics will be sufficient, although the 3rd example would be more reliable if you are prepared to take the trouble to enter <200> rather than just 200.

When you have that done all that should happen is whenever you enter data in the Serial Monitor it prints the message “This just in NNN” where NNN is the number you entered. And when that is working we can go another step.

Keep the code from my example in functions just like I have posted it.

…R

ok, it Homes, steps 200 and then displays “This just in NNN” with whatever I enter into the serial monitor .

#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

// Define the Pins used
#define home_switch 18 // Pin 9 connected to Home Switch (MicroSwitch)

// Stepper Travel Variables
long TravelX;  // Used to store the X value entered in the Serial Monitor
int move_finished = 1; // Used to check if move is completed
long initial_homing = -1; // Used to Home Stepper at startup

void forwardstep1() {
  mystepper1->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1); // use functions to step

///////////////////////////////////////////////////////////////////////
const byte numChars = 32;
char receivedChars[numChars];   // an array to store the received data
boolean newData = false;
//////////////////////////////////////////////////////////////////////

void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  AFMSmid.begin();  // create with the default frequency 1.6KHz
  pinMode(home_switch, INPUT_PULLUP);

  delay(5);

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    Astepper1.run();  // Start moving the stepper
    delay(5);
  }

  Astepper1.setCurrentPosition(0);  // Set the current position as zero for now
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing++;
    delay(5);
  }
  mystepper1->release(); //Release steper to save on heat! Using <Adafruit_MotorShield.h>
  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(600.0);      // Set Max Speed of Stepper (Faster for regular movements)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper

  // Print out Instructions on the Serial Monitor at Start
  Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
}

void loop() {

  /*  while (Serial.available() > 0)  { // Check if values are available in the Serial Buffer

      move_finished = 0; // Set variable for checking move of the Stepper

      TravelX = Serial.parseInt(); // Put numeric value from buffer in TravelX variable
      if (TravelX < 0 || TravelX > 1350) {  // Make sure the position entered is not beyond the HOME or MAX position
        Serial.println("");
        Serial.println("Please enter a value greater than zero and smaller or equal to 1350.....");
        Serial.println("");
      } else {
        Serial.print("Moving stepper into position: ");
        Serial.println(TravelX);
  */
///////////////////////////////////////////////////////////////////////////
  TravelX = 200;
  Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
  Astepper1.run();
  recvWithEndMarker();
  showNewData();
///////////////////////////////////////////////////////////////////////////

//       delay(1000);  // Wait 1 seconds before moving the Stepper
}
///////////////////////////////////////////////////////////////////////////
void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  char rc;

  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();

    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    }
    else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChars);
    newData = false;
  }
}
//////////////////////////////////////////////////////////////////////////
/*
  }

  if (TravelX >= 0 && TravelX <= 1350) {

    // Check if the Stepper has reached desired position
    if ((Astepper1.distanceToGo() != 0)) {

      Astepper1.run();  // Move Stepper into position

    }

    // If move is completed display message on Serial Monitor
    if ((move_finished == 0) && (Astepper1.distanceToGo() == 0)) {
      Serial.println("COMPLETED!");
      Serial.println("");
      Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
      move_finished = 1; // Reset move variable
    }
  }
  }
*/

Great.

Now add another small function to that code, like this and call it before showNewData()

void parseData() {
   TravelX = atol(receivedChars); // note that it is ATOL(
}

and comment out the existing line

  TravelX = 200;

...R

This compiles, uploads and runs.

Before we get too far, I wanted to clarify that eventually I am looking to replace the “TravelX” with serial input from a light sensor to use to adjust position of the stepper.

Thank you again!

#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

// Define the Pins used
#define home_switch 18 // Pin 9 connected to Home Switch (MicroSwitch)

// Stepper Travel Variables
long TravelX;  // Used to store the X value entered in the Serial Monitor
int move_finished = 1; // Used to check if move is completed
long initial_homing = -1; // Used to Home Stepper at startup

void forwardstep1() {
  mystepper1->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1); // use functions to step

///////////////////////////////////////////////////////////////////////
const byte numChars = 32;
char receivedChars[numChars];   // an array to store the received data
boolean newData = false;
//////////////////////////////////////////////////////////////////////

void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  AFMSmid.begin();  // create with the default frequency 1.6KHz
  pinMode(home_switch, INPUT_PULLUP);

  delay(5);

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing--;  // Decrease by 1 for next move if needed
    Astepper1.run();  // Start moving the stepper
    delay(5);
  }

  Astepper1.setCurrentPosition(0);  // Set the current position as zero for now
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing++;
    delay(5);
  }
  mystepper1->release(); //Release steper to save on heat! Using <Adafruit_MotorShield.h>
  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(600.0);      // Set Max Speed of Stepper (Faster for regular movements)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper

  // Print out Instructions on the Serial Monitor at Start
  Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
}

void loop() {
///////////////////////////////////////////////////////////////////////////
//  TravelX = 200;
  Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
  Astepper1.run();
  recvWithEndMarker();
  showNewData();
///////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////
void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  char rc;

  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();

    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    }
    else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void parseData() {
   TravelX = atol(receivedChars); // note that it is ATOL(
}

void showNewData() {
  if (newData == true) {
    Serial.print("This just in ... ");
    Serial.println(receivedChars);
    newData = false;
  }
}
//////////////////////////////////////////////////////////////////////////

You are missing a bit in loop(). It should be like this

void loop() {
///////////////////////////////////////////////////////////////////////////
//  TravelX = 200;
  Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
  Astepper1.run();
  recvWithEndMarker();
  parseData();
  showNewData();
///////////////////////////////////////////////////////////////////////////
}

And, while it probably makes no difference to the performance it would seem more logical to us humans if it was like this

void loop() {
///////////////////////////////////////////////////////////////////////////
  recvWithEndMarker();
  parseData();
  showNewData();
  Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
  Astepper1.run();
///////////////////////////////////////////////////////////////////////////
}

...R

PS. I'm not sure it is a good idea to use //////// as separators. IIRC there are some combinations of that which the compiler chokes on. I always use something like //============

oh wow. it works great!! Thank you very much..

I have more questions, but I will try to get my analog sensor readings incorporated first. I already see that I will have a problem with single steps per loop between each analog reading.

I will give this a shot and add more to this later.

Thank you again!!!!!!!

with serial input from a light sensor

What kind of light sensor outputs serial data?

PaulS:
What kind of light sensor outputs serial data?

I think the OP is just using Serial as a proxy for the values that will eventually come from the light sensor.

...R

Sorry about that. Yes, i intended to say that I am looking to replace the "TravelX" with "Analog" data from a light sensor.

Thanks again.

I am back at this again and I would like to see if i can get some more guidance.

Bellow is a sketch that works with my light sensor by using a light source at either above or below a set value. “UserRange = 500”

If light is < range. the stepper moves (-)
It light is > range. the stepper moves (+)
If else, then it stops.

  if (RawToLux(rawValue) < UserRange) {
    Astepper1.move(-10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else if (RawToLux(rawValue) > UserRange) {
    Astepper1.move(+10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else {
    Astepper1.stop();
  }

BUT, being that it is impossible to maintain a constant Lux value I would like to assign it to a range. Maybe something like having a variable = +100 and -100 from the UserRange of 500 so that it would take a significant change in lighting to re position the stepper.

Is there a way to set a range to a variable? I tried using constrain() but I find it requires map()? and I do not need to remap. I am a bit lost again.

Any advice is greatly appreciated.

//Intent!
//To obtain serial data from a light sensor and
//use it to adjust the positioning of stepper
//to keep a room at a constant brightness.

//===Stepper Setup=================================================================================
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

long TravelX;  // Variable used to store the X value entered in the Serial Monitor.
int move_finished = 1; // Variable used to check if stepper move is completed.
long initial_homing = -1; // Variable used to Home Stepper at startup.

//Associates the Accel Stepper Library for use with the Adafruit Motor Shield. "I think!".
void forwardstep1() {
  mystepper1->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, DOUBLE);
}
AccelStepper Astepper1(forwardstep1, backwardstep1); // use functions to step from Adafruit Motor Shield.

const byte numChars = 32;       //"const" makes the variable Read-Only never to change.
char receivedChars[numChars];   //An array to store the received data.
boolean newData = false;        //boolean for "off,false or 0"

#define home_switch 18 // Defines Pin 9 too Home Switch.

//===Analog Light Sensor================================================================
//Connect 5v to VCC and GND to GND
//Connect 3.3v to the AREF pin
int sensorPin = A8;    // Analog input pin for the GA1A1S202WP Analog Light Sensor (Lux Scale).
float rawRange = 1024; // 3.3v
float logRange = 5.0; // 3.3v = 10^5 lux
float RawToLux(int raw)
{
  float logLux = raw * logRange / rawRange;
  return pow(10, logLux);
}
int rawValue = analogRead(sensorPin); // read the raw value from the sensor:
int UserInput = 500;    //User prefered light level Input PIN.
int UserRange = 500; //User prefered light level Range from Input.

int HomeStep = 0;   //Home step.
int MaxStep = 2000; //Max blinds travel.

//int Lux1 = (RawToLux(rawValue) >= 0 && RawToLux(rawValue) <= 99);
//int Lux2 = (RawToLux(rawValue) >= 100 && RawToLux(rawValue) <= 499);

//====================================================================================
void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds
  AFMSmid.begin();     // create with the default frequency 1.6KHz
  pinMode(home_switch, INPUT_PULLUP);
  analogReference(EXTERNAL); //Analog Light Sensor

  delay(5);

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing++;  // Increase by 1 for next move if needed // Sets Stepper to Roll up blind till home.
    Astepper1.run();  // Start moving the stepper.
    delay(5);
  }

  Astepper1.setCurrentPosition(0);  // Set the current position as zero for now
  Astepper1.setMaxSpeed(100.0);      // Set Max Speed of Stepper (Slower to get better accuracy)
  Astepper1.setAcceleration(50.0);  // Set Acceleration of Stepper
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing--;  // Decrease by 1 for next move if needed.
    delay(5);
  }
  mystepper1->release(); //Release steper to save on heat! Using <Adafruit_MotorShield.h>
  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(600.0);      // Set Max Speed of Stepper (Faster for regular movements)
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper

  // Print out Instructions on the Serial Monitor at Start
  Serial.println("Enter Travel distance (Positive for CW / Negative for CCW and Zero for back to Home): ");
}
//===End Void Setup=================================================================================
void loop() {
  //===Analog Light Sensor Loop================================================================
  int rawValue = analogRead(sensorPin); // read the raw value from the sensor:
  Serial.println(RawToLux(rawValue));
  delay(10);    //This works, but it REALLY SLOWS DOWN the steper.....

  //===Lux Range Loop=================================================================================
  /* //This is for future ranges...
      if (UserInput >= 0 && UserInput <= 99) {
        UserRange = Lux1;
      }
      if (UserInput >= 100 && UserInput <= 499) {
        UserRange = Lux2;
      }
      if (UserInput >= 500 && UserInput <= 1499) {
        UserRange = Lux3;
      }
      if (UserInput >= 1500 && UserInput <= 4999) {
        UserRange = Lux4;
      }
      if (UserInput >= 5000 && UserInput <= 9999) {
        UserRange = Lux5;
      }
      if (UserInput >= 10000 && UserInput <= 24999) {
        UserRange = Lux6;
      }
      if (UserInput >= 25000 && UserInput <= 49999) {
        UserRange = Lux7;
      }
      if (UserInput >= 50000 && UserInput <= 74999) {
        UserRange = Lux8;
      }
      if (UserInput >= 75000 && UserInput <= 119999) {
        UserRange = Lux9;
      }
  */

//=== This is the area in question ======================

  if (RawToLux(rawValue) < UserRange) {
    Astepper1.move(-10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else if (RawToLux(rawValue) > UserRange) {
    Astepper1.move(+10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else {
    Astepper1.stop();
  }

  //===Stepper Loop for direct step input in serial monitor=======================================
  /*  recvWithEndMarker();
    parseData();
    showNewData();
    Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
    Astepper1.run();
  */
}
//===End Void Loop=================================================================================

void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  char rc;

  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();

    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    }
    else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void parseData() {
  TravelX = atol(receivedChars); // note that it is ATOL(
}

void showNewData() {
  if (newData == true) {
    Serial.print("Moving to position ... ");
    Serial.println(receivedChars);
    newData = false;
  }
}

//===Analog Light Sensor=========================================================


//===Credits=====================================================================
//Brainy-Bits.com.
//Adafruit.com Forum.
//Arduino Forum and "Robin2".

It seems to me that this code already works with a range
if (RawToLux(rawValue) < UserRange)

I don’t understand what you want to do that is different?

Maybe you would be better testing for the ELSE part first

if (lux > x and lux < y)

Or maybe you need another light sensor to detect the ambient light level and then you could have something like

if (lux > ambient + X and lux < ambient - X)

…R

Is there a way to set a range to a variable?

No. A variable holds a single value. You CAN compare that variable to two different values (ends of a range)

   if(someValue >= lowEnd && someValue <= highEnd)
   {
      // someValue is between lowEnd and highEnd, inclusive

Oh Robin2 you helped again… :slight_smile:

if (lux > ambient + X and lux < ambient - X)

After adding the ( - 250) & ( + 250) it worked like intended. i didn’t realize i could do that in the first place.

Thank you again.

Next, i have 9 buttons on a webpage i am trying to set so i can have the variable "UserRange" assigned to 9 different numbers. an example of a single variable is bellow.

  if (client.read() == "Range1")  {
    UserRange = 250;                     //User prefered light level Range from Webpage.
    Serial.println("UserRange");       //Verify output is as intended.
}

i keep getting this in the serial monitor and not the 250 i wanted.

GET /Range1 HTTP/1.1
new client

I will post the entire new sketch if i can get it below character limit.

//==== WiFi Initialization 
#include <SPI.h>
#include <WiFi101.h>
IPAddress ip(192, 168, 1, 110);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0); 
char ssid[] = "NETGEAR";
char pass[] = "xxxx";
int keyIndex = 0;
int status = WL_IDLE_STATUS;
WiFiServer server(80);


//===Stepper Initialization 
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMSmid(0x61); // I2C address of MEGA shield.
Adafruit_StepperMotor *mystepper1 = AFMSmid.getStepper(200, 1);  // 200step 1.8degree Motor on port #1 (M1 and M2).

long TravelX;
int move_finished = 1;
long initial_homing = -1; 

int Range1;

void forwardstep1() {
  mystepper1->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  mystepper1->onestep(BACKWARD, DOUBLE);
}
AccelStepper Astepper1(forwardstep1, backwardstep1); 

const byte numChars = 32;       //"const" makes the variable Read-Only never to change.
char receivedChars[numChars];   //An array to store the received data.
boolean newData = false;        //boolean for "off,false or 0"

#define home_switch 18 // Defines Pin 9 too Home Switch.
//===Stepper Initialization 


//===Analog Light Initialization
//Connect 5v to VCC and GND to GND
//Connect 3.3v to the AREF pin
int sensorPin = A8;  
float rawRange = 1024; // 3.3v
float logRange = 5.0; // 3.3v = 10^5 lux
float RawToLux(int raw)
{
  float logLux = raw * logRange / rawRange;
  return pow(10, logLux);
}
int rawValue = analogRead(sensorPin); // read the raw value from the sensor:
int UserRange;

int HomeStep = 0;   //Home step.
int MaxStep = 2000; //Max blinds travel.

//===Analog Light Initialization
void setup() {
  Serial.begin(9600);  // Start the Serial monitor with speed of 9600 Bauds

  //==== WiFi Setup
  WiFi.setPins(46, 47, 48); 

  WiFi.config(ip);
  status = WiFi.begin(ssid, pass);
  server.begin();

  // print your WiFi shield's SSID:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  //==== WiFi Setup ==================================================

  AFMSmid.begin(); 
  pinMode(home_switch, INPUT_PULLUP);
  analogReference(EXTERNAL); //Analog Light Sensor

  delay(5);

  //  Set Max Speed and Acceleration of each Steppers at startup for homing
  Astepper1.setMaxSpeed(100.0);
  Astepper1.setAcceleration(50.0);


  // Start Homing procedure of Stepper Motor at startup

  Serial.print("Stepper is Homing . . . . . . . . . . . ");

  while (digitalRead(home_switch)) {  // Make the Stepper move CCW until the switch is activated
    Astepper1.moveTo(initial_homing);  // Set the position to move to
    initial_homing++;  // Increase by 1 for next move if needed // Sets Stepper to Roll up blind till home.
    Astepper1.run();  // Start moving the stepper.
    delay(5);
  }

  Astepper1.setCurrentPosition(0); 
  Astepper1.setMaxSpeed(100.0);  
  Astepper1.setAcceleration(50.0); 
  initial_homing = 1;

  while (!digitalRead(home_switch)) { // Make the Stepper move CW until the switch is deactivated
    Astepper1.moveTo(initial_homing);
    Astepper1.run();
    initial_homing--;  // Decrease by 1 for next move if needed.
    delay(5);
  }
  mystepper1->release(); 
  Astepper1.setCurrentPosition(0);
  Serial.println("Homing Completed");
  Serial.println("");
  Astepper1.setMaxSpeed(600.0);      // Set Max Speed of Stepper
  Astepper1.setAcceleration(100.0);  // Set Acceleration of Stepper

}

void loop() {
  //===Analog Light Sensor Loop===========================================
  int rawValue = analogRead(sensorPin); // read the raw value from the sensor:
  //Serial.println(RawToLux(rawValue));
  //delay(10);    //This works, but it REALLY SLOWS DOWN the steper.....

  WiFiClient client = server.available();  // listen for incoming clients
  String request = client.readStringUntil('\r'); // Read the first line of the request
  Serial.println(request);
  client.flush();

  //======== Web Page Loop ============================================
  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character


          if (currentLine.length() == 0) {

            //           client.println("HTTP/1.1 200 OK");
            //           client.println("Content-type:text/html");
            //           client.println();                 // if the byte is a newline character

            //----Start of web page.------------------------------------------------------------------------------
            client.println("<html>");  // Beginning of web page.
            client.println("<center>");
            client.println(" Blind Mode Selection!
");
            client.println("<a href=\"/Blinds=Manual\"\"><button>Manual </button></a>");
            client.println("<a href=\"/Blinds=Auto\"\"><button>Auto </button></a>
");
            client.println("<a href=\"/Range1\"\"><button>Range: 1 </button></a>
");
            client.println("<a href=\"/Range2\"\"><button>Range: 2 </button></a>
");
            client.println("<a href=\"/Range3\"\"><button>Range: 3 </button></a>
");
            client.println("<a href=\"/Range4\"\"><button>Range: 4 </button></a>
");
            client.println("<a href=\"/Range5\"\"><button>Range: 5 </button></a>
");
            client.println("<a href=\"/Range6\"\"><button>Range: 6 </button></a>
");
            client.println("<a href=\"/Range7\"\"><button>Range: 7 </button></a>
");
            client.println("<a href=\"/Range8\"\"><button>Range: 8 </button></a>
");
            client.println("<a href=\"/Range9\"\"><button>Range: 9 </button></a>
");
            client.println("</html>");
            //----End of web page.------------------------------------------------------------------------------

            client.println();  // The HTTP response ends with another blank line:
            break;             // break out of the while loop:
          }
        }
      }
    }
    //    client.stop();            // close the connection:
    //    Serial.println("client disonnected");
  }
  //======== Web Page Loop =========================================

  //===Lux Range Loop======================================

  if (client.read() == "Range1")  {
    UserRange = 250;  //User prefered light level Range from Webpage.
    Serial.println("UserRange");
  }
 
  if (RawToLux(rawValue) < UserRange - 250) {
    Astepper1.move(-10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else if (RawToLux(rawValue) > UserRange + 250) {
    Astepper1.move(+10);  // Set the position to move to
    Astepper1.run();  // Start moving the stepper.
  }
  else {
    Astepper1.stop();
  }
  //===Lux Range Loop========================================

  //===Stepper Loop for direct step input in serial monitor=========================
  /*  recvWithEndMarker();
    parseData();
    showNewData();
    Astepper1.moveTo(TravelX);  // Set new moveto position of Stepper
    Astepper1.run();
  */
  //===Stepper Loop for direct step input in serial monitor===========================
}
//===End Void Loop=========================================

void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  char rc;

  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();

    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    }
    else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void parseData() {
  TravelX = atol(receivedChars);
}

void showNewData() {
  if (newData == true) {
    Serial.print("Moving to position ... ");
    Serial.println(receivedChars);
    newData = false;
  }
}