Skip to content

Instantly share code, notes, and snippets.

@ynsta
Created July 1, 2014 23:14
Show Gist options
  • Save ynsta/c02f0b2f4935814368ec to your computer and use it in GitHub Desktop.
Save ynsta/c02f0b2f4935814368ec to your computer and use it in GitHub Desktop.
Weller RT Station PID Protoype
#define TEMPERATURE 350
#define TEMPERATURE_MAX 400
#define PWM_PIN 3
#define PWM_MAX 245
#define PID_INT_MAX (500)
#define PID_INT_MIN (-PID_INT_MAX)
#define TEMP_GAIN 0.42
#define TEMP_OFFSET 28.0
#define PERIOD_MS 1000
uint8_t pwm_val;
int temp_val;
int adc_val;
unsigned long prev_time_ms;
void setup() {
//TCCR0B = TCCR0B & 0b11111010;
pwm_val = 0;
pinMode(PWM_PIN, OUTPUT);
Serial.begin(115200);
analogWrite(PWM_PIN,0);
delay(5000);
prev_time_ms = millis();
}
void read_temperature()
{
analogWrite(PWM_PIN,0);
delay(10);
adc_val = analogRead(A0);
analogWrite(PWM_PIN,pwm_val);
temp_val = round(((float)adc_val * TEMP_GAIN) + TEMP_OFFSET);
}
float pid_kp = 3.5f;
float pid_ki = 0.3f;
float pid_kd = 1.2f;
float pid_integral = 0.0f;
float pid_error = 0.0f;
uint8_t update_pid(int target, int current)
{
float derivative;
float error;
float pwm;
error = (float)(target - current);
pid_integral += error;
derivative = error - pid_error;
pid_error = error;
if (pid_integral > PID_INT_MAX)
pid_integral = PID_INT_MAX;
if (pid_integral < PID_INT_MIN)
pid_integral = PID_INT_MIN;
pwm = (pid_kp * error)
+ (pid_ki * pid_integral)
+ (pid_kd * derivative);
if (pwm > PWM_MAX)
pwm = PWM_MAX;
if (pwm < 0.0f)
pwm = 0.0f;
return (uint8_t)pwm;
}
void loop() {
unsigned long time_ms = millis();
if (time_ms - prev_time_ms < PERIOD_MS)
return ;
prev_time_ms = time_ms;
read_temperature();
pwm_val = update_pid(TEMPERATURE, temp_val);
digitalWrite(13, temp_val >= 50);
if (temp_val > TEMPERATURE_MAX)
pwm_val = 0;
analogWrite(PWM_PIN, pwm_val);
Serial.print(adc_val);
Serial.print("\t" );
Serial.print(temp_val);
Serial.print("\t" );
Serial.print(pwm_val);
Serial.print("\t" );
Serial.print(pid_integral);
Serial.print("\t" );
Serial.println(pid_error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment