Docx
Docx
Docx
* CS ==> D10
* SO ==> D12
* SCK ==> D13
* Vcc ==> Vcc (5v)
* Gnd ==> Gnd */
#include <SPI.h>
//We define the SPI pìns
#define MAX6675_CS 3
#define MAX6675_SO 2
#define MAX6675_SCK 4
//Pins
int PWM_pin = 11;
//Variables
float temperature_read = 0.0;
float set_temperature = 60;
float PID_error = 0;
float previous_error = 0;
float elapsedTime, Time, timePrev;
int PID_value = 0;
//PID constants
int kp = 9.1; int ki = 0.3; int kd = 1.8;
int PID_p = 0; int PID_i = 0; int PID_d = 0;
void setup() {
pinMode(PWM_pin,OUTPUT);
TCCR2B = TCCR2B & B11111000 |
B00000011; // pin 3 and 11 PWM frequency of
980.39 Hz
Time = millis();
lcd.init();
lcd.backlight();
}
void loop() {
// First we read the real value of temperature
temperature_read = readThermocouple();
//Next we calculate the error between the
setpoint and the real value
PID_error = set_temperature -
temperature_read;
//Calculate the P value
PID_p = kp * PID_error;
//Calculate the I value in a range on +-3
if(-3 < PID_error <3)
{
PID_i = PID_i + (ki * PID_error);
}
delay(300);
//lcd.clear();
lcd.setCursor(0,2);
lcd.print("PID TEMP control");
lcd.setCursor(0,3);
lcd.print("S:");
lcd.setCursor(2,3);
lcd.print(set_temperature,1);
lcd.setCursor(9,3);
lcd.print("R:");
lcd.setCursor(11,3);
lcd.print(temperature_read,1);
}
double readThermocouple() {
uint16_t v;
pinMode(MAX6675_CS, OUTPUT);
pinMode(MAX6675_SO, INPUT);
pinMode(MAX6675_SCK, OUTPUT);
digitalWrite(MAX6675_CS, LOW);
delay(1);
// Read in 16 bits,
// 15 = 0 always
// 14..2 = 0.25 degree counts MSB First
// 2 = 1 if thermocouple is open circuit
// 1..0 = uninteresting status
v = shiftIn(MAX6675_SO, MAX6675_SCK,
MSBFIRST);
v <<= 8;
v |= shiftIn(MAX6675_SO, MAX6675_SCK,
MSBFIRST);
digitalWrite(MAX6675_CS, HIGH);
if (v & 0x4)
{
// Bit 2 indicates if the thermocouple is
disconnected
return NAN;
}