|
| 1 | +#include <OneWire.h> |
| 2 | +#include <DallasTemperature.h> |
| 3 | +#include <Arduino.h> |
| 4 | + |
| 5 | +// GPIO where the DS18B20 is connected to |
| 6 | +const int oneWireBus = GPIO_NUM_25; |
| 7 | + |
| 8 | + |
| 9 | + int8_t LASER_1 = GPIO_NUM_12; |
| 10 | + int8_t LASER_2 = GPIO_NUM_4; |
| 11 | + int8_t LASER_3 = GPIO_NUM_2; |
| 12 | + |
| 13 | + |
| 14 | +// Setup a oneWire instance to communicate with any OneWire devices |
| 15 | +OneWire oneWire(oneWireBus); |
| 16 | + |
| 17 | +// Pass our oneWire reference to Dallas Temperature sensor |
| 18 | +DallasTemperature sensors(&oneWire); |
| 19 | + |
| 20 | +// PID constants |
| 21 | +const float Kp = 2.0; |
| 22 | +const float Ki = 0.5; |
| 23 | +const float Kd = 1.0; |
| 24 | + |
| 25 | +// PID variables |
| 26 | +float previousError = 0; |
| 27 | +float integral = 0; |
| 28 | + |
| 29 | +// Desired temperature |
| 30 | +const float setpoint = 30.0; // for example, 50°C |
| 31 | + |
| 32 | +// LEDC variables |
| 33 | +const int freq = 5000; |
| 34 | +const int ledChannel = 0; |
| 35 | +const int resolution = 8; |
| 36 | +const int heaterPin = 27; // PWM pin connected to the heater |
| 37 | + |
| 38 | +// Get the current temperature |
| 39 | +// Here you'll want to replace this with your actual temperature reading logic |
| 40 | +float getTemperature() { |
| 41 | + // Dummy implementation, replace with your sensor's logic |
| 42 | + sensors.requestTemperatures(); |
| 43 | + return sensors.getTempCByIndex(0); |
| 44 | +} |
| 45 | + |
| 46 | +void setup() { |
| 47 | + Serial.begin(115200); |
| 48 | + sensors.begin(); |
| 49 | + // Setup LEDC for heater control |
| 50 | + ledcSetup(ledChannel, freq, resolution); |
| 51 | + ledcAttachPin(heaterPin, ledChannel); |
| 52 | +} |
| 53 | + |
| 54 | +void loop() { |
| 55 | + |
| 56 | + float currentTemperature = getTemperature(); |
| 57 | + float error = setpoint - currentTemperature; |
| 58 | + |
| 59 | + integral += error; |
| 60 | + float derivative = error - previousError; |
| 61 | + |
| 62 | + // Calculate PID output |
| 63 | + float output = Kp * error + Ki * integral + Kd * derivative; |
| 64 | + |
| 65 | + // Ensure output is within the range [0, 255] for the 8-bit PWM resolution |
| 66 | + output = constrain(output, 0, 255); |
| 67 | + |
| 68 | + // Set the PWM signal |
| 69 | + ledcWrite(ledChannel, (int)output); |
| 70 | + |
| 71 | + // Update the previous error |
| 72 | + previousError = error; |
| 73 | + |
| 74 | + // Print values for debugging (optional) |
| 75 | + Serial.print("Current Temperature: "); Serial.print(currentTemperature); |
| 76 | + Serial.print(" °C | PWM Output: "); Serial.println(output); |
| 77 | + |
| 78 | + delay(1000); |
| 79 | +} |
0 commit comments