Skip to content

Instantly share code, notes, and snippets.

@alecGraves
Created November 8, 2017 20:22
Show Gist options
  • Save alecGraves/37c366ba2dc581397ff56068fc431495 to your computer and use it in GitHub Desktop.
Save alecGraves/37c366ba2dc581397ff56068fc431495 to your computer and use it in GitHub Desktop.
const int MPIN = 2; //motor pwm out pin
const int DPIN = A0; // voltage distance sensor pin
float steady_state_error;
float voltage;
float target;
float accumulate;
void setup()
{
pinMode(DPIN, INPUT);
pinMode(MPIN, OUTPUT);
accumulate = 0;
target = 1.5; //target voltage
Serial.begin(9600);
}
void loop()
{
voltage = analogRead(DPIN) * 0.00488758553; //analogread * (5.0 / 1023.0)
steady_state_error = -1*max(min((target-voltage), 1), -1);
accumulate += 0.1 * steady_state_error;
accumulate = min(max(accumulate, -1), 1);
Serial.print(voltage);
Serial.print('\t');
Serial.print(target);
Serial.print('\t');
Serial.print(steady_state_error);
Serial.print('\t');
Serial.print(accumulate);
Serial.print('\n');
for(int i = 0; i < 20; ++i)
{
digitalWrite(MPIN, HIGH);
delayMicroseconds(accumulate*250 + steady_state_error*250+1500);
digitalWrite(MPIN, LOW);
delayMicroseconds(3000-accumulate*250 + steady_state_error*250);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment