Defining Encoder() pins at runtime

Status
Not open for further replies.

brianmichalk

Active member
Using quadrature Encoder library, v1.3, Teensy3.2.
I thought I would be clever with a macro definition to get around the requirement of
defining the encoder A/B pins at compile time. The problem is that a supplier
swapped the encoder lines on a motor I'm using, so I added a solder pad that when
shorted, would inform the firmware whether to reverse the pins.
It looks like the macro extension is not supported:

#define REVERSE_PIN 9 // if pin 9 is grounded, then reverse the encoder pin A/B
#define ENCODER_A_PIN ({ \
int i = 0;\
pinMode(REVERSE_PIN, INPUT_PULLUP);\
delay(10);\
if (digitalRead(REVERSE_PIN)==LOW) { i=1;}\
i;\
})

I can modify the library, and will do so. I am wondering if there is a better way to do this.
 
Maybe read the pin once in setup() and set a variable to either 1 or -1. Then when you read the encoder, multiply by that number.
 
Doh! It's so easy. Okay, this does solve my particular problem. Thanks.
For argument's sake, what would your solution be if the encoder wires were on completely different pins?
 
How about instantiating the Encoder dynamically? This is a modification of the "Basic Example" from the Encoder library. It compiles but is untested:
Code:
#include "Arduino.h"
#include <Encoder.h>

Encoder *encoderPtr;
const uint8_t polarityPin = 9;

void setup() {
	Serial.begin(115200);
	Serial.println("Basic Encoder Test:");
	pinMode(polarityPin, INPUT_PULLUP);
	if (digitalRead(polarityPin)) {
		encoderPtr = new Encoder(2, 3);
	} else {
		encoderPtr = new Encoder(3, 2);
	}
}

long oldPosition = -999;

void loop() {
	long newPosition = encoderPtr->read();
	if (newPosition != oldPosition) {
		oldPosition = newPosition;
		Serial.println(newPosition);
	}
}
 
Thanks. I keep forgetting about this. Too many languages at one time.

How about instantiating the Encoder dynamically? This is a modification of the "Basic Example" from the Encoder library. It compiles but is untested:
Code:
#include "Arduino.h"
#include <Encoder.h>

Encoder *encoderPtr;
const uint8_t polarityPin = 9;

void setup() {
	Serial.begin(115200);
	Serial.println("Basic Encoder Test:");
	pinMode(polarityPin, INPUT_PULLUP);
	if (digitalRead(polarityPin)) {
		encoderPtr = new Encoder(2, 3);
	} else {
		encoderPtr = new Encoder(3, 2);
	}
}

long oldPosition = -999;

void loop() {
	long newPosition = encoderPtr->read();
	if (newPosition != oldPosition) {
		oldPosition = newPosition;
		Serial.println(newPosition);
	}
}
 
Status
Not open for further replies.
Back
Top