1

I am attempting to create a simple code that will home the motor then wait for input for direction. I have the homing function working, however the loop that reads the data from the serial monitor and returns it to the program is acting really buggy. If I enter a 1 the stepper will rotate one turn in the CCW direction, hit the home mark then reverse and go CW. If I enter a 0 the stepper will make one turn in the CW direction then repeat that move. I added a bit of feedback so I could see what my direction variable is doing, it will hold a "1", make the move, rehome and show a "0". I know the problem is in the loop, but for the life of me I can't seem to figure it out. I am new to coding, so for the love of god, go easy on me! I have added my full code so someone a little higher up in the coding world will see what I am doing. This is just some code so I can try and learn a little something and make some strange stuff in the future. Gotta start somewhere. If this question is better asked on a different thread, please direct me to it.

    // Connections
#define HALL_SENSOR      3
#define DIR      10
#define STEP      11

 
 
void homefunction() {
  
  while (digitalRead(HALL_SENSOR) == 1) {
 
    digitalWrite(DIR, LOW);
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
  }
 
}
 
void setup() {
 
  // Setup the stepper controller pins as Outputs
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);
 
  // Setup the Hall Effect switch as an Input
  pinMode(HALL_SENSOR, INPUT_PULLUP);
 
  // Home the motor
  homefunction();

  // Sets up serial monitor
  Serial.begin(9600);
  
}
 
void loop() 

  {int Direction; //Use to get the direction from the serial monitor
    Serial.println("What Direction would you like the motor to spin?"); //Input data
    while (Serial.available() == 0) //Wait for data
    Serial.read();
       Direction = Serial.parseInt();
 
 
 {
  // Read motor direction
  digitalWrite(DIR, Direction);
  Serial.println(Direction);
 
  // Spin motor
  for(int x = 0; x < 200; x++)
  {
    // while (Direction==0) //Added to hold value
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
    //Serial.println(x);
  }}}
1
  • debug your code ... sprinkle Serial.println() statements throughout your code so that you can see what is executing when ... i think that you will discover quickly the source of your problem – jsotola Feb 10 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.