I want to make a linear axis using a gearbox motor. I want the motor to start turning clockwise when i press button1 when ever it hits the first limit switch (limitswitch1) the motor needs to turn counterclockwise until it hits the second limitswitch (limitswitch2). now its in rest position again until i press button1. Could someone help me getting started. I dont have much experience with arduino yet.
(edit) I want to use a L298n to control the gearbox motor
Problems on a quick look, you never change 'buttonPushCounter' so it's always 0 and you read the limit switches but do nothing with the values you've read.
Make sure your buttons and switches are wired properly. You have configured the pin as INPUT which means you either need a pull-down or a pull-up resistor. It would be easier to configure them as INPUT_PULLUP and wire to ground then you don't need an external resistor.
const int buttonPin = 2;
const int limit1Pin = 5;
const int limit2Pin = 4;
const int ENA = 9;
const int IN1 = 7;
const int IN2 = 6;
int buttonState = 0;
int buttonPushCounter = 0;
int lastButtonState = 0;
int limit1State = 0;
int limit2State = 0;
void setup()
{
// put your setup code here, to run once:
pinMode (buttonPin, INPUT);
pinMode (limit1Pin, INPUT);
pinMode (limit2Pin, INPUT);
pinMode (ENA, OUTPUT);
pinMode (IN1, OUTPUT);
pinMode (IN2, OUTPUT);
Serial.begin(9600);
}
void runClockwise()
{
Serial.println("Clockwise");
analogWrite (ENA, 255);
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
}
void runCounterclockwise()
{
Serial.println("Counterclockwise");
analogWrite (ENA, 255);
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
}
void stopMotor()
{
Serial.println("Stop");
analogWrite (ENA, 0);
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
void loop()
{
// put your main code here, to run repeatedly:
buttonState = digitalRead(buttonPin);
limit1State = digitalRead(limit1Pin);
limit2State = digitalRead(limit2Pin);
if (buttonState != lastButtonState)
{
// State Change Detected
lastButtonState = buttonState;
// when i press button1
// I want the motor to start turning clockwise
if (buttonState == HIGH)
{
runClockwise();
}
}
// when ever it hits the first limit switch (limitswitch1)
// the motor needs to turn counterclockwise
if (limit1State == HIGH)
{
// Limit1 Switch Pressed
runCounterclockwise();
}
// until it hits the second limitswitch (limitswitch2). now its in rest position again until i press button1.
if (limit2State == HIGH)
{
// Limit2 Switch Pressed
stopMotor();
}
}