(btw - you can use the code tag to format code blocks)
Is this perhaps a typo?
const int InputPinStart = 8; // Input pin 8 to start auto rotation of rotor
...
val = digitalRead(InputPinStart);
if (InputPinStart == HIGH) {
You are reading the encoder in a non-blocking fashion, so one improvement might be to make the other control code non-blocking as well. Here are some pointers:
- non-blocking ADC reading:
https://www.gammon.com.au/adc (https://www.gammon.com.au/adc)
- non-blocking stepper motor control:
https://reprage.com/post/non-blocking-control-of-stepper-motors-on-arduino (https://reprage.com/post/non-blocking-control-of-stepper-motors-on-arduino)
PinStart is a constant - it will always be 8. HIGH is another constant - it will always be 1. Therefore this test:
if (PinStart == HIGH) {
will always fail.
Maybe you want:
if (digitalRead(PinStart) == HIGH)
ledtester,
thanks for the review and comments. I reworked it again and got it to compile.
Do you see anything else that I tripped up on?
// Modified code for Arduino, Quadrature Optical Encoder, Stepper Motor 9-18-2019
#define encoder_a 2 // encoder a = arduino pin 2
#define encoder_b 3 // encoder b = arduino pin 3
#define motor_step 4 // motor step = arduino pin 4
#define motor_direction 5 // motor direction = arduino pin 5
#define PinStart 8 // button to start auto rotation of rotor = arduino pin 8
volatile long motor_position, encoder;
void setup () {
//set up the various outputs
pinMode(motor_step, OUTPUT);
pinMode(motor_direction, OUTPUT);
// then the encoder inputs
pinMode(encoder_a, INPUT);
pinMode(encoder_b, INPUT);
digitalWrite(encoder_a, HIGH);
digitalWrite(encoder_b, HIGH);
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, encoderPinChangeA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
attachInterrupt(1, encoderPinChangeB, CHANGE);
encoder = 0;
pinMode (PinStart, OUTPUT); // Declare pushbutton as input to start rotation
}
void step(long stepDelay) {
digitalWrite(motor_step, HIGH);
_delay_us(200);
digitalWrite(motor_step, LOW);
_delay_us(200);
}
void encoderPinChangeA()
{
if (digitalRead(encoder_a) == digitalRead(encoder_b))
{
encoder--;
}
else
{
encoder++;
}
}
void encoderPinChangeB()
{
if (digitalRead(encoder_a) != digitalRead(encoder_b))
{
encoder--;
}
else
{
encoder++;
}
}
void loop() {
//if you want to make it 1:1 ensure the encoder res matches the motor res by dividing/multiplying
if (digitalRead(PinStart) == HIGH) {
for (int i = 0; i < 100; i++) {
step(1000);
}
}
else if (encoder > 0) {
digitalWrite(motor_direction, HIGH);
digitalWrite(motor_step, HIGH);
digitalWrite(motor_step, LOW);
_delay_us(200);
motor_position++;
encoder = 0;
}
else if (encoder < 0) {
digitalWrite(motor_direction, LOW);
digitalWrite(motor_step, HIGH);
digitalWrite(motor_step, LOW);
_delay_us(200);
motor_position--;
encoder = 0;
}
}