I am trying to build a fan that senses the temperature in the room and turns on a motor after the temperature sensor surpasses the room temperature. However, the temperature sensor continues to give fluctuating readings and often times the arduino serial monitor reads temperature values even when the temperature sensor is not present in the circuit. Here is the code, any assistance helpful
int led = 13; //led attached to pin 13
int motorPin = 9; //motor attached to pin 9
const int tempPin = A0; //temperature sensor attached to pin A0
float baselineTemp = 0; //Base temperature is 21 degrees celsius
int CaltempVal;
int sensorVal;
int tempVal;
float temp;
void setup() {
pinMode(led,OUTPUT); //voltage coming out of pin 13
pinMode(motorPin, OUTPUT);//votlage coming out of pin 9
Serial.begin(9600); //open serial connection to display values
Serial.println("begin");
while(millis() < 5000) { // calibrate for 5 secs
CaltempVal= analogRead(A0);
if (CaltempVal > baselineTemp){ //if the temp in the room is higher than baseline temp than temp value is new baseline temp
baselineTemp = CaltempVal;
}
}
float volt = (baselineTemp / 1024.0)* 5.0; //convert the ADC reading to voltage
float temp = (volt - .5)* 100;
Serial.print("finished, roomtemp is:");
Serial.println(temp);
}
void loop() {
int tempVal = analogRead(tempPin);
Serial.print("sensor Value:"); //print out the name serial print
Serial.print(tempVal); //send out the voltage
float voltage = (tempVal / 1024.0)* 5.0; //convert the ADC reading to voltage
Serial.print(", Volts: ");
Serial.print(voltage); //send the voltage level tout the Serial port
Serial.print(",degrees C:");
float temperature = (voltage - .5)* 100;
Serial.println(temperature); //convert the voltage in to temperature in degrees C
if (temperature <= temp +4){ // if temperature is lower or equal to room temp, the fan is off
digitalWrite(led, LOW);
digitalWrite(motorPin, LOW);
}
else if (temperature > temp + 4) { //if temperature is higher than room temp, the fan will turn on
digitalWrite(led, HIGH);
digitalWrite(motorPin,HIGH);
}
delay(500);
}
//end of loop