Go Down

Topic: Basic Button - React Program (Read 972 times) previous topic - next topic

Kingtut125

Hey guys. I wrote my 1st program and want to get some feedback/assistance.

This program is basic. When you press a button, led comes on and motor rotates.
Please tell me if I have complicated things. Also, not sure why this happens. When I touch the resistor, the motor turns by itself and not necessarily in the same direction. I need it to always rotate the same direction.
What am I doing wrong?

Thanks in advance for you assistance.

// defines pins numbers
const int dirPin  = 3;
const int stepPin = 4;
const int enPin   = 5;
const int buttonPin = 8;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status
void setup() {
 
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);
 
}
void loop() {

  buttonState = digitalRead(buttonPin);
 
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
   if (buttonState == HIGH) {
   for(int x = 0; x < 1600; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
    buttonState = LOW;
  }
  delay(1000); // One second delay
  } else {
      buttonState = 1;
  }
}

wvmarle

What am I doing wrong?
Start with the two obvious things:
- you forgot to use code tags
- you forgot to post the schematic of your setup
Quality of answers is related to the quality of questions. Good questions will get good answers. Useless answers are a sign of a poor question.

PaulS

Code: [Select]
  pinMode(buttonPin, INPUT);
Wiring is so much simpler, and the results far more predictable if the mode is INPUT_PULLUP. Why isn't it?
The art of getting good answers lies in asking good questions.

Kingtut125

It isn't that way cause I didn't know I could do that.

Go Up