// https://wokwi.com/projects/407157987423216641
// https://forum.arduino.cc/t/micros-problem/1288457
# include <Servo.h>
// # define INTERRUPTS // uncomment for interrupt version
Servo theServo;
const byte servoPin = 9;
Servo fake;
const byte fakePin = 10;
const byte faderPin = A0;
# define JawNeutral 1472 // Servos will be restricted to neutral position at times
# define StJawSigIn 2
# define JawServoOut 7
# define TnSwitch 11
# ifdef INTERRUPTS
volatile unsigned long JawNeutralMicrosStart;
# else
unsigned long JawNeutralMicrosStart;
# endif
boolean JawToNeutral = true;
void StJawRise()
{
digitalWrite(JawServoOut, HIGH);
JawNeutralMicrosStart = micros();
}
void setup()
{
Serial.begin(115200);
theServo.attach(servoPin); // ?? , 1000, 2000);
fake.attach(fakePin);
fake.write(90);
pinMode(TnSwitch, INPUT_PULLUP);
pinMode(StJawSigIn, INPUT);
pinMode(JawServoOut, OUTPUT);
pinMode(13, OUTPUT);
# ifdef INTERRUPTS
attachInterrupt(digitalPinToInterrupt(StJawSigIn), StJawRise, RISING);
Serial.println("Using interrupts");
# else
Serial.println("no interrupts need be menitoned");
# endif
}
void doPot()
{
static unsigned long lastTime;
unsigned long now = millis();
if (now - lastTime < 50) return;
lastTime = now;
int val = analogRead(faderPin);
val = map(val, 0, 1023, 0, 180);
theServo.write(val);
}
; // hey there!
void loop()
{
doPot();
// just put the servo pulse on another pin
if (0) { // if (1) to just rapidly copy the servo signal
digitalWrite(JawServoOut, digitalRead(StJawSigIn));
return;
}
JawToNeutral = digitalRead(TnSwitch) == HIGH;
{
static int lastPrinted = -1;
if (lastPrinted != JawToNeutral) {
Serial.println(JawToNeutral ? "Neutral" : "Follow");
lastPrinted = JawToNeutral;
}
}
# ifndef INTERRUPTS
static bool lastSignal;
bool thisSignal = digitalRead(StJawSigIn) == HIGH; // pulled down...
if (thisSignal != lastSignal && thisSignal) StJawRise();
lastSignal = thisSignal;
# endif
if (JawToNeutral) {
unsigned long myStart = JawNeutralMicrosStart;
# ifdef INTERRUPTS
noInterrupts();
myStart = JawNeutralMicrosStart;
interrupts();
# endif
if (micros() - myStart > JawNeutral)
digitalWrite(JawServoOut, LOW);
}
else // follow input
digitalWrite(JawServoOut, digitalRead(StJawSigIn));
}