/*
* PID Voltage Regulator Example.
*
* See the accompaning circuit in VoltageRegulator.png.
* The circuit is a very poor regulator that's complex
* and nonlinear. A good example to show PID tuning.
*
* If connected correctly the LED shows the approximate
* output of the system. The brightness should respond
* to the dial. Check the serial port to see what the
* actual system values are.
*
********************************************************/
#include <FastPID.h>
#define PIN_INPUT 4
#define PIN_SETPOINT 5
#define PIN_OUTPUT 2
#define LED 18
float Kp=0.1, Ki=0.5, Kd=0, Hz=10;
int output_bits = 8;
bool output_signed = false;
FastPID myPID(Kp, Ki, Kd, Hz, output_bits, output_signed);
const int SAMPLE_NUMBER = 10;
const double BALANCE_RESISTOR = 9880.0;
const double MAX_ADC = 4095.0;
const double BETA = 3974.0;
const double ROOM_TEMP = 298.15;
const double RESISTOR_ROOM_TEMP = 10000.0;
double currentTemperature = 0;
void setup()
{
Serial.begin(9600);
pinMode(PIN_INPUT, INPUT); //Feedback sensor
pinMode(PIN_OUTPUT, OUTPUT); //PWM atuator
pinMode(PIN_SETPOINT, INPUT); //Input setpoint
}
void loop()
{
digitalWrite( LED, ( millis() % 1000 ) < 50 );
int setpoint = 300;
int feedback = 10 * pSENSOR(); //Converte a leitura do sensor para inteiro
uint32_t before, after;
before = micros();
uint8_t output = myPID.step(setpoint, feedback);
after = micros();
analogWrite(PIN_OUTPUT, output);
Serial.print(" Set: ");
Serial.print(setpoint);
Serial.print(" Sensor: ");
Serial.print(feedback);
Serial.print(" PWM: ");
Serial.println(output);
delay(100);
}
double pSENSOR()
{
double rThermistor = 0; // Holds thermistor resistance value
double tKelvin = 0; // Holds calculated temperature
double tCelsius = 0; // Hold temperature in celsius
double adcAverage = 0; // Holds the average voltage measurement
int adcSamples[SAMPLE_NUMBER]; // Array to hold each voltage measurement
for (int i = 0; i < SAMPLE_NUMBER; i++ ) { adcSamples[i] = analogRead(PIN_INPUT); delay(10); }
for (int i = 0; i < SAMPLE_NUMBER; i++ ) { adcAverage = adcSamples[i]; }
adcAverage /= SAMPLE_NUMBER;
rThermistor = BALANCE_RESISTOR * ( (MAX_ADC / adcAverage) - 1);
tKelvin = (BETA * ROOM_TEMP) / (BETA + (ROOM_TEMP * log(rThermistor / RESISTOR_ROOM_TEMP)));
tCelsius = tKelvin - 273.15; // convert kelvin to celsius
tCelsius = tCelsius * (-1); //Por algum motivo é necessário tornar a tCelsius positivo
return tCelsius; // Return the temperature in Celsius
}