I have a program for Arduino Mini 16MHz, and I would use it for Arduino Due.
Mini has a digital port 2-13, but DUE has 22-53.
I need 22pin for encoder A and 23pin for encoder B for out 52pin - pulse and 53pin - step.
I do not know how i can write this code functioning for DUE.
#define encoder_a 2 //need for due 22pin
#define encoder_b 3 //need for due 23pin
#define motor_step 4 //need for due 52pin
#define motor_direction 5 //need for due 53pin
#include <delay.h>
volatile long motor_position, encoder;
byte inputA;
byte inputB;
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);
// enable pullup as we are using an open collector encoder
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; //reseet the encoder position to 0
}
void loop() {
//do stuff dependent on encoder position here
//such as move a stepper motor to match encoder position
//if you want to make it 1:1 ensure the encoder res matches the motor res by dividing/multiplying
if (encoder > 0) {
//digitalWrite(motor_direction, HIGH);// move stepper in reverse
PORTD = PORTD | 0b00100000;
//digitalWrite(motor_step, HIGH);
PORTD = PORTD | 0b00010000;
//digitalWrite(motor_step, LOW);
PORTD = PORTD & 0b11101111;
delayMicroseconds(600); //_delay_us(200); //modify to alter speed
motor_position++;
encoder = 0; //encoder--;
}
else if (encoder < 0) {
//digitalWrite (motor_direction, LOW); //move stepper forward
PORTD = PORTD & 0b11011111;
//digitalWrite (motor_step, HIGH);
PORTD = PORTD | 0b00010000;
//digitalWrite (motor_step, LOW);
PORTD = PORTD & 0b11101111;
delayMicroseconds(600); //_delay_us(200); //modify to alter speed
motor_position--;
encoder = 0; //encoder++;
}
}
void encoderPinChangeA() {
inputA = (PIND & 0b00000100) >>2; // result is 0b00000001 if input is high, 0b00000000 if input is low.
inputB = (PIND & 0b00001000) >>3; //result is 0b00000001 if input is high, 0b00000000 if input is low.
//if (digitalRead(encoder_a)==digitalRead(encoder_b)) {
if (inputA == inputB){
encoder--;
}
else{
encoder++;
}
}
void encoderPinChangeB() {
inputA = (PIND & 0b00000100) >>2; // result is 0b00000001 if input is high, 0b00000000 if input is low.
inputB = (PIND & 0b00001000) >>3; // result is 0b00000001 if input is high, 0b00000000 if input is low.
//if (digitalRead(encoder_a) != digitalRead(encoder_b)) {
if (inputA != inputB){
encoder--;
}
else {
encoder++;
}
}