I decided to use smoothed humidity data from the DHT-22 sensor to turn a fan with DC motor on and off.
Code below combines DHT-22 data smoothing and motor response:
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 2 // sensor DHT22 data connected to Arduino pin 2
#define DHTTYPE DHT22 // using sensor DHT22
DHT dht(DHTPIN, DHTTYPE); //dht library
int chk;
int humid; //stores humidity
int tempC; //stores temperature
int tempF; //stores temp in F
//data smoothing
const int numReadings = 10;
int tempReadings [numReadings];
int tempReadIndex = 0;
int tempTotal = 0;
int tempAverage = 0;
int humReadings [numReadings];
int humReadIndex=0;
int humTotal = 0;
int humAverage = 0;
int inputPin= 2; //put sensor pin here
//detecting sensor change
int last;
//response to sensor change
//for fan and motor
int speedPin=5;
int dir1=4;
int dir2=3;
int mSpeed=0;
void setup() {
// put your setup code here, to run once:
//pins for fan and motot
pinMode(speedPin,OUTPUT);
pinMode(dir1,OUTPUT);
pinMode(dir2,OUTPUT);
//dht sensor
dht.begin();
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
tempReadings[thisReading]= 0;
humReadings[thisReading]=0;
Serial.begin(9600);
}
}
void loop() {
humid=dht.readHumidity();
tempC=dht.readTemperature();
delay(2000);
humTotal = humTotal - humReadings[humReadIndex];
humReadings[humReadIndex] = humid;
humTotal = humTotal + humReadings [humReadIndex];
humReadIndex = humReadIndex + 1;
if (humReadIndex >= numReadings) {
humReadIndex=0;
}
humAverage = humTotal / numReadings;
if (humAverage>=50)
{
digitalWrite(dir1,HIGH);
digitalWrite(dir2,LOW);
analogWrite(speedPin,255);
}
if (humAverage<50)
{
analogWrite(speedPin,0);
}
}
I finished writing the code and set up the sensor and motor. Before I could test, the wire on the motor broke off. I will need to see if I can reattach or replace with materials in the IDEATE room. I will come to office hours tomorrow to review.
