#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
// پایههای رجیستر GPADC و GPIO
#define GPADC_BASE 0x02009000
#define GP_SR_CON 0x0000
#define GP_CTRL 0x0004
#define GP_CS_EN 0x0008
#define GP_DATA_INTS 0x0038
#define GP_CH0_DATA 0x0080
#define ADC_VREF 1.8
#define VCC 3.3
#define ADC_MAX 4095.0
#define R1 10000.0
#define R0 10000.0
#define T0 298.15
#define B 3950.0
#define GPIO_BASE 0x02000000
#define PB_CFG0 0x0030
#define PB_DAT 0x0040
#define PE_CFG0 0x00C0
#define PE_DAT 0x00D0
#define PB5_SHIFT 20
#define PB5_MASK (1u << 5)
#define PE0_SHIFT 0
#define PE0_MASK (1u << 0)
#define FUNC_OUTPUT 0x1
#define PWM_PIN PB5_MASK
#define MODE_PIN PE0_MASK
static volatile uint32_t *gpio;
static volatile uint32_t *gpadc;
static volatile int pwm_duty_cycle = 0;
static volatile int mode = 0;
static volatile double shared_temperature = 0.0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// توابع تایمر
static inline uint32_t read_cntfrq(void) {
uint32_t v;
asm volatile("mrc p15, 0, %0, c14, c0, 0" : "=r"(v));
return v;
}
static inline uint64_t read_cntpct(void) {
uint32_t lo, hi;
asm volatile("mrrc p15, 0, %0, %1, c14" : "=r"(lo), "=r"(hi));
return ((uint64_t)hi << 32) | lo;
}
// ساختار فیلتر کالمن
typedef struct {
double estimate;
double errorEstimate;
double processNoise;
double measurementNoise;
} KalmanFilter;
void initKalman(KalmanFilter *kf, double processNoise, double measurementNoise) {
kf->processNoise = processNoise;
kf->measurementNoise = measurementNoise;
}
double kalmanUpdate(KalmanFilter *kf, double measurement) {
double predictedEstimate = kf->estimate;
double predictedError = kf->errorEstimate + kf->processNoise;
double kalmanGain = predictedError / (predictedError + kf->measurementNoise);
kf->estimate = predictedEstimate + kalmanGain * (measurement - predictedEstimate);
kf->errorEstimate = (1.0 - kalmanGain) * predictedError;
return kf->estimate;
}
// ساختار PID
typedef struct {
double Kp, Ki, Kd;
double prevError;
double integral;
double derivative;
double maxOutput;
} PID;
void initPID(PID *pid, double kp, double ki, double kd, double max_output) {
pid->Kp = kp;
pid->Ki = ki;
pid->Kd = kd;
pid->prevError = 0;
pid->integral = 0;
pid->derivative = 0;
pid->maxOutput = max_output;
}
// ساختار جدید برای محدوده ضرایب PID
typedef struct {
double Kp_min, Kp_max;
double Ki_min, Ki_max;
double Kd_min, Kd_max;
} PIDBounds;
// ساختار برای ذخیره معیارهای عملکرد
typedef struct {
double rise_time; // زمان صعود (ثانیه)
double overshoot; // overshoot (درجه)
double steady_state_error; // خطای حالت ماندگار (درجه)
} PerformanceMetrics;
// توابع اولویت و اتصال به هسته
void set_realtime_priority(void) {
struct sched_param sp = { .sched_priority = 90 };
if (sched_setscheduler(0, SCHED_FIFO, &sp))
perror("خطا در تنظیم اولویت بلادرنگ");
}
void set_affinity(int cpu) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0)
perror("خطا در اتصال به هسته");
}
// توابع دسترسی به رجیستر
static inline void reg_write(volatile uint32_t *base, uint32_t off, uint32_t clr_mask, uint32_t set_mask) {
volatile uint32_t *addr = base + (off >> 2);
uint32_t val = *addr;
val = (val & ~clr_mask) | set_mask;
*addr = val;
}
static inline uint32_t gpadc_read(uint32_t off) {
return (volatile uint32_t)(gpadc + (off>>2));
}
static inline void gpadc_write(uint32_t off, uint32_t val) {
(volatile uint32_t)(gpadc + (off>>2)) = val;
}
int readGPADCRaw() {
while (!(gpadc_read(GP_DATA_INTS) & 0x1));
gpadc_write(GP_DATA_INTS, 1);
return gpadc_read(GP_CH0_DATA) & 0x0FFF;
}
void measure_gpadc_time(void) {
const uint32_t cnt_hz = read_cntfrq();
const int num_trials = 100;
uint64_t total_ticks = 0;
for (int i = 0; i < num_trials; i++) {
uint64_t start = read_cntpct();
int raw = readGPADCRaw();
uint64_t end = read_cntpct();
total_ticks += (end - start);
}
double avg_ticks = (double)total_ticks / num_trials;
double avg_time_us = (avg_ticks / cnt_hz) * 1e6;
printf("میانگین زمان اجرای readGPADCRaw: %.2f میکروثانیه\n", avg_time_us);
}
void setupPins() {
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd < 0) { perror("open /dev/mem"); exit(1); }
size_t pagesz = (size_t)sysconf(_SC_PAGESIZE);
gpio = mmap(NULL, pagesz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO_BASE);
close(fd);
if (gpio == MAP_FAILED) { perror("mmap"); exit(1); }
reg_write(gpio, PB_CFG0, 0xFu << PB5_SHIFT, FUNC_OUTPUT << PB5_SHIFT);
reg_write(gpio, PE_CFG0, 0xFu << PE0_SHIFT, FUNC_OUTPUT << PE0_SHIFT);
}
void initGPADC() {
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd < 0) { perror("open /dev/mem for GPADC"); exit(1); }
size_t pagesz = sysconf(_SC_PAGESIZE);
gpadc = mmap(NULL, pagesz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPADC_BASE);
close(fd);
if (gpadc == MAP_FAILED) { perror("mmap GPADC"); exit(1); }
gpadc_write(GP_SR_CON, (0x17 << 16) | 0x9);
gpadc_write(GP_CS_EN, 0x1);
uint32_t ctrl = gpadc_read(GP_CTRL);
ctrl &= ~(0x3 << 18);
ctrl |= (0x2 << 18) | (1 << 16);
gpadc_write(GP_CTRL, ctrl);
}
double read_temperature() {
double raw = readGPADCRaw();
double adc_voltage = (raw * ADC_VREF) / ADC_MAX;
double R_therm = R1 * (adc_voltage / (VCC - adc_voltage));
double lnR = log(R_therm / R0);
double T_kelvin = 1.0 / ((1.0 / T0) + (1.0 / B) * lnR);
return T_kelvin - 273.15;
}
double read_filtered_temperature(KalmanFilter *kf) {
pthread_mutex_lock(&mutex);
double rawTemp = shared_temperature;
pthread_mutex_unlock(&mutex);
return kalmanUpdate(kf, rawTemp);
}
// تابع PWM
void* pwm_thread(void* arg) {
set_affinity(0);
set_realtime_priority();
const uint32_t cnt_hz = read_cntfrq();
const uint64_t period = cnt_hz / 25000;
volatile uint32_t *pb_dat = gpio + (PB_DAT >> 2);
volatile uint32_t *pe_dat = gpio + (PE_DAT >> 2);
int duty = 0;
int current_mode = 0;
uint64_t t = read_cntpct();
while (1) {
pthread_mutex_lock(&mutex);
duty = pwm_duty_cycle;
current_mode = mode;
pthread_mutex_unlock(&mutex);
uint64_t high_ticks = (period * duty) / 100;
uint64_t low_ticks = period - high_ticks;
if (duty > 0) {
*pb_dat |= PWM_PIN;
}
uint64_t target = t + high_ticks;
while (read_cntpct() < target);
*pb_dat &= ~PWM_PIN;
target = t + period;
pthread_mutex_lock(&mutex);
shared_temperature = read_temperature();
pthread_mutex_unlock(&mutex);
if (current_mode) {
*pe_dat &= ~MODE_PIN;
} else {
*pe_dat |= MODE_PIN;
}
while (read_cntpct() < target);
t += period;
}
return NULL;
}
// تابع محاسبه PID
double computePID(PID *pid, double setpoint, double measured, double dt, double minOutput, double maxOutput, int invertError, double feedforward) {
double error = invertError ? (measured - setpoint) : (setpoint - measured);
pid->integral += error * dt;
double raw_derivative = (error - pid->prevError) / dt;
double alpha = 0.8;
pid->derivative = alpha * raw_derivative + (1 - alpha) * pid->derivative;
double output = pid->Kp * error + pid->Ki * pid->integral + pid->Kd * pid->derivative + feedforward;
if (output > maxOutput) {
output = maxOutput;
if (error > 0) pid->integral -= error * dt;
} else if (output < minOutput) {
output = minOutput;
if (error < 0) pid->integral -= error * dt;
}
pid->prevError = error;
return output;
}
// فیدفوروارد
double calculate_feedforward(double targetTemp, double currentTemp) {
double k = 0.3; // ضریب تجربی - قابل تنظیم با آزمایش
double bias = 0.15; // بایاس تجربی - قابل تنظیم با آزمایش
double feedforward ;
if (targetTemp < 30) {
feedforward = k * (targetTemp - currentTemp) + bias;
} else if (targetTemp < 50) {
feedforward = 2k * (targetTemp - currentTemp) + bias;
} else {
feedforward = 3k * (targetTemp - currentTemp) + bias;
}
return feedforward;
}
// تابع timespec_add (انتقال به اینجا برای جلوگیری از خطای implicit declaration)
static inline void timespec_add(struct timespec *res, const struct timespec *a, const struct timespec *b) {
res->tv_sec = a->tv_sec + b->tv_sec;
res->tv_nsec = a->tv_nsec + b->tv_nsec;
if (res->tv_nsec >= 1000000000L) {
res->tv_sec++;
res->tv_nsec -= 1000000000L;
}
}
// تابع جدید برای تنظیم خودکار ضرایب PID
void autoTunePID(PID *pid, PerformanceMetrics *metrics, PIDBounds *bounds, double targetTemp, double currentTemp, double dt) {
const double rise_time_threshold = 35.0; // ثانیه
const double overshoot_threshold = 0.25; // درجه
const double steady_state_error_threshold = 0.5; // درجه
double error = fabs(targetTemp - currentTemp);
if (metrics->rise_time > rise_time_threshold) {
pid->Kp = fmin(pid->Kp * 1.05, bounds->Kp_max);
pid->Ki = fmin(pid->Ki * 1.05, bounds->Ki_max);
}
if (metrics->overshoot > overshoot_threshold) {
pid->Kd = fmin(pid->Kd * 1.1, bounds->Kd_max);
pid->Kp = fmax(pid->Kp * 0.95, bounds->Kp_min);
pid->Ki = fmax(pid->Ki * 0.95, bounds->Ki_min);
}
if (metrics->steady_state_error > steady_state_error_threshold && metrics->steady_state_error > 0) {
pid->Ki = fmin(pid->Ki * 1.05, bounds->Ki_max);
}
}
// تابع reachTemperature
void reachTemperature(int stageNumber, double targetTemp, int holdTimeSeconds, double pwm_min, double pwm_max,
PID *pid_heat, PID *pid_cool, PID *pid_first, double firstMeas, KalmanFilter *kf, PIDBounds *bounds) {
const double dt = 0.125;
const double stability_threshold = 0.55;
const double reset_threshold = 4;
const double coolingThreshold = 3;
struct timespec start_time, next_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
clock_gettime(CLOCK_MONOTONIC, &next_time);
long stable_ms = 0;
long hold_ms = holdTimeSeconds * 1000;
double max_temp = firstMeas;
int rise_time_reached = 0;
double rise_time = 0.0;
double steady_state_error_sum = 0.0;
int steady_state_count = 0;
PerformanceMetrics metrics = {0.0, 0.0, 0.0};
printf("\n--- شروع مرحله %d: هدف = %.1f°C ---\n", stageNumber, targetTemp);
while (stable_ms < hold_ms) {
timespec_add(&next_time, &next_time, &(struct timespec){0, (long)(dt * 1e9)});
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next_time, NULL);
double currentTemp = read_filtered_temperature(kf);
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
double elapsed_time = (now.tv_sec - start_time.tv_sec) + (now.tv_nsec - start_time.tv_nsec) / 1e9;
if (!rise_time_reached && currentTemp >= targetTemp * 0.8) {
rise_time = elapsed_time;
rise_time_reached = 1;
}
if (currentTemp > max_temp) {
max_temp = currentTemp;
}
metrics.overshoot = fmax(0.0, max_temp - targetTemp);
double error = targetTemp - currentTemp;
if (fabs(error) <= stability_threshold) {
steady_state_error_sum += fabs(error);
steady_state_count++;
metrics.steady_state_error = steady_state_count > 0 ? steady_state_error_sum / steady_state_count : 0.0;
}
metrics.rise_time = rise_time_reached ? rise_time : elapsed_time;
autoTunePID(pid_heat, &metrics, bounds, targetTemp, currentTemp, dt);
int isCooling = (currentTemp > targetTemp + coolingThreshold);
int dutyCycle = 0;
int currentMode = 0;
double feedforward = calculate_feedforward(targetTemp, currentTemp);
if (!isCooling && targetTemp > firstMeas) {
currentMode = 1;
double pidOutput = computePID(pid_heat, targetTemp, currentTemp, dt, pwm_min, pwm_max, 0, feedforward);
dutyCycle = (int)pidOutput;
} else if (isCooling && targetTemp > firstMeas) {
currentMode = 0;
double pidOutput = computePID(pid_cool, targetTemp, currentTemp, dt, pwm_min, pwm_max, 1, feedforward);
dutyCycle = 0.4 * (int)pidOutput;
} else if (targetTemp < firstMeas) {
currentMode = 0;
double pidOutput = computePID(pid_cool, targetTemp, currentTemp, dt, pwm_min, pwm_max, 1, feedforward);
dutyCycle = (int)pidOutput;
}
if (dutyCycle > pwm_max) dutyCycle = pwm_max;
if (dutyCycle < pwm_min) dutyCycle = pwm_min;
pthread_mutex_lock(&mutex);
pwm_duty_cycle = dutyCycle;
mode = currentMode;
pthread_mutex_unlock(&mutex);
if (fabs(error) <= stability_threshold) {
stable_ms += (long)(dt * 1000);
} else if (fabs(error) > reset_threshold) {
stable_ms = 0;
}
static double acc_print = 0;
acc_print += dt;
if (acc_print >= 1) {
printf("مرحله %d - %s: دما=%.2f°C, خطا=%.2f°C, PWM=%d%%, حالت=%s, پایدار=%dms, Kp=%.2f, Ki=%.3f, Kd=%.3f\n",
stageNumber, isCooling ? "سرمایش" : "گرمایش",
currentTemp, error, dutyCycle, currentMode ? "گرمایش" : "سرمایش",
stable_ms, pid_heat->Kp, pid_heat->Ki, pid_heat->Kd);
acc_print = 0;
}
}
pthread_mutex_lock(&mutex);
pwm_duty_cycle = 0;
mode = 0;
pthread_mutex_unlock(&mutex);
printf("--- پایان مرحله %d: دما نهایی = %.2f°C ---\n", stageNumber, shared_temperature);
}
// تابع main
int main() {
int numStages;
double pwm_min = 0.0;
double pwm_max = 50.0;
double Q = 0.07, R = 0.68;
double Kp_heat, Ki_heat, Kd_heat;
PIDBounds bounds = {
.Kp_min = 0.04, .Kp_max = 0.3,
.Ki_min = 0.15, .Ki_max = 0.3,
.Kd_min = 5, .Kd_max = 6
};
setupPins();
initGPADC();
measure_gpadc_time();
fprintf(stderr, "تعداد مراحل را وارد کنید: ");
scanf("%d", &numStages);
double targetTemps[numStages];
int holdTimes[numStages];
for (int i = 0; i < numStages; i++) {
fprintf(stderr, "دمای هدف برای مرحله %d (°C): ", i + 1);
scanf("%lf", &targetTemps[i]);
fprintf(stderr, "زمان نگهداری برای مرحله %d (ثانیه): ", i + 1);
scanf("%d", &holdTimes[i]);
}
fprintf(stderr, "ضریب Kp برای گرمایش: ");
scanf("%lf", &Kp_heat);
fprintf(stderr, "ضریب Ki برای گرمایش: ");
scanf("%lf", &Ki_heat);
fprintf(stderr, "ضریب Kd برای گرمایش: ");
scanf("%lf", &Kd_heat);
fprintf(stderr, "حداقل و حداکثر Kp (مثل 1.0 5.0): ");
scanf("%lf %lf", &bounds.Kp_min, &bounds.Kp_max);
fprintf(stderr, "حداقل و حداکثر Ki (مثل 0.01 0.1): ");
scanf("%lf %lf", &bounds.Ki_min, &bounds.Ki_max);
fprintf(stderr, "حداقل و حداکثر Kd (مثل 0.05 0.3): ");
scanf("%lf %lf", &bounds.Kd_min, &bounds.Kd_max);
double firstMeas = read_temperature();
KalmanFilter kf;
initKalman(&kf, Q, R);
kf.estimate = firstMeas;
kf.errorEstimate = 1.0;
PID pid_heat, pid_cool, pid_first;
initPID(&pid_heat, Kp_heat, Ki_heat, Kd_heat, pwm_max);
initPID(&pid_cool, 0.1, 0.25, 4.1, pwm_max);
initPID(&pid_first, 1.5, 0.1, 8, pwm_max);
pthread_t pwm_tid;
if (pthread_create(&pwm_tid, NULL, pwm_thread, NULL) != 0) {
perror("خطا در ایجاد رشته PWM");
return 1;
}
set_affinity(1);
for (int i = 0; i < numStages; i++) {
reachTemperature(i + 1, targetTemps[i], holdTimes[i], pwm_min, pwm_max,
&pid_heat, &pid_cool, &pid_first, firstMeas, &kf, &bounds);
}
pthread_cancel(pwm_tid);
pthread_join(pwm_tid, NULL);
printf("پایان فرآیند ترمال سایکلر\n");
return 0;
}
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <errno.h> // For errno
// پایههای رجیستر GPADC و GPIO
#define GPADC_BASE 0x02009000
#define GP_SR_CON 0x0000
#define GP_CTRL 0x0004
#define GP_CS_EN 0x0008
#define GP_DATA_INTS 0x0038
#define GP_CH0_DATA 0x0080
// پارامترهای ترمیستور
#define ADC_VREF 1.8
#define VCC 3.3
#define ADC_MAX 4095.0 // 12-bit ADC
#define R1 10000.0 // مقاومت سری R1
#define R0 10000.0 // مقاومت ترمیستور در دمای مرجع
#define T0 298.15 // دمای مرجع (25°C) بر حسب کلوین
#define B 3950.0 // ضریب بتا ترمیستور
// پایههای GPIO
#define GPIO_BASE 0x02000000
#define PB_CFG0 0x0030 // Port B config
#define PB_DAT 0x0040 // Port B data
#define PE_CFG0 0x00C0 // Port E config
#define PE_DAT 0x00D0 // Port E data
#define PB5_SHIFT 20 // Shift for PB5 (PWM)
#define PB5_MASK (1u << 5) // Mask for PB5
#define PE0_SHIFT 0 // Shift for PE0 (Mode: Heat/Cool)
#define PE0_MASK (1u << 0) // Mask for PE0
#define FUNC_OUTPUT 0x1 // GPIO function for output
#define PWM_PIN PB5_MASK // Pin used for PWM output (Heater power)
#define MODE_PIN PE0_MASK // Pin used for Heat/Cool mode selection
// سختافزار و متغیرهای مشترک
static volatile uint32_t *gpio = NULL;
static volatile uint32_t *gpadc = NULL;
static volatile int pwm_duty_cycle = 0; // Shared PWM duty cycle (0-100)
static volatile int mode = 0; // Shared mode (1: Heat, 0: Cool)
static volatile double shared_temperature = 0.0; // Shared temperature reading
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Mutex for shared variables
// توابع تایمر ARM Generic Timer
// خواندن فرکانس شمارنده (شناخته شده در زمان کامپایل یا از رجیستر)
static inline uint32_t read_cntfrq(void) {
uint32_t v;
// MRC p15, 0, <Rt>, c14, c0, 0 reads CNTFRQ
asm volatile("mrc p15, 0, %0, c14, c0, 0" : "=r"(v));
return v;
}
// خواندن مقدار شمارنده فیزیکی
static inline uint64_t read_cntpct(void) {
uint32_t lo, hi;
// MRRC p15, 0, <Rt1>, <Rt2>, c14 reads CNTPCT
asm volatile("mrrc p15, 0, %0, %1, c14" : "=r"(lo), "=r"(hi));
return ((uint64_t)hi << 32) | lo;
}
// ساختار فیلتر کالمن
typedef struct {
double estimate;
double errorEstimate;
double processNoise;
double measurementNoise;
} KalmanFilter;
void initKalman(KalmanFilter *kf, double initialEstimate, double initialError, double processNoise, double measurementNoise) {
kf->estimate = initialEstimate;
kf->errorEstimate = initialError;
kf->processNoise = processNoise;
kf->measurementNoise = measurementNoise;
}
double kalmanUpdate(KalmanFilter *kf, double measurement) {
// Prediction update
double predictedEstimate = kf->estimate; // X_k|k-1 = X_k-1|k-1
double predictedError = kf->errorEstimate + kf->processNoise; // P_k|k-1 = P_k-1|k-1 + Q
// Measurement update
double kalmanGain = predictedError / (predictedError + kf->measurementNoise); // K_k = P_k|k-1 / (P_k|k-1 + R)
kf->estimate = predictedEstimate + kalmanGain * (measurement - predictedEstimate); // X_k|k = X_k|k-1 + K_k * (Z_k - X_k|k-1)
kf->errorEstimate = (1.0 - kalmanGain) * predictedError; // P_k|k = (1 - K_k) * P_k|k-1
return kf->estimate;
}
// ساختار PID
typedef struct {
double Kp, Ki, Kd;
double prevError;
double integral;
double derivative;
double integralLimit; // Limit for integral windup
} PID;
void initPID(PID *pid, double kp, double ki, double kd, double integralLimit) {
pid->Kp = kp;
pid->Ki = ki;
pid->Kd = kd;
pid->prevError = 0;
pid->integral = 0;
pid->derivative = 0;
pid->integralLimit = integralLimit;
}
// تابع ریست کردن حالت PID (برای شروع مرحله جدید یا تغییر حالت)
void resetPID(PID *pid) {
pid->prevError = 0;
pid->integral = 0;
pid->derivative = 0;
}
// ساختار جدید برای محدوده ضرایب PID (برای auto-tuning)
typedef struct {
double Kp_min, Kp_max;
double Ki_min, Ki_max;
double Kd_min, Kd_max;
} PIDBounds;
// ساختار برای ذخیره معیارهای عملکرد
typedef struct {
double rise_time; // زمان صعود (ثانیه) - تا رسیدن به درصدی از هدف
double overshoot; // overshoot (درجه) - حداکثر تجاوز از هدف
double steady_state_error_abs_avg; // میانگین خطای مطلق در حالت ماندگار
int rise_time_reached; // فلگ برای اینکه آیا زمان صعود ثبت شده است
double max_temp_during_stage; // حداکثر دمای ثبت شده در مرحله
} PerformanceMetrics;
void resetPerformanceMetrics(PerformanceMetrics *metrics, double initialTemp) {
metrics->rise_time = 0.0;
metrics->overshoot = 0.0;
metrics->steady_state_error_abs_avg = 0.0;
metrics->rise_time_reached = 0;
metrics->max_temp_during_stage = initialTemp;
}
// توابع اولویت و اتصال به هسته
void set_realtime_priority(int policy, int priority) {
struct sched_param sp = { .sched_priority = priority };
if (sched_setscheduler(0, policy, &sp)) {
perror("خطا در تنظیم اولویت بلادرنگ");
// Continue execution, just log the error
}
}
void set_affinity(int cpu) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0) {
perror("خطا در اتصال به هسته");
// Continue execution, just log the error
}
}
// توابع دسترسی به رجیستر GPIO و GPADC
static inline void reg_write(volatile uint32_t *base, uint32_t off, uint32_t clr_mask, uint32_t set_mask) {
volatile uint32_t *addr = base + (off >> 2);
// Use barrier to ensure previous memory accesses complete before this read
__sync_synchronize();
uint32_t val = *addr;
val = (val & ~clr_mask) | set_mask;
// Use barrier to ensure the write completes before subsequent memory accesses
__sync_synchronize();
*addr = val;
}
static inline uint32_t reg_read(volatile uint32_t *base, uint32_t off) {
volatile uint32_t *addr = base + (off >> 2);
__sync_synchronize();
return *addr;
}
int readGPADCRaw() {
// Wait for data interrupt flag for channel 0
// Add timeout mechanism for robustness in a real system
uint64_t start_time = read_cntpct();
const uint64_t timeout_ticks = read_cntfrq() / 100; // Timeout after 10ms
while (!(reg_read(gpadc, GP_DATA_INTS) & 0x1)) {
if (read_cntpct() - start_time > timeout_ticks) {
fprintf(stderr, "GPADC timeout waiting for data!\n");
return -1; // Indicate error
}
}
// Clear interrupt flag
reg_write(gpadc, GP_DATA_INTS, 0xFFFFFFFF, 0x1);
// Read data (only lower 12 bits are valid)
return reg_read(gpadc, GP_CH0_DATA) & 0x0FFF;
}
void measure_gpadc_time(void) {
const uint32_t cnt_hz = read_cntfrq();
const int num_trials = 100;
uint64_t total_ticks = 0;
for (int i = 0; i < num_trials; i++) {
uint64_t start = read_cntpct();
int raw = readGPADCRaw();
if (raw == -1) { // Handle timeout
fprintf(stderr, "Skipping timing trial due to ADC read error\n");
continue;
}
uint64_t end = read_cntpct();
total_ticks += (end - start);
}
if (total_ticks > 0) {
double avg_ticks = (double)total_ticks / num_trials;
double avg_time_us = (avg_ticks / cnt_hz) * 1e6;
printf("میانگین زمان اجرای readGPADCRaw (%d trials): %.2f میکروثانیه\n", num_trials, avg_time_us);
} else {
printf("GPADC timing measurement failed.\n");
}
}
void setupHardware() {
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd < 0) { perror("open /dev/mem"); exit(EXIT_FAILURE); }
size_t pagesz = (size_t)sysconf(_SC_PAGESIZE);
// Map GPIO
gpio = mmap(NULL, pagesz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPIO_BASE);
if (gpio == MAP_FAILED) { perror("mmap GPIO"); close(fd); exit(EXIT_FAILURE); }
// Map GPADC
gpadc = mmap(NULL, pagesz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, GPADC_BASE);
if (gpadc == MAP_FAILED) { perror("mmap GPADC"); munmap((void*)gpio, pagesz); close(fd); exit(EXIT_FAILURE); }
close(fd); // /dev/mem can be closed after mmap
// Configure GPIO pins
// PB5: Output for PWM
reg_write(gpio, PB_CFG0, 0xFu << PB5_SHIFT, FUNC_OUTPUT << PB5_SHIFT);
// PE0: Output for Mode (Heat/Cool)
reg_write(gpio, PE_CFG0, 0xFu << PE0_SHIFT, FUNC_OUTPUT << PE0_SHIFT);
// Initialize GPADC
// Sample time config, enable clock etc. (Registers specific to the chip)
// These values (0x17, 0x9, 0x2, 0x1) are taken from the original code - assuming they are correct for the target hardware.
reg_write(gpadc, GP_SR_CON, 0, (0x17 << 16) | 0x9); // Set sample rate and control
reg_write(gpadc, GP_CS_EN, 0, 0x1); // Enable ADC channel 0
uint32_t ctrl = reg_read(gpadc, GP_CTRL);
ctrl &= ~(0x3 << 18); // Clear bits 19:18
ctrl |= (0x2 << 18) | (1 << 16); // Set ADC clock source/prescaler and enable continuous mode? (Assuming 1<<16 is enable)
reg_write(gpadc, GP_CTRL, 0, ctrl);
// Initial state: Heater Off, Cooler Off (assuming mode=0, duty=0 is safe/off state)
pthread_mutex_lock(&mutex);
pwm_duty_cycle = 0;
mode = 0; // Mode 0 = Cooler? (Heater Off?)
// Set initial GPIO state
reg_write(gpio, PB_DAT, PWM_PIN, 0); // PB5 low
reg_write(gpio, PE_DAT, MODE_PIN, 0); // PE0 low
pthread_mutex_unlock(&mutex);
printf("Hardware setup complete.\n");
}
void cleanupHardware() {
if (gpio != MAP_FAILED && gpio != NULL) {
// Ensure pins are set to a safe state (e.g., low output or input) before unmapping
if (gpio) {
reg_write(gpio, PB_DAT, PWM_PIN, 0); // PB5 low
reg_write(gpio, PE_DAT, MODE_PIN, 0); // PE0 low
}
munmap((void*)gpio, sysconf(_SC_PAGESIZE));
gpio = NULL;
}
if (gpadc != MAP_FAILED && gpadc != NULL) {
// Disable ADC? (No specific register shown for disable, rely on cleanup)
munmap((void*)gpadc, sysconf(_SC_PAGESIZE));
gpadc = NULL;
}
printf("Hardware cleanup complete.\n");
}
double read_temperature_thermistor() {
int raw = readGPADCRaw();
if (raw == -1) return shared_temperature; // Return last known good value on error
// Ensure raw value is within valid ADC range
if (raw < 0 || raw > ADC_MAX) {
fprintf(stderr, "Invalid raw ADC value: %d\n", raw);
return shared_temperature; // Return last known good value
}
// Voltage across thermistor
double adc_voltage = (raw * ADC_VREF) / ADC_MAX;
// Avoid division by zero or negative voltage if VCC is less than adc_voltage
if (VCC - adc_voltage <= 0) {
fprintf(stderr, "Invalid voltage calculation for thermistor.\n");
return shared_temperature; // Return last known good value
}
// Resistance of thermistor: R_therm = R1 * (V_therm / (VCC - V_therm))
double R_therm = R1 * (adc_voltage / (VCC - adc_voltage));
// Ensure R_therm is positive and non-zero for log
if (R_therm <= 0) {
fprintf(stderr, "Invalid thermistor resistance: %.2f\n", R_therm);
return shared_temperature; // Return last known good value
}
// Temperature using Beta parameter equation
// 1/T = 1/T0 + (1/B) * ln(R_therm / R0)
double lnR = log(R_therm / R0);
double T_kelvin = 1.0 / ((1.0 / T0) + (1.0 / B) * lnR);
// Convert Kelvin to Celsius
return T_kelvin - 273.15;
}
// تابع PWM Thread
void* pwm_thread(void* arg) {
// This thread should be high priority and pinned to a core for predictable timing
set_affinity(0);
set_realtime_priority(SCHED_FIFO, 95); // Use a higher priority than control thread
const uint32_t cnt_hz = read_cntfrq();
const double pwm_freq_hz = 25000.0; // 25 kHz PWM frequency
const uint64_t period_ticks = cnt_hz / pwm_freq_hz;
volatile uint32_t *pb_dat = gpio + (PB_DAT >> 2);
volatile uint32_t *pe_dat = gpio + (PE_DAT >> 2);
int duty = 0;
int current_mode = 0;
uint64_t next_period_start = read_cntpct();
printf("PWM thread started on CPU %d with priority %d.\n", sched_getcpu(), sched_getparam(0, NULL)->sched_priority);
while (1) {
// Wait for the start of the next PWM period
// Use clock_nanosleep for better accuracy in real-time contexts
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
uint64_t current_ticks = read_cntpct();
long long diff_ticks = next_period_start - current_ticks;
if (diff_ticks > 0) {
// Convert ticks to nanoseconds
long long sleep_ns = (diff_ticks * 1000000000LL) / cnt_hz;
if (sleep_ns > 0) {
struct timespec sleep_ts = { .tv_sec = sleep_ns / 1000000000LL, .tv_nsec = sleep_ns % 1000000000LL };
// Add sleep_ts to current time to get absolute wake time
struct timespec abs_wakeup_ts;
timespec_add(&abs_wakeup_ts, &now, &sleep_ts);
// Busy-wait for small remaining time if nanosleep overshoots
// int ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &abs_wakeup_ts, NULL);
// if (ret != 0 && ret != EINTR) {
// perror("clock_nanosleep in PWM thread");
// }
// // Simple busy-wait to catch up if nanosleep was short
// while(read_cntpct() < next_period_start); // Add a small grace period?
// Simple busy wait is often preferred in very tight RT loops
// to avoid scheduling delays of nanosleep.
while(read_cntpct() < next_period_start);
} else {
// If diff_ticks is 0 or negative, we are already late
// printf("PWM thread is late. Target: %llu, Current: %llu\n", next_period_start, current_ticks);
}
} else {
// If diff_ticks is 0 or negative, we are already late
// printf("PWM thread is late. Target: %llu, Current: %llu\n", next_period_start, current_ticks);
}
next_period_start += period_ticks; // Schedule the start of the *next* period
// Read shared control values with mutex
pthread_mutex_lock(&mutex);
duty = pwm_duty_cycle;
current_mode = mode;
pthread_mutex_unlock(&mutex);
// Calculate high time ticks based on duty cycle
uint64_t high_ticks = (period_ticks * duty) / 100;
// Set GPIOs
if (current_mode == 1) { // Heating mode
reg_write(gpio, PE_DAT, MODE_PIN, MODE_PIN); // PE0 high
if (duty > 0) {
reg_write(gpio, PB_DAT, 0, PWM_PIN); // PB5 high for high time
} else {
reg_write(gpio, PB_DAT, PWM_PIN, 0); // PB5 low (0% duty)
}
} else { // Cooling mode (or Idle)
reg_write(gpio, PE_DAT, MODE_PIN, 0); // PE0 low (assumed cooler/fan enable)
reg_write(gpio, PB_DAT, PWM_PIN, 0); // PB5 low (Heater always off in this mode)
high_ticks = 0; // Force 0 high time for heater PWM in cool mode
}
// Busy-wait for high time (only relevant if mode is heating and duty > 0)
if (high_ticks > 0) {
uint64_t high_time_end = next_period_start - period_ticks + high_ticks; // Calculate absolute end time for high pulse
while (read_cntpct() < high_time_end);
reg_write(gpio, PB_DAT, PWM_PIN, 0); // PB5 low for low time
}
// Wait for the end of the period (rest of the time)
// The main period timing is handled by waiting for `next_period_start` at the top of the loop.
}
return NULL;
}
// تابع محاسبه PID
double computePID(PID *pid, double setpoint, double measured, double dt, int invertError, double feedforward) {
double error = invertError ? (measured - setpoint) : (setpoint - measured);
// Proportional term
double p_term = pid->Kp * error;
// Integral term
pid->integral += error * dt;
// Apply integral windup limit
if (pid->integral > pid->integralLimit) {
pid->integral = pid->integralLimit;
} else if (pid->integral < -pid->integralLimit) {
pid->integral = -pid->integralLimit;
}
double i_term = pid->Ki * pid->integral;
// Derivative term (using derivative of error)
// Add simple filtering to derivative term to reduce noise sensitivity
double raw_derivative = (error - pid->prevError) / dt;
// Using a simple exponential moving average filter (alpha typically 0 to 1)
// alpha = 1 means no filtering, alpha = 0 means no derivative
// Choose alpha based on desired filtering strength. 0.8 is a common value.
double alpha = 0.8;
pid->derivative = alpha * raw_derivative + (1.0 - alpha) * pid->derivative; // Filtered derivative
double d_term = pid->Kd * pid->derivative;
// Store current error for next iteration
pid->prevError = error;
// Combine terms and add feedforward
double output = p_term + i_term + d_term + feedforward;
return output;
}
// فیدفوروارد (مثال ساده بر اساس هدف و دمای فعلی)
// توجه: یک فیدفوروارد موثر معمولاً به کالیبراسیون نیاز دارد
double calculate_feedforward(double targetTemp, double currentTemp) {
// این یک مثال ساده است. یک فیدفوروارد بهتر ممکن است فقط به targetTemp وابسته باشد
// و قدرت ثابتی را برای حفظ آن دما فراهم کند که باید کالیبره شود.
// این مثال کمی شبیه بخش P عمل می کند اما می تواند به پر کردن شکاف کمک کند.
// مقادیر K و bias باید با آزمایش تنظیم شوند.
double ff = 0.0;
// Add a basic bias needed to maintain temperature against ambient loss
// This bias would ideally be mapped to target temperature.
// Let's add a small constant bias for now.
double bias = 0.1; // Example bias (percentage of max power)
// Simple linear scaling example based on temperature difference
double temp_diff = targetTemp - currentTemp;
double k = 0.5; // Sensitivity
// A more setpoint-dependent FF could look like:
// if (targetTemp > 50) ff = 30; // Example: need 30% power to maintain 50C+
// else if (targetTemp > 30) ff = 15; // Example: need 15% power to maintain 30-50C
// For this example, let's use a mix or just the simple difference based approach + bias
ff = k * temp_diff + bias;
// Ensure feedforward is not negative (heater can't provide negative heat)
if (ff < 0) ff = 0;
if (ff > 100) ff = 100; // Limit feedforward output
return ff; // Return as a percentage of max power
}
// تابع timespec_add (انتقال به اینجا برای جلوگیری از خطای implicit declaration)
static inline void timespec_add(struct timespec *res, const struct timespec *a, const struct timespec *b) {
res->tv_sec = a->tv_sec + b->tv_sec;
res->tv_nsec = a->tv_nsec + b->tv_nsec;
if (res->tv_nsec >= 1000000000L) {
res->tv_sec++;
res->tv_nsec -= 1000000000L;
}
}
// تابع تنظیم خودکار ضرایب PID (Heuristic)
// این تابع PID مشخص شده را بر اساس معیارهای عملکرد تنظیم می کند
// این یک روش آزمون و خطای ساده است و نه یک متد استاندارد auto-tuning
void adjustPIDHeuristic(PID *pid_to_tune, PerformanceMetrics *metrics, const PIDBounds *bounds,
double currentTemp, double targetTemp, double dt,
double riseTimeThreshold, double overshootThreshold, double steadyStateErrorThreshold,
double kp_adjust_factor, double ki_adjust_factor, double kd_adjust_factor) {
double error = targetTemp - currentTemp;
int applied_adjustment = 0;
// Rule 1: If rise time is too slow (assuming target is > starting temp)
if (targetTemp > metrics->max_temp_during_stage && metrics->rise_time > riseTimeThreshold && metrics->rise_time_reached) {
pid_to_tune->Kp = fmin(pid_to_tune->Kp * (1.0 + kp_adjust_factor), bounds->Kp_max);
pid_to_tune->Ki = fmin(pid_to_tune->Ki * (1.0 + ki_adjust_factor), bounds->Ki_max);
printf(" [Tune] Rise time slow (%.2fs > %.2fs). Increasing Kp, Ki.\n", metrics->rise_time, riseTimeThreshold);
applied_adjustment = 1;
}
// Rule 2: If significant overshoot occurs
if (metrics->overshoot > overshootThreshold) {
pid_to_tune->Kd = fmin(pid_to_tune->Kd * (1.0 + kd_adjust_factor), bounds->Kd_max);
pid_to_tune->Kp = fmax(pid_to_tune->Kp * (1.0 - kp_adjust_factor), bounds->Kp_min); // Decrease Kp to reduce aggressiveness
// Be careful decreasing Ki, might cause steady-state error later
// pid_to_tune->Ki = fmax(pid_to_tune->Ki * (1.0 - ki_adjust_factor), bounds->Ki_min);
printf(" [Tune] Overshoot detected (%.2f°C > %.2f°C). Increasing Kd, Decreasing Kp.\n", metrics->overshoot, overshootThreshold);
applied_adjustment = 1;
}
// Rule 3: If persistent steady-state error exists (only check when near target)
// This check needs to be careful not to constantly increase Ki if the system is inherently limited (e.g., max power reached)
// Only adjust if we've been near the target for some time and error persists.
// This rule might be better applied periodically or at the end of the stable period attempt
// For now, keep it simple and check when within a band around the target.
const double steady_state_band = 1.0; // Degrees Celsius
if (fabs(error) < steady_state_band && metrics->steady_state_error_abs_avg > steadyStateErrorThreshold) {
if (pid_to_tune->Ki < bounds->Ki_max) { // Avoid increasing Ki if already at max
pid_to_tune->Ki = fmin(pid_to_tune->Ki * (1.0 + ki_adjust_factor), bounds->Ki_max);
printf(" [Tune] Persistent steady-state error (avg %.2f°C > %.2f°C). Increasing Ki.\n", metrics->steady_state_error_abs_avg, steadyStateErrorThreshold);
applied_adjustment = 1;
}
}
// Optional: Decay adjustments or use smaller steps if near bounds/optimum
// Ensure bounds are applied to Kp, Ki, Kd
pid_to_tune->Kp = fmax(bounds->Kp_min, fmin(pid_to_tune->Kp, bounds->Kp_max));
pid_to_tune->Ki = fmax(bounds->Ki_min, fmin(pid_to_tune->Ki, bounds->Ki_max));
pid_to_tune->Kd = fmax(bounds->Kd_min, fmin(pid_to_tune->Kd, bounds->Kd_max));
if (applied_adjustment) {
printf(" [Tune] New Kp: %.2f, Ki: %.3f, Kd: %.3f\n", pid_to_tune->Kp, pid_to_tune->Ki, pid_to_tune->Kd);
}
}
// تابع reachTemperature
void reachTemperature(int stageNumber, double targetTemp, int holdTimeSeconds, double pwm_min, double pwm_max,
PID *pid_heat, PID *pid_cool, KalmanFilter *kf, const PIDBounds *bounds,
double riseTimeThreshold, double overshootThreshold, double steadyStateErrorThreshold,
double kp_adjust_factor, double ki_adjust_factor, double kd_adjust_factor,
double control_dt, double stability_threshold, double rise_time_pct) {
struct timespec start_time, next_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
next_time = start_time; // Start the periodic timer from now
long stable_ms = 0;
long hold_ms = (long)holdTimeSeconds * 1000;
// Reset PID states for the new stage
resetPID(pid_heat);
resetPID(pid_cool);
// Reset performance metrics for the new stage
double currentTemp = read_temperature_thermistor(); // Get initial temp for metrics tracking
pthread_mutex_lock(&mutex);
shared_temperature = currentTemp; // Update shared temperature
pthread_mutex_unlock(&mutex);
// Apply Kalman filter to initial reading
currentTemp = kalmanUpdate(kf, currentTemp);
PerformanceMetrics metrics;
resetPerformanceMetrics(&metrics, currentTemp);
printf("\n--- شروع مرحله %d: هدف = %.1f°C, زمان نگهداری = %ds ---\n", stageNumber, targetTemp, holdTimeSeconds);
double steady_state_error_sum_stage = 0.0;
int steady_state_count_stage = 0;
while (stable_ms < hold_ms) {
// Calculate next wake up time
timespec_add(&next_time, &next_time, &(struct timespec){0, (long)(control_dt * 1e9)});
// Sleep until next wake up time
int ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next_time, NULL);
if (ret != 0 && ret != EINTR) {
perror("clock_nanosleep in reachTemperature");
// Decide how to handle error - continue or exit? Continuing might cause timing issues.
}
// --- Read Sensor ---
double rawTemp = read_temperature_thermistor();
pthread_mutex_lock(&mutex);
shared_temperature = rawTemp; // Update shared variable ASAP
pthread_mutex_unlock(&mutex);
// Apply Kalman filter
currentTemp = kalmanUpdate(kf, rawTemp);
// --- Update Performance Metrics ---
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
double elapsed_time = (now.tv_sec - start_time.tv_sec) + (now.tv_nsec - start_time.tv_nsec) / 1e9;
// Track max temperature for overshoot calculation
if (currentTemp > metrics.max_temp_during_stage) {
metrics.max_temp_during_stage = currentTemp;
}
// Calculate rise time (if target > initial temp and not already recorded)
if (targetTemp > metrics.max_temp_during_stage && !metrics.rise_time_reached && currentTemp >= targetTemp * (rise_time_pct / 100.0)) {
metrics.rise_time = elapsed_time;
metrics.rise_time_reached = 1;
}
// Calculate overshoot (only makes sense if heating towards a higher temp)
if (targetTemp > metrics.max_temp_during_stage) { // Assuming metrics.max_temp_during_stage starts at initial temp
metrics.overshoot = fmax(0.0, metrics.max_temp_during_stage - targetTemp);
} else { // Reset overshoot if cooling or target is lower
metrics.overshoot = 0.0;
}
// --- PID Control Logic ---
double error = targetTemp - currentTemp;
int currentMode = 0; // 0: Cool, 1: Heat
int dutyCycle = 0;
// Simple deadband around the target
if (error > stability_threshold) { // Heating needed
currentMode = 1; // Set mode to Heat
// Calculate feedforward
double ff = calculate_feedforward(targetTemp, currentTemp);
// Compute PID output for heating
double pidOutput = computePID(pid_heat, targetTemp, currentTemp, control_dt, 0, ff);
dutyCycle = (int)pidOutput;
// Auto-tune only the heating PID when actively heating towards a higher target
// This is a simplification; a real system might need more complex tuning logic
if (targetTemp > kf->estimate - 1.0) { // Only tune if heating *up*
adjustPIDHeuristic(pid_heat, &metrics, bounds,
currentTemp, targetTemp, control_dt,
riseTimeThreshold, overshootThreshold, steadyStateErrorThreshold,
kp_adjust_factor, ki_adjust_factor, kd_adjust_factor);
}
} else if (error < -stability_threshold) { // Cooling needed
currentMode = 0; // Set mode to Cool
// In this simple model, cooling is just turning the heater off and enabling the fan (mode=0)
// A more advanced system would use pid_cool to control fan speed or Peltier cooler power
// double pidOutput = computePID(pid_cool, targetTemp, currentTemp, control_dt, 1, 0); // Example if cooling power was controlled
dutyCycle = 0; // Heater off during cooling
} else { // Within stability band
currentMode = 0; // Set mode to Cool/Idle (Heater off)
dutyCycle = 0; // Heater off
// Track steady-state error when within the stable band
steady_state_error_sum_stage += fabs(error);
steady_state_count_stage++;
metrics.steady_state_error_abs_avg = steady_state_count_stage > 0 ?
steady_state_error_sum_stage / steady_state_count_stage : 0.0;
}
// Apply PWM limits
if (currentMode == 1) { // Only apply limits if heating
if (dutyCycle > pwm_max) dutyCycle = pwm_max;
if (dutyCycle < pwm_min) dutyCycle = pwm_min;
} else { // Ensure heater is off if not in heating mode
dutyCycle = 0;
}
// Update shared variables with mutex
pthread_mutex_lock(&mutex);
pwm_duty_cycle = dutyCycle;
mode = currentMode; // 1 for heat, 0 for cool/idle
pthread_mutex_unlock(&mutex);
// --- Check Stability ---
if (fabs(error) <= stability_threshold) {
stable_ms += (long)(control_dt * 1000);
} else {
// Reset stable time if temperature goes outside the band
stable_ms = 0;
// Optionally reset steady-state error tracking too
steady_state_error_sum_stage = 0.0;
steady_state_count_stage = 0;
}
// --- Print Status (e.g., every second) ---
static double acc_print_time = 0;
acc_print_time += control_dt;
if (acc_print_time >= 1.0) {
printf("مرحله %d - زمان: %.1fs, دما: %.2f°C (فیلترشده), خطا: %.2f°C, PWM: %d%%, حالت: %s, پایدار: %d/%dms, Kp: %.2f, Ki: %.3f, Kd: %.3f\n",
stageNumber, elapsed_time, currentTemp, error, dutyCycle, currentMode ? "گرمایش" : "سرمایش/بیکار",
stable_ms, hold_ms, pid_heat->Kp, pid_heat->Ki, pid_heat->Kd);
acc_print_time = 0;
}
// Check for abnormal temperature (optional safety)
if (currentTemp > targetTemp + 10.0) { // Example: 10 degrees above target
fprintf(stderr, "هشدار: دما به طور قابل توجهی بالاتر از هدف است! مرحله %d دما: %.2f°C هدف: %.2f°C\n",
stageNumber, currentTemp, targetTemp);
// Implement safety action: e.g., goto a safe state, log error, exit
// For now, just print warning and continue
}
}
// Stage finished - turn off power
pthread_mutex_lock(&mutex);
pwm_duty_cycle = 0;
mode = 0; // Ensure mode is off/cool state
pthread_mutex_unlock(&mutex);
printf("--- پایان مرحله %d --- دما نهایی = %.2f°C, زمان نگهداری هدف = %ds, زمان واقعی پایداری = %dms\n",
stageNumber, currentTemp, holdTimeSeconds, stable_ms);
printf(" معیارهای عملکرد این مرحله (تقریبی): زمان صعود = %.2fs, تجاوز = %.2f°C, میانگین خطای حالت ماندگار = %.2f°C\n",
metrics.rise_time_reached ? metrics.rise_time : -1.0, metrics.overshoot, metrics.steady_state_error_abs_avg);
}
// تابع main
int main() {
int numStages;
double pwm_min = 0.0;
double pwm_max = 100.0; // Assume 100% is max heater power
// Kalman Filter parameters
double Q_kalman = 0.05; // Process noise covariance
double R_kalman = 0.5; // Measurement noise covariance
double initialError_kalman = 1.0; // Initial state error
// Initial PID parameters (Heating)
double Kp_heat_initial, Ki_heat_initial, Kd_heat_initial;
// Initial PID parameters (Cooling - if used for control)
// In this revised code, cooling is ON/OFF via mode, PID only triggers it.
// So these values define the error threshold for switching to cool mode.
// Let's keep the PID struct but maybe rename/repurpose for clarity if cooling is simple ON/OFF.
// For now, assume they are used internally by the 'error < -stability_threshold' check logic.
// If you implement proportional cooling, you'd use this PID's output.
double Kp_cool_initial = 0.1; // These values from original code's initPID(pid_cool, ...)
double Ki_cool_initial = 0.25;
double Kd_cool_initial = 4.1;
double integralLimit_cool = 50.0; // Limit integral for cooling PID if used
double integralLimit_heat = 50.0; // Integral limit for heating PID
// PID Bounds for Auto-tuning
PIDBounds bounds;
// Auto-tuning parameters
double riseTimeThreshold; // Time in seconds
double overshootThreshold; // Degrees Celsius
double steadyStateErrorThreshold; // Degrees Celsius (absolute average error)
double kp_adjust_factor; // Multiplicative factor (e.g., 0.05 for 5% increase)
double ki_adjust_factor;
double kd_adjust_factor;
double rise_time_pct = 80.0; // Percentage of target temp for rise time calculation
// Control loop parameters
double control_dt = 0.25; // Control loop period in seconds (e.g., 250ms)
double stability_threshold = 0.5; // Degrees Celsius (band around target for stability check)
// --- Setup ---
setupHardware();
measure_gpadc_time(); // Measure ADC read time
// --- Read User Inputs ---
fprintf(stderr, "تعداد مراحل را وارد کنید: ");
if (scanf("%d", &numStages) != 1 || numStages <= 0) {
fprintf(stderr, "ورودی نامعتبر برای تعداد مراحل.\n");
cleanupHardware();
return EXIT_FAILURE;
}
double targetTemps[numStages];
int holdTimes[numStages];
for (int i = 0; i < numStages; i++) {
fprintf(stderr, "دمای هدف برای مرحله %d (°C): ", i + 1);
if (scanf("%lf", &targetTemps[i]) != 1) {
fprintf(stderr, "ورودی نامعتبر برای دمای هدف مرحله %d.\n", i+1);
cleanupHardware();
return EXIT_FAILURE;
}
fprintf(stderr, "زمان نگهداری برای مرحله %d (ثانیه): ", i + 1);
if (scanf("%d", &holdTimes[i]) != 1 || holdTimes[i] < 0) {
fprintf(stderr, "ورودی نامعتبر برای زمان نگهداری مرحله %d.\n", i+1);
cleanupHardware();
return EXIT_FAILURE;
}
}
fprintf(stderr, "ضریب Kp اولیه برای گرمایش: ");
if (scanf("%lf", &Kp_heat_initial) != 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "ضریب Ki اولیه برای گرمایش: ");
if (scanf("%lf", &Ki_heat_initial) != 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "ضریب Kd اولیه برای گرمایش: ");
if (scanf("%lf", &Kd_heat_initial) != 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "محدوده Kp (min max): ");
if (scanf("%lf %lf", &bounds.Kp_min, &bounds.Kp_max) != 2 || bounds.Kp_min > bounds.Kp_max || bounds.Kp_min < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "محدوده Ki (min max): ");
if (scanf("%lf %lf", &bounds.Ki_min, &bounds.Ki_max) != 2 || bounds.Ki_min > bounds.Ki_max || bounds.Ki_min < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "محدوده Kd (min max): ");
if (scanf("%lf %lf", &bounds.Kd_min, &bounds.Kd_max) != 2 || bounds.Kd_min > bounds.Kd_max || bounds.Kd_min < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "آستانه زمان صعود برای تنظیم خودکار (ثانیه): ");
if (scanf("%lf", &riseTimeThreshold) != 1 || riseTimeThreshold < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "آستانه تجاوز از هدف برای تنظیم خودکار (°C): ");
if (scanf("%lf", &overshootThreshold) != 1 || overshootThreshold < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "آستانه میانگین خطای حالت ماندگار برای تنظیم خودکار (°C): ");
if (scanf("%lf", &steadyStateErrorThreshold) != 1 || steadyStateErrorThreshold < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "ضریب افزایش Kp برای تنظیم خودکار (مثل 0.05 برای 5%%): ");
if (scanf("%lf", &kp_adjust_factor) != 1 || kp_adjust_factor <= 0 || kp_adjust_factor >= 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "ضریب افزایش Ki برای تنظیم خودکار (مثل 0.05 برای 5%%): ");
if (scanf("%lf", &ki_adjust_factor) != 1 || ki_adjust_factor <= 0 || ki_adjust_factor >= 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "ضریب افزایش Kd برای تنظیم خودکار (مثل 0.05 برای 5%%): ");
if (scanf("%lf", &kd_adjust_factor) != 1 || kd_adjust_factor <= 0 || kd_adjust_factor >= 1) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "بازه زمانی کنترل (control_dt در ثانیه، مثل 0.25): ");
if (scanf("%lf", &control_dt) != 1 || control_dt <= 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "آستانه پایداری (°C، مثلا 0.5): ");
if (scanf("%lf", &stability_threshold) != 1 || stability_threshold < 0) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
fprintf(stderr, "درصد هدف برای محاسبه زمان صعود (مثل 80 برای رسیدن به 80%% هدف): ");
if (scanf("%lf", &rise_time_pct) != 1 || rise_time_pct <= 0 || rise_time_pct > 100) { fprintf(stderr, "ورودی نامعتبر.\n"); cleanupHardware(); return EXIT_FAILURE; }
// --- Initialization ---
// Read initial temperature for Kalman filter
double initial_temp = read_temperature_thermistor();
if (initial_temp == shared_temperature && initial_temp == 0.0) {
fprintf(stderr, "خطا در خواندن اولیه دما. برنامه خارج میشود.\n");
cleanupHardware();
return EXIT_FAILURE;
}
KalmanFilter kf;
initKalman(&kf, initial_temp, initialError_kalman, Q_kalman, R_kalman);
printf("دمای اولیه (خام): %.2f°C, (فیلتر شده): %.2f°C\n", initial_temp, kf.estimate);
PID pid_heat, pid_cool;
initPID(&pid_heat, Kp_heat_initial, Ki_heat_initial, Kd_heat_initial, integralLimit_heat);
// Initialize pid_cool parameters (might not be used for control output, but determines threshold)
initPID(&pid_cool, Kp_cool_initial, Ki_cool_initial, Kd_cool_initial, integralLimit_cool);
// Set initial shared temperature after Kalman filter
pthread_mutex_lock(&mutex);
shared_temperature = kf.estimate;
pthread_mutex_unlock(&mutex);
// --- Create PWM Thread ---
pthread_t pwm_tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
// Optional: Set stack size if needed
// pthread_attr_setstacksize(&attr, 1024 * 1024); // 1MB stack
if (pthread_create(&pwm_tid, &attr, pwm_thread, NULL) != 0) {
perror("خطا در ایجاد رشته PWM");
pthread_attr_destroy(&attr);
cleanupHardware();
return EXIT_FAILURE;
}
pthread_attr_destroy(&attr);
// Pin the main control thread to a different core if available
set_affinity(1);
// Set real-time priority for the main control thread (lower than PWM)
set_realtime_priority(SCHED_FIFO, 80); // Priority 80 (lower than 95 for PWM)
printf("Main control thread started on CPU %d with priority %d.\n", sched_getcpu(), sched_getparam(0, NULL)->sched_priority);
// --- Run Thermal Cycle Stages ---
for (int i = 0; i < numStages; i++) {
reachTemperature(i + 1, targetTemps[i], holdTimes[i], pwm_min, pwm_max,
&pid_heat, &pid_cool, &kf, &bounds,
riseTimeThreshold, overshootThreshold, steadyStateErrorThreshold,
kp_adjust_factor, ki_adjust_factor, kd_adjust_factor,
control_dt, stability_threshold, rise_time_pct);
}
// --- Cleanup ---
printf("Thermal cycle finished. Stopping PWM thread...\n");
pthread_cancel(pwm_tid); // Request thread cancellation
pthread_join(pwm_tid, NULL); // Wait for thread to exit
cleanupHardware(); // Release memory mappings and reset pins
printf("پایان فرآیند ترمال سایکلر.\n");
return EXIT_SUCCESS;
}
// Implement timespec_add here if it's not in a common header included by all files
// static inline void timespec_add(struct timespec *res, const struct timespec *a, const struct timespec *b) {
// res->tv_sec = a->tv_sec + b->tv_sec;
// res->tv_nsec = a->tv_nsec + b->tv_nsec;
// if (res->tv_nsec >= 1000000000L) {
// res->tv_sec++;
// res->tv_nsec -= 1000000000L;
// }
// }