JCA34F:
If nothing is connected to the analog input pin, it is "floating" , picking up noise that is being interpreted as a signal, put a 10k resistor from pin to GND when the joystick is not connected.
I added a serial print so you can see the value of "val".
// include Arduino stepper motor library
#include <Stepper.h>
// define number of steps per revolution
#define STEPS 32
// define stepper motor control pins
#define IN1 11
#define IN2 10
#define IN3 9
#define IN4 8
// initialize stepper library
Stepper stepper(STEPS, IN4, IN2, IN3, IN1);
// joystick pot output is connected to Arduino A0
#define joystick A0
uint32_t tStart, tEnd = 250;
void setup()
{
Serial.begin(9600);
}
void loop()
{
// read analog value from the potentiometer
int val = analogRead(joystick);
if(millis() - tStart > tEnd)
{
Serial.println(val);
tStart += tEnd;
}
// if the joystic is in the middle ===> stop the motor
if( (val > 500) && (val < 523) )
{
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW);
digitalWrite(IN4, LOW);
}
else
{
// move the motor in the first direction
while (val >= 523)
{
// map the speed between 5 and 500 rpm
int speed_ = map(val, 523, 1023, 5, 500);
// set motor speed
stepper.setSpeed(speed_);
// move the motor (1 step)
stepper.step(1);
val = analogRead(joystick);
}
// move the motor in the other direction
while (val <= 500)
{
// map the speed between 5 and 500 rpm
int speed_ = map(val, 500, 0, 5, 500);
// set motor speed
stepper.setSpeed(speed_);
// move the motor (1 step)
stepper.step(-1);
val = analogRead(joystick);
}
}
}
I can't begin to count howmany times I tried a new video, tutorial, code, hardware rewiring.
I finally got it to work just now.
so what I can confirm for anyone that may read this with the same issue. . is when I went to serial monitor it was spamming randomly. which I believe is what you were calling a "floating Pin".
Since then I rewired and tried a simple potentiometer with the built-in example code "basics Analog Read Signal". Everything worked so I rewired the original project (joystick controlling step motor) **did not use a AA battery to power the stepper drive board, however, since the drive board was receiving power I don't believe this was the issue. **
So to sum up the believed issue:
- by using serial.print and serial monitor to view this data I had a floating pin
- floating pin - a pin that is neither connected to VCC or GND thus randomly outputs "on/off" or in this case the numerical values
- rewired which is the believed fix for this