include<Arduino_FreeRTOS.h>
#include<task.h>
#include<semphr.h>
#define NTC_PIN A0
#define POT_PIN A1
#define FAN_PIN 9
#define BUTTON_PIN 2
#define R_REF 10000.0
#define A 0.001129148
#define B 0.000234125
#define C 0.0000000876741
volatile bool manualMode=false;
float temperature=0.0;
int dutyCycle=0;
SemaphoreHandle_t xMutex;
void TaskReadTemp(void*pvParameters){
while(1){
int adcValue=analogRead(NTC_PIN);
float voltage=(adcValue/1023.0)*3.3;
float resistance=R_REF*(3.3/voltage-1.0);
float logR=log(resistance);
float tempK=1.0/(A+B*logR+C*logR*logR*logR);
temperature=tempK-273.15;
vTaskDelay(500/portTICK_PERIOD_MS);
}}
void TaskControlPWM(void*pvParameters){
while(1){
xSemaphoreTake(xMutex,portMAX_DELAY);
if(!manualMode){
dutyCycle=map(constrain(temperature,20,40),20,40,0,255);
}else{
int potValue=analogRead(POT_PIN);
dutyCycle=map(potValue,0,1023,0,255);
}
analogWrite(FAN_PIN,dutyCycle);
xSemaphoreGive(xMutex);
vTaskDelay(200/portTICK_PERIOD_MS);
}}
void TaskHandleButton(void*pvParameters){
pinMode(BUTTON_PIN,INPUT_PULLUP);
bool lastState=HIGH;
while(1){
bool currentState=digitalRead(BUTTON_PIN);
if(currentState==LOW&&lastState==HIGH){
vTaskDelay(50/portTICK_PERIOD_MS);
if(digitalRead(BUTTON_PIN)==LOW){
xSemaphoreTake(xMutex,portMAX_DELAY);
manualMode=!manualMode;
xSemaphoreGive(xMutex);
}}
lastState=currentState;
vTaskDelay(10/portTICK_PERIOD_MS);
}}
void TaskSendSerial(void*pvParameters){
Serial.begin(9600);
while(1){
xSemaphoreTake(xMutex,portMAX_DELAY);
String modeStr=manualMode?"Manual":"Auto";
Serial.print("Mod: ");
Serial.print(modeStr);
Serial.print(", Temp: ");
Serial.print(temperature,2);
Serial.print(" C, Duty: ");
Serial.println(dutyCycle);
xSemaphoreGive(xMutex);
vTaskDelay(1000/portTICK_PERIOD_MS);
}}
void setup(){
pinMode(FAN_PIN,OUTPUT);
xMutex=xSemaphoreCreateMutex();
xTaskCreate(TaskReadTemp,"ReadTemp",128,NULL,2,NULL);
xTaskCreate(TaskControlPWM,"ControlPWM",128,NULL,2,NULL);
xTaskCreate(TaskHandleButton,"HandleButton",128,NULL,1,NULL);
xTaskCreate(TaskSendSerial,"SendSerial",128,NULL,1,NULL);
}
void loop(){}