fantube/fantube.ino

125 lines
2.7 KiB
C++

#include <Thread.h>
#include <Servo.h>
#include <dht11.h> // https://github.com/adidax/dht11
#include "HCMotor.h" // https://github.com/HobbyComponents/HCMotor/
#define DHT11PIN 4 // DHT11 - PIN 4
#define FANPIN 5 // IRF520 MOS Driver - PIN 5
#define SERVOPIN 6 // Servo - PIN 6
Servo myservo;
HCMotor fan;
dht11 DHT11;
int currenttemp = 0;
int currenthum = 0;
int fanstatus = 0;
int damperpos = 0;
bool damperstatus = false; // false - damper closed; true - damper opened
Thread checkSensorThread = Thread();
Thread ledThread = Thread();
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
checkSensorThread.onRun(sensorDataCheck);
checkSensorThread.setInterval(60000);
ledThread.onRun(ledBlink);
ledThread.setInterval(2000);
fan.Init();
fan.attach(0, DCMOTOR, FANPIN);
fan.DutyCycle(0, 100); // min and max fan rotation
delay(2222);
sensorDataCheck();
damperOpen();
fanSpeed(0);
}
void loop()
{
if (checkSensorThread.shouldRun())
checkSensorThread.run();
if (ledThread.shouldRun())
ledThread.run();
}
void sensorDataCheck()
{
sensorDataRead();
serPrintHumTemp();
if (currenttemp < 5) {
if (damperstatus) damperClose(); // <5 - damper close
} else if (!damperstatus) damperOpen(); // >4 - damper open
if (currenttemp > 25) {
if (currenttemp > 30) {
if (currenttemp > 35) {
if (currenttemp > 40) { fanSpeed(100); // >40 - fan full
} else fanSpeed(75); // >35 - fan three quarters
} else fanSpeed(50); // >30 - fan half
} else fanSpeed(30); // >25 - fan third
} else fanSpeed(0); // <26 - fan off
}
void ledBlink() {
static bool ledStatus = false;
ledStatus = !ledStatus;
digitalWrite(LED_BUILTIN, ledStatus);
}
void sensorDataRead()
{
int chk = DHT11.read(DHT11PIN);
currenthum = DHT11.humidity;
if (currenthum == 0)
{
for (int i=0; i<=5; i++)
{
delay(111);
chk = DHT11.read(DHT11PIN);
currenthum = DHT11.humidity;
if (currenthum > 0) i = 5;
}
}
currenttemp = DHT11.temperature;
}
void damperClose()
{
myservo.attach(SERVOPIN);
delay(55);
for (damperpos = 0; damperpos <= 90; damperpos += 1)
{
myservo.write(damperpos);
delay(25);
}
delay(55);
myservo.detach();
damperstatus = false;
}
void damperOpen()
{
myservo.attach(SERVOPIN);
delay(55);
for (damperpos = 90; damperpos >= 0; damperpos -= 1)
{
myservo.write(damperpos);
delay(15);
}
delay(55);
myservo.detach();
damperstatus = true;
}
void fanSpeed(int fanrate)
{
fan.OnTime(0, fanrate);
fanstatus = fanrate;
}
void serPrintHumTemp()
{
Serial.print("temp: ");
Serial.print(currenttemp);
Serial.print("; hum: ");
Serial.println(currenthum);
}