Stepper Motor Control with Arduino and Joystick

- Arduino UNO board
- 28BYJ-48 stepper motor (with ULN2003A driver board)
- Joystick
- 5V power source
- Bread board
- Jumper wires


1
|
#include <Stepper.h>
|
1
|
#define STEPS 32
|
1
2
3
4
5
6
7
8
|
// 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);
|
1
2
|
// joystick pot output is connected to Arduino A0
#define joystick A0
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
/*
* Unipolar stepper motor speed and direction control with Arduino
* and joystick
* This is a free software with NO WARRANTY.
* http://simple-circuit.com/
*/
// 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
void setup()
{
}
void loop()
{
// read analog value from the potentiometer
int val = analogRead(joystick);
// 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);
}
}
}
|