#include <PID_v1.h>
#include <U8g2lib.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Encoder.h>
// Pin Definitions
#define HEATING_ELEMENT_PIN 6 // Example pin for the heating element
#define BUTTON_PIN 7 // Pin for the on-off button
#define DS18B20_DATA_PIN 5 // Digital pin connected to DQ of DS18B20 sensor (Arduino Nano pin D5)
// Encoder Pin Definitions
#define ENCODER_PIN1 A0 // Encoder pin 1
#define ENCODER_PIN2 A1 // Encoder pin 2
// PID Variables
double setpoint, input, output;
double Kp = 2, Ki = 5, Kd = 1; // PID Tuning Parameters
PID myPID(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);
// Encoder Setup
Encoder encoder(ENCODER_PIN1, ENCODER_PIN2);
int lastEncoderPos = -999;
int encoderPos = 0;
// Display Setup (Change according to your specific OLED display)
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); // OLED display object
// DS18B20 sensor setup
OneWire oneWire(DS18B20_DATA_PIN); // Initialize a OneWire instance
DallasTemperature sensors(&oneWire); // Pass OneWire reference to DallasTemperature library
// Other Variables
bool heatingOn = false;
void setup() {
// Initialize Serial communication
Serial.begin(9600);
// Initialize heating element pin and button pin
pinMode(HEATING_ELEMENT_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Set the initial setpoint temperature
setpoint = 200; // Default setpoint temperature
// Initialize PID
myPID.SetMode(AUTOMATIC);
// Initialize Encoder pins
// ... (Encoder pin initialization)
// Initialize OLED display
u8g2.begin();
u8g2.setFont(u8g2_font_ncenB08_tr); // Choose font size and type
// Start DS18B20 sensor communication
sensors.begin();
displayTemperature(); // Display initial temperature
}
void loop() {
encoderPos = encoder.read() / 4; // Divide by 4 for finer adjustment
if (encoderPos != lastEncoderPos) {
setpoint = map(encoderPos, 0, 100, 190, 210);
displayTemperature();
lastEncoderPos = encoderPos;
}
input = readTemperatureSensor(); // Function to read temperature from sensor
myPID.Compute();
if (digitalRead(BUTTON_PIN) == LOW) {
heatingOn = !heatingOn; // Toggle heating element state
delay(250); // Debounce delay for the button press
}
if (heatingOn) {
analogWrite(HEATING_ELEMENT_PIN, output);
} else {
analogWrite(HEATING_ELEMENT_PIN, 0);
}
}
void displayTemperature() {
// Clear display and print the setpoint temperature
u8g2.firstPage();
do {
u8g2.setCursor(0, 20);
u8g2.print("Setpoint Temp:");
u8g2.setCursor(0, 40);
u8g2.print(setpoint);
u8g2.print(" C");
} while (u8g2.nextPage());
}
double readTemperatureSensor() {
sensors.requestTemperatures(); // Send the command to get temperature readings
double tempC = sensors.getTempCByIndex(0); // Get temperature in Celsius
return tempC; // Return temperature value
}
Loading
ds18b20
ds18b20