Skip to content

Instantly share code, notes, and snippets.

@axlevisu
Last active February 19, 2016 10:41
Show Gist options
  • Save axlevisu/19ad86bb77aa8f88d6c2 to your computer and use it in GitHub Desktop.
Save axlevisu/19ad86bb77aa8f88d6c2 to your computer and use it in GitHub Desktop.
int potin = 1;
int mot1 = 7;
int mot2 = 6;
int sensorValue = 0;
//int pid = 0;
//int pwmcontrol=4;
int init_angle= 0;
int final_angle= 0;
int final_sensor_value= 0;
int first_time= 1;
float error= 0;
float last_error =0;
float integral= 0;
float differential= 0;
int time_period =5;//in ms
float p = 2.5;
float i =5;
float d = .017;
// the setup routine runs once when you press reset:
void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
//setting of pin:
pinMode(potin,INPUT);
pinMode(mot1,OUTPUT);
pinMode(mot2,OUTPUT);
//pinMode(pwmcontrol,OUTPUT);
}
void turn(int a, int b)
{
analogWrite(mot1,a);
analogWrite(mot2,b);
Serial.println("\n mot1: ");
Serial.println(a);
Serial.println("\n mot2: ");
Serial.println(b);
}
// the loop routine runs over and over again forever:
void loop()
{ // read the input on analog pin 0:
int sensorValue = analogRead(potin);
if(first_time==1){
Serial.println("\n Initial Angle: ");
init_angle = (sensorValue*360.0)/1024.0;
Serial.println(init_angle);
//Calculating the final angle
Serial.println("\n Final Angle: ");
final_angle = (init_angle + 180)%360;
Serial.println(final_angle);
final_sensor_value = (final_angle*1024.0)/360.0;
//final_sensor_value = (sensorValue + 512)%1024;
first_time=0;
}
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (4.84 / 1023.0);
// print out the value you read:
Serial.println("\n voltage: ");
Serial.println(voltage);
Serial.println("\n sensorValue: ");
Serial.println(sensorValue);
//error=(final_sensor_value - sensorValue) * (5.0 / 1023.0);
error=(final_sensor_value - sensorValue);
integral+= (error*time_period)/1000;
differential= ((error-last_error)/time_period)*1000;
//pwm calculation:
int pwm = p*error + i*integral + d*differential;
last_error = error;
if(pwm > 255){pwm = 255;}
if(pwm < -255){pwm = -255;}
if(pwm > 0){turn(pwm,0);}
if(pwm < 0){turn(0,-pwm);}
delay(time_period);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment