Servo myServo;
int potPin = A5;
int lastPos = -1;
int pairPos = -1;
bool allowDialInput = true; // Flag to control dial input
unsigned long lastSubscriptionTime = 0;
const unsigned long dialInputTimeout = 2000;
void setup() {
Serial.begin(9600);
myServo.attach(A3);
Particle.variable("servoPos", myServo.read());
Particle.subscribe("spinServo", handleSpinServo);
}
void loop() {
int potReading = analogRead(potPin);
int mappedPos = map(potReading, 0, 4095, 20, 160);
// Only update the servo position if the potentiometer reading has changed significantly
if (abs(mappedPos - myServo.read()) > 20 && allowDialInput) {
myServo.write(mappedPos);
Serial.print("Set servo position to: ");
Serial.println(mappedPos);
Particle.publish("doPairedPublish", String(mappedPos));
Serial.print("Published new position: ");
Serial.println(mappedPos);
lastPos = mappedPos;
delay(500);
}
// Check if the timeout has passed, re-enable dial input if necessary
if (!allowDialInput && millis() - lastSubscriptionTime >= dialInputTimeout) {
allowDialInput = true;
Serial.println("Dial input re-enabled");
}
}
void handleSpinServo(const char *event, const char *data) {
// Convert the data to an integer representing the new servo position
int newPos = atoi(data);
// Disable dial input when handling external subscription
allowDialInput = false;
myServo.write(newPos);
// Record the paired position
pairPos = newPos;
Serial.print("Set servo position via subscribe to: ");
Serial.println(newPos);
lastSubscriptionTime = millis();
}
Click to Expand
Content Rating
Is this a good/useful/informative piece of content to include in the project? Have your say!
You must login before you can post a comment. .