Hi,
I'm trying a very simple PID-based temperature controller project.
The project relies on a solid-state relay, and DS18B20 temperature probe, and a heating pad.
I use the popular OneWire & DallasTemperature libraries.
I cannot get any reading from the probe - the program outputs -127, which means no data.
I've tried: different ports for the probe; different data-wire pull-up resistors (same resistance value, different resistors, as I thought I had fried them); different probes (all DS18B20, of course); different bread boards; and finally a probe that came with a plug-in terminal that includes the resistor. Nothing worked.
Here is the code I use - is there anything wrong with it? Thank you.
// For PID regulation
#include <PID_v1.h>
// For DS18B20 sensor
#include <OneWire.h>
#include <DallasTemperature.h>
// DS18B20 sensor is on PIN 2 of the Arduino
#define ONE_WIRE_BUS 2
// Solid state relay is on PIN 4 of the Arduino
#define RELAY_PIN 4
// Sensor objects
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// PID variables
double Setpoint, Input, Output;
int WindowSize = 5000;
unsigned long windowStartTime, lastPrintTime;
// PID tuning parameters
double Kp=65, Ki=0.71, Kd=0;
// PID object
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
// Function that controls activation or deactivation
// of the relay. The LED built into the Arduino is on when
// the relay is active, otherwise it is off.
void relay_state(bool state) {
digitalWrite(RELAY_PIN, state);
digitalWrite(LED_BUILTIN, state);
}
// Function that print temperature each second
void printTemperatureEverySec(double temp) {
if ((millis()-lastPrintTime) > 1000) {
lastPrintTime = millis();
Serial.println(temp);
}
}
// Setup function that runs once at startup
void setup()
{
// Define relay and led pins as output
pinMode(RELAY_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
// Set the relay to low state
relay_state(LOW);
Serial.begin(115200);
// Store current time in variables used by PID
// and display functions
windowStartTime = millis();
lastPrintTime = millis();
// Setpoint for the PID temperature control 40 degrees Celcius
Setpoint = 40;
// Tell the PID to range between 0 and the full window size
myPID.SetOutputLimits(0, WindowSize);
// Turn the PID on
myPID.SetMode(AUTOMATIC);
}
// Main loop function
void loop()
{
// Get the temperature from the sensor
sensors.requestTemperatures();
Input = sensors.getTempCByIndex(0);
printTemperatureEverySec(Input);
// Compute the PID
myPID.Compute();
/************************************************
* turn the output pin on/off based on pid output
************************************************/
if (millis() - windowStartTime > WindowSize)
{
//time to shift the Relay Window
windowStartTime += WindowSize;
}
if ((Output < (millis() - windowStartTime)) || (Input < 0)) {
relay_state(LOW);
}
else
relay_state(HIGH);
}