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;
// Time out to disable the dial at a period of time
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);
if (abs(mappedPos - lastPos) > 20 && allowDialInput) {
Particle.publish("doPairedPublish", String(mappedPos));
// Publish the updated servo position to next device
// and print in serial monitor
Serial.print("Publish servo position: ");
Serial.println(mappedPos);
// Update the last known position
lastPos = mappedPos;
// Add a delay to avoid rapid updates
delay(500);
}
// Check if the timeout has passed, re-enable dial input
if (!allowDialInput && millis() - lastSubscriptionTime >= dialInputTimeout) {
allowDialInput = true;
Serial.println("Dial input re-enabled");
}
}
void handleSpinServo(const char *event, const char *data) {
int newPos = atoi(data);
allowDialInput = false;
myServo.write(newPos);
// Disable dial input when handling external subscription
// Set the servo position based on the subscribed value
pairPos = newPos;
// Record the paired position
Serial.print("Set servo position via subscribe to: ");
Serial.println(newPos);
// Print the updated servo position to the serial monitor
// Record the time of the subscription
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. .